blob: 6ff42afff78f62f37c21ea1d09c796ce16708612 [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"
Kenneth Russell954ed9ce2018-04-12 23:07:0168#include "content/browser/gpu/gpu_data_manager_impl.h"
mlamouriefdca9d2014-09-16 16:55:4069#include "content/browser/manifest/manifest_manager_host.h"
Max Morin5bc74f52018-05-09 07:00:2170#include "content/browser/media/audio_stream_broker.h"
dalecurtisbc6572e12014-09-12 19:22:3071#include "content/browser/media/audio_stream_monitor.h"
miu50f97892014-09-22 22:49:5272#include "content/browser/media/capture/web_contents_audio_muter.h"
dalecurtis88c240072015-12-09 02:11:1873#include "content/browser/media/media_web_contents_observer.h"
zqzhang1adf3cb2016-11-01 11:26:4574#include "content/browser/media/session/media_session_impl.h"
Mike Wassermandabad612020-08-13 04:26:2775#include "content/browser/permissions/permission_controller_impl.h"
Yuzu Saijoa11069a2020-04-22 10:56:5576#include "content/browser/plugin_content_origin_allowlist.h"
Kevin McNee94ea52f52020-06-23 17:42:0677#include "content/browser/portal/portal.h"
Tal Pressman5dcd2382020-08-26 07:13:0578#include "content/browser/renderer_host/agent_scheduling_group_host.h"
danakje34636e2020-09-15 22:15:0079#include "content/browser/renderer_host/cross_process_frame_connector.h"
David Black9cca3592019-11-06 23:02:2280#include "content/browser/renderer_host/frame_token_message_queue.h"
danakje34636e2020-09-15 22:15:0081#include "content/browser/renderer_host/frame_tree_node.h"
82#include "content/browser/renderer_host/navigation_entry_impl.h"
83#include "content/browser/renderer_host/navigation_request.h"
84#include "content/browser/renderer_host/navigator.h"
85#include "content/browser/renderer_host/render_frame_host_impl.h"
86#include "content/browser/renderer_host/render_frame_proxy_host.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"
Rakina Zata Amni4029b6d2020-07-28 02:36:20153#include "media/base/media_switches.h"
Max Morinddebb972018-09-20 10:04:14154#include "media/base/user_input_monitor.h"
wjmaclean64951902016-04-29 20:59:12155#include "net/base/url_util.h"
[email protected]8bfc8272013-09-09 20:10:53156#include "net/http/http_cache.h"
157#include "net/http/http_transaction_factory.h"
David Van Clevef99881632020-07-16 19:41:13158#include "net/http/http_util.h"
rhalavati0fbaeef32017-06-01 15:56:30159#include "net/traffic_annotation/network_traffic_annotation.h"
Scott Violet02e38b92018-03-27 23:42:14160#include "ppapi/buildflags/buildflags.h"
Mounir Lamourifd9dcefa2017-07-06 10:26:55161#include "services/metrics/public/cpp/ukm_recorder.h"
John Abd-El-Malekb175a612018-12-03 20:11:58162#include "services/network/public/cpp/features.h"
arthursonzognib93a4472020-04-10 07:38:00163#include "services/network/public/cpp/web_sandbox_flags.h"
164#include "services/network/public/mojom/web_sandbox_flags.mojom.h"
rockot734fb662016-10-15 16:41:30165#include "services/service_manager/public/cpp/interface_provider.h"
Becca Hughes6daf5662018-06-27 16:50:54166#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
Blink Reformata30d4232018-04-07 15:31:06167#include "third_party/blink/public/common/mime_util/mime_util.h"
danakj938b37a62019-09-24 18:35:54168#include "third_party/blink/public/common/page/page_zoom.h"
Sergio Villar Senin9d9d4f52019-10-15 10:57:57169#include "third_party/blink/public/common/security/security_style.h"
Gyuyoung Kim1ac4ca782020-09-11 03:32:51170#include "third_party/blink/public/common/web_preferences/web_preferences.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>;
Fergal Daly55b6d722020-09-11 07:56:33301 ~CloseDialogCallbackWrapper() = default;
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
Fergal Daly55b6d722020-09-11 07:56:33532 for (const auto& it : session_storage_namespace_map) {
533 new_contents->GetController().SetSessionStorageNamespace(it.first,
534 it.second.get());
[email protected]fdac6ade2013-07-20 01:06:30535 }
536
Sean Toppingbbc4a2bd2019-01-30 02:16:14537 WebContentsImpl* outer_web_contents = nullptr;
Sam McNally69a33772018-06-27 16:54:12538 if (params.guest_delegate) {
539 // This makes |new_contents| act as a guest.
540 // For more info, see comment above class BrowserPluginGuest.
Albert J. Wongc55cc64d2018-10-12 02:50:04541 BrowserPluginGuest::CreateInWebContents(new_contents.get(),
542 params.guest_delegate);
Sean Toppingbbc4a2bd2019-01-30 02:16:14543 outer_web_contents = static_cast<WebContentsImpl*>(
544 params.guest_delegate->GetOwnerWebContents());
Sam McNally69a33772018-06-27 16:54:12545 }
546
[email protected]54944cde2012-12-09 09:24:59547 new_contents->Init(params);
Sean Toppingbbc4a2bd2019-01-30 02:16:14548 if (outer_web_contents)
549 outer_web_contents->InnerWebContentsCreated(new_contents.get());
[email protected]d1198fd2012-08-13 22:50:19550 return new_contents;
[email protected]a81343d232011-12-27 07:39:20551}
[email protected]746d3052012-05-22 15:15:47552
benwells5e7260d2017-03-20 23:36:33553void WebContentsImpl::FriendWrapper::AddCreatedCallbackForTesting(
nickf9acfbe2014-12-23 19:12:37554 const CreatedCallback& callback) {
[email protected]cbb1ef592013-06-05 19:49:46555 g_created_callbacks.Get().push_back(callback);
556}
557
benwells5e7260d2017-03-20 23:36:33558void WebContentsImpl::FriendWrapper::RemoveCreatedCallbackForTesting(
nickf9acfbe2014-12-23 19:12:37559 const CreatedCallback& callback) {
[email protected]cbb1ef592013-06-05 19:49:46560 for (size_t i = 0; i < g_created_callbacks.Get().size(); ++i) {
Robert Liao1db5a352019-06-05 20:57:34561 if (g_created_callbacks.Get().at(i) == callback) {
[email protected]cbb1ef592013-06-05 19:49:46562 g_created_callbacks.Get().erase(g_created_callbacks.Get().begin() + i);
563 return;
564 }
565 }
566}
567
avidf38c952015-10-27 13:45:13568WebContents* WebContents::FromRenderViewHost(RenderViewHost* rvh) {
Alexander Timin5fdeff22020-09-08 09:20:37569 OPTIONAL_TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
570 "WebContents::FromRenderViewHost", "render_view_host",
571 rvh);
avidf38c952015-10-27 13:45:13572 if (!rvh)
573 return nullptr;
[email protected]746d3052012-05-22 15:15:47574 return rvh->GetDelegate()->GetAsWebContents();
575}
576
[email protected]a86c0e962013-12-17 17:10:39577WebContents* WebContents::FromRenderFrameHost(RenderFrameHost* rfh) {
Alexander Timin5fdeff22020-09-08 09:20:37578 OPTIONAL_TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
579 "WebContents::FromRenderFrameHost", "render_frame_host",
580 base::trace_event::ToTracedValue(rfh));
avidf38c952015-10-27 13:45:13581 if (!rfh)
582 return nullptr;
Alexander Timin33bd754c02020-03-10 22:50:18583 if (!rfh->IsCurrent() && base::FeatureList::IsEnabled(
584 kCheckWebContentsAccessFromNonCurrentFrame)) {
585 // TODO(crbug.com/1059903): return nullptr here eventually.
586 base::debug::DumpWithoutCrashing();
587 }
avidf38c952015-10-27 13:45:13588 return static_cast<RenderFrameHostImpl*>(rfh)->delegate()->GetAsWebContents();
[email protected]a86c0e962013-12-17 17:10:39589}
590
ananta4b7467a52016-09-23 01:42:38591WebContents* WebContents::FromFrameTreeNodeId(int frame_tree_node_id) {
Alexander Timin5fdeff22020-09-08 09:20:37592 OPTIONAL_TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
593 "WebContents::FromFrameTreeNodeId",
594 "frame_tree_node_id", frame_tree_node_id);
ananta4b7467a52016-09-23 01:42:38595 FrameTreeNode* frame_tree_node =
596 FrameTreeNode::GloballyFindByID(frame_tree_node_id);
anantab8cfa3b2016-10-14 22:43:19597 if (!frame_tree_node)
598 return nullptr;
jam8c4edd02017-05-06 18:50:33599 return WebContentsImpl::FromFrameTreeNode(frame_tree_node);
ananta4b7467a52016-09-23 01:42:38600}
601
leon.han552e9de2017-02-09 14:37:30602void WebContents::SetScreenOrientationDelegate(
603 ScreenOrientationDelegate* delegate) {
604 ScreenOrientationProvider::SetDelegate(delegate);
605}
606
[email protected]7fff43e2013-05-21 20:21:10607// WebContentsImpl::DestructionObserver ----------------------------------------
608
609class WebContentsImpl::DestructionObserver : public WebContentsObserver {
610 public:
611 DestructionObserver(WebContentsImpl* owner, WebContents* watched_contents)
Fergal Daly09d6c762020-05-29 02:05:18612 : WebContentsObserver(watched_contents), owner_(owner) {}
[email protected]7fff43e2013-05-21 20:21:10613
614 // WebContentsObserver:
dchengc2282aa2014-10-21 12:07:58615 void WebContentsDestroyed() override {
[email protected]12a46832014-05-09 13:35:58616 owner_->OnWebContentsDestroyed(
617 static_cast<WebContentsImpl*>(web_contents()));
[email protected]7fff43e2013-05-21 20:21:10618 }
619
620 private:
621 WebContentsImpl* owner_;
622
623 DISALLOW_COPY_AND_ASSIGN(DestructionObserver);
624};
625
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:50626// TODO(sreejakshetty): Make |WebContentsImpl::ColorChooser| per-frame instead
627// of WebContents-owned.
Joel Hockey85b379d2017-12-11 10:42:13628// WebContentsImpl::ColorChooser ----------------------------------------------
Joel Hockey163835a2017-12-20 11:51:57629class WebContentsImpl::ColorChooser : public blink::mojom::ColorChooser {
Joel Hockey85b379d2017-12-11 10:42:13630 public:
631 ColorChooser(content::ColorChooser* chooser,
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20632 mojo::PendingReceiver<blink::mojom::ColorChooser> receiver,
633 mojo::PendingRemote<blink::mojom::ColorChooserClient> client)
Joel Hockey85b379d2017-12-11 10:42:13634 : chooser_(chooser),
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20635 receiver_(this, std::move(receiver)),
Joel Hockey85b379d2017-12-11 10:42:13636 client_(std::move(client)) {
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20637 receiver_.set_disconnect_handler(
Joel Hockey85b379d2017-12-11 10:42:13638 base::BindOnce([](content::ColorChooser* chooser) { chooser->End(); },
639 base::Unretained(chooser)));
640 }
[email protected]8ed16472014-04-11 19:02:48641
Joel Hockey85b379d2017-12-11 10:42:13642 ~ColorChooser() override { chooser_->End(); }
[email protected]8ed16472014-04-11 19:02:48643
Joel Hockey85b379d2017-12-11 10:42:13644 void SetSelectedColor(SkColor color) override {
Alexander Timin5fdeff22020-09-08 09:20:37645 OPTIONAL_TRACE_EVENT0("content",
646 "WebContentsImpl::ColorChooser::SetSelectedColor");
Joel Hockey85b379d2017-12-11 10:42:13647 chooser_->SetSelectedColor(color);
648 }
649
650 void DidChooseColorInColorChooser(SkColor color) {
Alexander Timin5fdeff22020-09-08 09:20:37651 OPTIONAL_TRACE_EVENT0(
652 "content",
653 "WebContentsImpl::ColorChooser::DidChooseColorInColorChooser");
Joel Hockey85b379d2017-12-11 10:42:13654 client_->DidChooseColor(color);
655 }
656
657 private:
658 // Color chooser that was opened by this tab.
659 std::unique_ptr<content::ColorChooser> chooser_;
660
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20661 // mojo receiver.
662 mojo::Receiver<blink::mojom::ColorChooser> receiver_;
Joel Hockey85b379d2017-12-11 10:42:13663
664 // mojo renderer client.
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20665 mojo::Remote<blink::mojom::ColorChooserClient> client_;
Joel Hockey85b379d2017-12-11 10:42:13666};
nicka0ac8382016-12-15 23:59:23667
lazyboy6ec48b2a2015-06-29 15:18:14668// WebContentsImpl::WebContentsTreeNode ----------------------------------------
lfg601233692017-03-06 22:45:44669WebContentsImpl::WebContentsTreeNode::WebContentsTreeNode(
670 WebContentsImpl* current_web_contents)
671 : current_web_contents_(current_web_contents),
672 outer_web_contents_(nullptr),
lazyboy6ec48b2a2015-06-29 15:18:14673 outer_contents_frame_tree_node_id_(
avallee0206f782016-07-28 18:55:33674 FrameTreeNode::kFrameTreeNodeInvalidId),
lfg601233692017-03-06 22:45:44675 focused_web_contents_(current_web_contents) {}
lazyboy6ec48b2a2015-06-29 15:18:14676
Fergal Daly55b6d722020-09-11 07:56:33677WebContentsImpl::WebContentsTreeNode::~WebContentsTreeNode() = default;
lazyboy6ec48b2a2015-06-29 15:18:14678
Lucas Furukawa Gadani99125822019-01-03 15:41:49679std::unique_ptr<WebContents>
680WebContentsImpl::WebContentsTreeNode::DisconnectFromOuterWebContents() {
Alexander Timin5fdeff22020-09-08 09:20:37681 OPTIONAL_TRACE_EVENT0("content",
682 "WebContentsTreeNode::DisconnectFromOuterWebContents");
Lucas Furukawa Gadani99125822019-01-03 15:41:49683 std::unique_ptr<WebContents> inner_contents =
684 outer_web_contents_->node_.DetachInnerWebContents(current_web_contents_);
685 OuterContentsFrameTreeNode()->RemoveObserver(this);
686 outer_contents_frame_tree_node_id_ = FrameTreeNode::kFrameTreeNodeInvalidId;
687 outer_web_contents_ = nullptr;
688 return inner_contents;
689}
690
paulmeyerfeafc2d2017-04-25 21:46:40691void WebContentsImpl::WebContentsTreeNode::AttachInnerWebContents(
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:50692 std::unique_ptr<WebContents> inner_web_contents,
693 RenderFrameHostImpl* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:37694 OPTIONAL_TRACE_EVENT0("content",
695 "WebContentsTreeNode::AttachInnerWebContents");
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:50696 WebContentsImpl* inner_web_contents_impl =
697 static_cast<WebContentsImpl*>(inner_web_contents.get());
698 WebContentsTreeNode& inner_web_contents_node = inner_web_contents_impl->node_;
699
700 inner_web_contents_node.focused_web_contents_ = nullptr;
701 inner_web_contents_node.outer_web_contents_ = current_web_contents_;
702 inner_web_contents_node.outer_contents_frame_tree_node_id_ =
703 render_frame_host->frame_tree_node()->frame_tree_node_id();
704
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18705 inner_web_contents_.push_back(std::move(inner_web_contents));
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:50706
707 render_frame_host->frame_tree_node()->AddObserver(&inner_web_contents_node);
Jeremy Roman03ce13ce2020-05-29 22:16:57708 current_web_contents_->InnerWebContentsAttached(inner_web_contents_impl);
paulmeyerfeafc2d2017-04-25 21:46:40709}
710
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18711std::unique_ptr<WebContents>
712WebContentsImpl::WebContentsTreeNode::DetachInnerWebContents(
paulmeyerfeafc2d2017-04-25 21:46:40713 WebContentsImpl* inner_web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:37714 OPTIONAL_TRACE_EVENT0(
715 "content",
716 "WebContentsImpl::WebContentsTreeNode::DetachInnerWebContents");
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18717 std::unique_ptr<WebContents> detached_contents;
718 for (std::unique_ptr<WebContents>& web_contents : inner_web_contents_) {
719 if (web_contents.get() == inner_web_contents) {
720 detached_contents = std::move(web_contents);
721 std::swap(web_contents, inner_web_contents_.back());
722 inner_web_contents_.pop_back();
Jeremy Roman03ce13ce2020-05-29 22:16:57723 current_web_contents_->InnerWebContentsDetached(inner_web_contents);
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18724 return detached_contents;
725 }
726 }
727
728 NOTREACHED();
729 return nullptr;
paulmeyerfeafc2d2017-04-25 21:46:40730}
731
lfga3e2bdc2017-03-07 20:44:01732FrameTreeNode*
733WebContentsImpl::WebContentsTreeNode::OuterContentsFrameTreeNode() const {
734 return FrameTreeNode::GloballyFindByID(outer_contents_frame_tree_node_id_);
lfg601233692017-03-06 22:45:44735}
736
lfga3e2bdc2017-03-07 20:44:01737void WebContentsImpl::WebContentsTreeNode::OnFrameTreeNodeDestroyed(
738 FrameTreeNode* node) {
Alexander Timin5fdeff22020-09-08 09:20:37739 OPTIONAL_TRACE_EVENT0("content",
740 "WebContentsTreeNode::OnFrameTreeNodeDestroyed");
lfga3e2bdc2017-03-07 20:44:01741 DCHECK_EQ(outer_contents_frame_tree_node_id_, node->frame_tree_node_id())
742 << "WebContentsTreeNode should only receive notifications for the "
743 "FrameTreeNode in its outer WebContents that hosts it.";
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18744
745 // Deletes |this| too.
746 outer_web_contents_->node_.DetachInnerWebContents(current_web_contents_);
lazyboy6ec48b2a2015-06-29 15:18:14747}
748
avallee0206f782016-07-28 18:55:33749void WebContentsImpl::WebContentsTreeNode::SetFocusedWebContents(
750 WebContentsImpl* web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:37751 OPTIONAL_TRACE_EVENT0("content",
752 "WebContentsTreeNode::SetFocusedWebContents");
avallee0206f782016-07-28 18:55:33753 DCHECK(!outer_web_contents())
754 << "Only the outermost WebContents tracks focus.";
755 focused_web_contents_ = web_contents;
756}
757
paulmeyerfeafc2d2017-04-25 21:46:40758WebContentsImpl*
759WebContentsImpl::WebContentsTreeNode::GetInnerWebContentsInFrame(
760 const FrameTreeNode* frame) {
761 auto ftn_id = frame->frame_tree_node_id();
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18762 for (auto& contents : inner_web_contents_) {
763 WebContentsImpl* impl = static_cast<WebContentsImpl*>(contents.get());
764 if (impl->node_.outer_contents_frame_tree_node_id() == ftn_id) {
765 return impl;
paulmeyerfeafc2d2017-04-25 21:46:40766 }
767 }
768 return nullptr;
769}
770
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18771std::vector<WebContentsImpl*>
772WebContentsImpl::WebContentsTreeNode::GetInnerWebContents() const {
773 std::vector<WebContentsImpl*> inner_web_contents;
774 for (auto& contents : inner_web_contents_)
775 inner_web_contents.push_back(static_cast<WebContentsImpl*>(contents.get()));
776
777 return inner_web_contents;
paulmeyerfeafc2d2017-04-25 21:46:40778}
779
Alexander Timin90c20c32020-08-12 15:28:32780// WebContentsObserverList -----------------------------------------------------
781WebContentsImpl::WebContentsObserverList::WebContentsObserverList() = default;
782WebContentsImpl::WebContentsObserverList::~WebContentsObserverList() = default;
783
784void WebContentsImpl::WebContentsObserverList::AddObserver(
785 WebContentsObserver* observer) {
786 observers_.AddObserver(observer);
787}
788
789void WebContentsImpl::WebContentsObserverList::RemoveObserver(
790 WebContentsObserver* observer) {
791 observers_.RemoveObserver(observer);
792}
793
[email protected]b172aee2012-04-10 17:05:26794// WebContentsImpl -------------------------------------------------------------
[email protected]420ae012009-04-24 05:16:32795
alexmose201c7cd2015-06-10 17:14:21796WebContentsImpl::WebContentsImpl(BrowserContext* browser_context)
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28797 : delegate_(nullptr),
[email protected]69e797f2013-04-30 01:10:22798 controller_(this, browser_context),
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28799 render_view_host_delegate_view_(nullptr),
alexmose201c7cd2015-06-10 17:14:21800 created_with_opener_(false),
Lucas Furukawa Gadani99125822019-01-03 15:41:49801 node_(this),
Fergal Daly09d6c762020-05-29 02:05:18802 frame_tree_(&controller_, this, this, this, this, this),
[email protected]6dfed692014-05-22 04:18:03803 is_load_to_different_document_(false),
[email protected]443b80e2010-12-14 00:42:23804 crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING),
805 crashed_error_code_(0),
[email protected]d5f942ba2008-09-26 19:30:34806 waiting_for_response_(false),
[email protected]fcf75d42013-12-03 20:11:26807 load_state_(net::LOAD_STATE_IDLE, base::string16()),
[email protected]094e5b22009-09-25 04:23:56808 upload_size_(0),
809 upload_position_(0),
dfalcantarae6b7b46752015-07-10 18:14:16810 is_resume_pending_(false),
[email protected]b4c84012014-04-28 19:51:10811 has_accessed_initial_document_(false),
Collin Bakerc5259962019-11-14 17:51:58812 visible_capturer_count_(0),
813 hidden_capturer_count_(0),
[email protected]fdd61c62009-04-22 19:22:57814 is_being_destroyed_(false),
815 notify_disconnection_(false),
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28816 dialog_manager_(nullptr),
[email protected]7ab1e7d62009-10-14 23:32:01817 is_showing_before_unload_dialog_(false),
gab0dccfef2015-05-20 18:43:39818 last_active_time_(base::TimeTicks::Now()),
[email protected]ebf40a72010-07-22 01:46:38819 closed_by_user_gesture_(false),
danakj938b37a62019-09-24 18:35:54820 minimum_zoom_percent_(
821 static_cast<int>(blink::kMinimumPageZoomFactor * 100)),
822 maximum_zoom_percent_(
823 static_cast<int>(blink::kMaximumPageZoomFactor * 100)),
w.shackleton49bcd392016-01-06 17:38:22824 zoom_scroll_remainder_(0),
alexmosc9e76ec2016-05-16 22:59:37825 fullscreen_widget_process_id_(ChildProcessHost::kInvalidUniqueID),
[email protected]5dcaf8e2013-12-28 01:31:42826 fullscreen_widget_routing_id_(MSG_ROUTING_NONE),
[email protected]0b431992014-06-24 00:08:03827 fullscreen_widget_had_focus_at_shutdown_(false),
[email protected]34ff1cfc2014-08-20 06:16:05828 force_disable_overscroll_content_(false),
[email protected]95640212014-07-26 18:14:30829 last_dialog_suppressed_(false),
waffles1c12bf402016-02-10 17:45:48830 accessibility_mode_(
Dominic Mazzoni21fb0282019-02-13 18:32:47831 GetContentClient()->browser()->GetAXModeForBrowserContext(
832 browser_context)),
avayvodcc85bbd2015-08-28 19:11:15833 audio_stream_monitor_(this),
Thomas Guilbert882c4cec2019-02-14 05:55:45834 media_web_contents_observer_(
835 std::make_unique<MediaWebContentsObserver>(this)),
mcnee336ea2c2017-05-23 22:50:59836#if !defined(OS_ANDROID)
mcnee432e47d2015-11-09 19:37:46837 page_scale_factor_is_one_(true),
mcnee336ea2c2017-05-23 22:50:59838#endif // !defined(OS_ANDROID)
qinmin72e8bd02016-10-21 19:35:37839 is_overlay_content_(false),
ekaramadf6750aa2017-06-06 18:29:42840 showing_context_menu_(false),
W. James MacLean62198672019-06-04 16:46:10841 text_autosizer_page_info_({0, 0, 1.f}),
shivanigithubcceeacf2020-03-06 20:00:27842 native_theme_observer_(this) {
Alexander Timin5fdeff22020-09-08 09:20:37843 TRACE_EVENT0("content", "WebContentsImpl::WebContentsImpl");
danakjf4b9e942019-11-29 15:43:04844 frame_tree_.SetFrameRemoveListener(base::BindRepeating(
845 &WebContentsImpl::OnFrameRemoved, base::Unretained(this)));
brettw4b461082016-11-19 18:55:16846#if BUILDFLAG(ENABLE_PLUGINS)
Fergal Daly55b6d722020-09-11 07:56:33847 pepper_playback_observer_ = std::make_unique<PepperPlaybackObserver>(this);
zqzhang181047e62016-07-01 13:37:17848#endif
blundelle75a8f92017-03-27 08:11:17849
Becca Hughes86334622018-07-09 21:29:38850#if defined(OS_ANDROID)
Elly Fong-Jonescdd7ae82019-02-20 23:26:33851 display_cutout_host_impl_ = std::make_unique<DisplayCutoutHostImpl>(this);
Becca Hughes86334622018-07-09 21:29:38852#endif
John Delaney732721e92020-02-07 23:11:27853
Alison Maher7f366dc62020-03-03 19:46:00854 ui::NativeTheme* native_theme = ui::NativeTheme::GetInstanceForWeb();
855 native_theme_observer_.Add(native_theme);
856 using_dark_colors_ = native_theme->ShouldUseDarkColors();
857 preferred_color_scheme_ = native_theme->GetPreferredColorScheme();
858
Mike Wassermanb213b9352020-04-16 00:32:34859 screen_change_monitor_ =
860 std::make_unique<ScreenChangeMonitor>(base::BindRepeating(
861 &WebContentsImpl::OnScreensChange, base::Unretained(this)));
862
John Delaney732721e92020-02-07 23:11:27863 // ConversionHost takes a weak ref on |this|, so it must be created outside of
864 // the initializer list.
Charlie Harrison405f6212020-04-14 21:57:32865 if (base::FeatureList::IsEnabled(features::kConversionMeasurement)) {
866 conversion_host_ = std::make_unique<ConversionHost>(this);
867 }
[email protected]332af7732009-03-11 13:21:35868}
initial.commit09911bf2008-07-26 23:55:29869
[email protected]b172aee2012-04-10 17:05:26870WebContentsImpl::~WebContentsImpl() {
Alexander Timin5fdeff22020-09-08 09:20:37871 TRACE_EVENT0("content", "WebContentsImpl::~WebContentsImpl");
872
creisba91ba82017-05-12 22:56:19873 // Imperfect sanity check against double free, given some crashes unexpectedly
874 // observed in the wild.
875 CHECK(!is_being_destroyed_);
876
877 // We generally keep track of is_being_destroyed_ to let other features know
878 // to avoid certain actions during destruction.
[email protected]420ae012009-04-24 05:16:32879 is_being_destroyed_ = true;
880
creis97867aa2017-02-17 18:39:45881 // A WebContents should never be deleted while it is notifying observers,
creisba91ba82017-05-12 22:56:19882 // since this will lead to a use-after-free as it continues to notify later
creis97867aa2017-02-17 18:39:45883 // observers.
Alexander Timin90c20c32020-08-12 15:28:32884 CHECK(!observers_.is_notifying_observers());
creis97867aa2017-02-17 18:39:45885
Avi Drissman33972942020-06-19 14:16:01886 FullscreenContentsSet(GetBrowserContext())->erase(this);
887
kenrb2a565f82015-09-02 20:24:59888 rwh_input_event_router_.reset();
889
Julie Jeongeun Kim7d0986172019-12-04 03:17:25890 for (auto& entry : receiver_sets_)
891 entry.second->CloseAllReceivers();
rockotf62002a2016-09-15 00:08:59892
avallee0206f782016-07-28 18:55:33893 WebContentsImpl* outermost = GetOutermostWebContents();
avallee9993fca2016-11-17 06:16:50894 if (this != outermost && ContainsOrIsFocusedWebContents()) {
avallee0206f782016-07-28 18:55:33895 // If the current WebContents is in focus, unset it.
avallee9993fca2016-11-17 06:16:50896 outermost->SetAsFocusedWebContentsIfNecessary();
avallee0206f782016-07-28 18:55:33897 }
898
Nick Carterd73635b2018-03-13 18:31:41899 if (mouse_lock_widget_)
James Hollyerd5c9de462020-03-10 19:02:45900 mouse_lock_widget_->RejectMouseLockOrUnlockIfNecessary(
901 blink::mojom::PointerLockResult::kElementDestroyed);
Nick Carterd73635b2018-03-13 18:31:41902
dcheng72be33c2016-01-21 04:11:31903 for (FrameTreeNode* node : frame_tree_.Nodes()) {
904 // Delete all RFHs pending shutdown, which will lead the corresponding RVHs
905 // to be shutdown and be deleted as well.
dcheng57e39e22016-01-21 00:25:38906 node->render_manager()->ClearRFHsPendingShutdown();
dcheng57e39e22016-01-21 00:25:38907 node->render_manager()->ClearWebUIInstances();
dcheng72be33c2016-01-21 04:11:31908 }
carlosk35f35af2015-12-01 10:55:40909
dcheng57e39e22016-01-21 00:25:38910 for (RenderWidgetHostImpl* widget : created_widgets_)
911 widget->DetachDelegate();
[email protected]b24b68a2012-09-24 21:57:26912 created_widgets_.clear();
913
[email protected]3ab9cb82011-06-03 18:02:07914 // Clear out any JavaScript state.
avi5d3b8692016-10-12 22:00:46915 if (dialog_manager_) {
avi6879fcf2017-01-21 05:27:53916 dialog_manager_->CancelDialogs(this, /*reset_state=*/true);
avi5d3b8692016-10-12 22:00:46917 }
[email protected]3ab9cb82011-06-03 18:02:07918
Joel Hockey85b379d2017-12-11 10:42:13919 color_chooser_.reset();
Rakina Zata Amni16196122018-11-14 02:14:00920 find_request_manager_.reset();
[email protected]da8543762012-03-20 08:52:20921
[email protected]420ae012009-04-24 05:16:32922 NotifyDisconnected();
[email protected]420ae012009-04-24 05:16:32923
[email protected]ca13a442012-04-17 14:00:12924 // Notify any observer that have a reference on this WebContents.
[email protected]8ff00d72012-10-23 19:12:21925 NotificationService::current()->Notify(
926 NOTIFICATION_WEB_CONTENTS_DESTROYED,
927 Source<WebContents>(this),
928 NotificationService::NoDetails());
[email protected]420ae012009-04-24 05:16:32929
Arthur Sonzogni5a9a88c2018-10-18 13:16:00930 // Destroy all subframes now. This notifies observers.
931 GetMainFrame()->ResetChildren();
[email protected]df0c843f2014-05-23 20:37:23932 GetRenderManager()->ResetProxyHosts();
[email protected]c06c58c2014-03-12 20:31:59933
clamy0e119882015-07-31 16:12:33934 // Manually call the observer methods for the root frame tree node. It is
935 // necessary to manually delete all objects tracking navigations
936 // (NavigationHandle, NavigationRequest) for observers to be properly
937 // notified of these navigations stopping before the WebContents is
938 // destroyed.
[email protected]df0c843f2014-05-23 20:37:23939 RenderFrameHostManager* root = GetRenderManager();
naskob21fe4872015-02-24 14:15:56940
Lowell Manners20250112019-10-18 15:06:15941 GetController().GetBackForwardCache().Shutdown();
942
naskob21fe4872015-02-24 14:15:56943 root->current_frame_host()->SetRenderFrameCreated(false);
clamyfc3850d2018-02-23 14:35:28944 root->current_frame_host()->ResetNavigationRequests();
clamy0e119882015-07-31 16:12:33945
Arthur Hemeryc3380172018-01-22 14:00:17946 // Do not update state as the WebContents is being destroyed.
Arthur Hemery241b9392019-10-24 11:08:41947 frame_tree_.root()->ResetNavigationRequest(true);
Arthur Hemeryc3380172018-01-22 14:00:17948 if (root->speculative_frame_host()) {
danakjf2342432019-05-15 21:46:09949 root->speculative_frame_host()->DeleteRenderFrame(
950 FrameDeleteIntention::kSpeculativeMainFrameForShutdown);
Arthur Hemeryc3380172018-01-22 14:00:17951 root->speculative_frame_host()->SetRenderFrameCreated(false);
clamyfc3850d2018-02-23 14:35:28952 root->speculative_frame_host()->ResetNavigationRequests();
clamy0e119882015-07-31 16:12:33953 }
[email protected]f273ee52013-10-18 16:05:27954
brettw4b461082016-11-19 18:55:16955#if BUILDFLAG(ENABLE_PLUGINS)
zqzhang181047e62016-07-01 13:37:17956 // Call this before WebContentsDestroyed() is broadcasted since
957 // AudioFocusManager will be destroyed after that.
958 pepper_playback_observer_.reset();
959#endif // defined(ENABLED_PLUGINS)
960
Chris Hamiltondf0d72cd2018-05-29 16:23:53961 // If audio is playing then notify external observers of the audio stream
962 // disappearing.
963 if (is_currently_audible_) {
964 is_currently_audible_ = false;
Alexander Timin90c20c32020-08-12 15:28:32965 observers_.ForEachObserver([&](WebContentsObserver* observer) {
966 observer->OnAudioStateChanged(false);
967 });
Chris Hamiltondf0d72cd2018-05-29 16:23:53968 if (GetOuterWebContents())
969 GetOuterWebContents()->OnAudioStateChanged();
970 }
971
Alexander Timin90c20c32020-08-12 15:28:32972 observers_.ForEachObserver([&](WebContentsObserver* observer) {
973 observer->FrameDeleted(root->current_frame_host());
974 });
975 observers_.ForEachObserver([&](WebContentsObserver* observer) {
976 observer->RenderViewDeleted(root->current_host());
977 });
Kevin McNee576bb5d82019-05-29 16:47:51978#if defined(OS_ANDROID)
979 // For simplicity, destroy the Java WebContents before we notify of the
980 // destruction of the WebContents.
981 ClearWebContentsAndroid();
982#endif
983
Alexander Timin90c20c32020-08-12 15:28:32984 observers_.ForEachObserver(
985 [&](WebContentsObserver* observer) { observer->WebContentsDestroyed(); });
Becca Hughesd11d6502018-07-31 17:01:28986 if (display_cutout_host_impl_)
987 display_cutout_host_impl_->WebContentsDestroyed();
988
Alexander Timin90c20c32020-08-12 15:28:32989 observers_.ForEachObserver(
990 [&](WebContentsObserver* observer) { observer->ResetWebContents(); });
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28991 SetDelegate(nullptr);
[email protected]b5a1d11c2011-02-17 03:09:42992}
993
erikchen50735fd2018-05-05 15:08:33994std::unique_ptr<WebContentsImpl> WebContentsImpl::CreateWithOpener(
[email protected]54944cde2012-12-09 09:24:59995 const WebContents::CreateParams& params,
Ian Clelland5cbaaf82017-11-27 22:00:03996 RenderFrameHostImpl* opener_rfh) {
Alexander Timin5fdeff22020-09-08 09:20:37997 OPTIONAL_TRACE_EVENT1("browser", "WebContentsImpl::CreateWithOpener",
998 "opener", base::trace_event::ToTracedValue(opener_rfh));
Ian Clelland5cbaaf82017-11-27 22:00:03999 FrameTreeNode* opener = nullptr;
1000 if (opener_rfh)
1001 opener = opener_rfh->frame_tree_node();
erikchen50735fd2018-05-05 15:08:331002 std::unique_ptr<WebContentsImpl> new_contents(
1003 new WebContentsImpl(params.browser_context));
lukasza6f8ac622017-06-06 03:10:201004 new_contents->SetOpenerForNewContents(opener, params.opener_suppressed);
alexmose201c7cd2015-06-10 17:14:211005
alexmosaedfc6f2016-01-21 23:57:381006 // If the opener is sandboxed, a new popup must inherit the opener's sandbox
1007 // flags, and these flags take effect immediately. An exception is if the
1008 // opener's sandbox flags lack the PropagatesToAuxiliaryBrowsingContexts
1009 // bit (which is controlled by the "allow-popups-to-escape-sandbox" token).
1010 // See https://html.spec.whatwg.org/#attr-iframe-sandbox.
lukasza6f8ac622017-06-06 03:10:201011 FrameTreeNode* new_root = new_contents->GetFrameTree()->root();
alexmosaedfc6f2016-01-21 23:57:381012 if (opener) {
arthursonzognib93a4472020-04-10 07:38:001013 network::mojom::WebSandboxFlags opener_flags =
Antonio Gomes7096ac02020-02-14 14:29:541014 opener_rfh->active_sandbox_flags();
arthursonzognib93a4472020-04-10 07:38:001015 const network::mojom::WebSandboxFlags inherit_flag =
1016 network::mojom::WebSandboxFlags::kPropagatesToAuxiliaryBrowsingContexts;
Ehsan Karamad39407082019-02-19 23:38:191017 bool sandbox_propagates_to_auxilary_context =
1018 (opener_flags & inherit_flag) == inherit_flag;
1019 if (sandbox_propagates_to_auxilary_context)
Charlie Hue1b77ac2019-12-13 21:30:171020 new_root->SetPendingFramePolicy({opener_flags,
1021 {} /* container_policy */,
1022 {} /* required_document_policy */});
arthursonzognib93a4472020-04-10 07:38:001023 if (opener_flags == network::mojom::WebSandboxFlags::kNone ||
Ehsan Karamad39407082019-02-19 23:38:191024 sandbox_propagates_to_auxilary_context) {
1025 // TODO(ekaramad, iclelland): Do not propagate feature policies from non-
1026 // sandboxed disowned openers (rel=noopener).
1027 // If the current page is not sandboxed, or if the sandbox is to propagate
1028 // to the popups then opener's feature policy will apply to the new popup
1029 // as well.
1030 new_root->SetOpenerFeaturePolicyState(
Ehsan Karamad34d10682019-02-26 20:55:041031 opener_rfh->feature_policy()->GetFeatureState());
alexmosaedfc6f2016-01-21 23:57:381032 }
1033 }
1034
mark a. foltzef394fce2017-10-21 09:11:021035 // Apply starting sandbox flags.
Luna Luc3fdacdf2017-11-08 04:48:531036 blink::FramePolicy frame_policy(new_root->pending_frame_policy());
mark a. foltzef394fce2017-10-21 09:11:021037 frame_policy.sandbox_flags |= params.starting_sandbox_flags;
1038 new_root->SetPendingFramePolicy(frame_policy);
Charlie Hu5ffc0152019-12-06 15:59:531039 new_root->CommitFramePolicy(frame_policy);
mark a. foltzef394fce2017-10-21 09:11:021040
alexmose201c7cd2015-06-10 17:14:211041 // This may be true even when opener is null, such as when opening blocked
1042 // popups.
alexmos090fae8e2015-05-28 17:09:281043 if (params.created_with_opener)
1044 new_contents->created_with_opener_ = true;
1045
Sean Toppingbbc4a2bd2019-01-30 02:16:141046 WebContentsImpl* outer_web_contents = nullptr;
[email protected]4858e432014-06-23 18:14:171047 if (params.guest_delegate) {
[email protected]83100cd2014-05-10 11:50:061048 // This makes |new_contents| act as a guest.
1049 // For more info, see comment above class BrowserPluginGuest.
Albert J. Wongc55cc64d2018-10-12 02:50:041050 BrowserPluginGuest::CreateInWebContents(new_contents.get(),
1051 params.guest_delegate);
Sean Toppingbbc4a2bd2019-01-30 02:16:141052 outer_web_contents = static_cast<WebContentsImpl*>(
1053 params.guest_delegate->GetOwnerWebContents());
[email protected]83100cd2014-05-10 11:50:061054 }
mark a. foltzef394fce2017-10-21 09:11:021055
[email protected]54944cde2012-12-09 09:24:591056 new_contents->Init(params);
Sean Toppingbbc4a2bd2019-01-30 02:16:141057 if (outer_web_contents)
1058 outer_web_contents->InnerWebContentsCreated(new_contents.get());
[email protected]d1198fd2012-08-13 22:50:191059 return new_contents;
1060}
1061
[email protected]95640212014-07-26 18:14:301062// static
1063std::vector<WebContentsImpl*> WebContentsImpl::GetAllWebContents() {
Alexander Timin5fdeff22020-09-08 09:20:371064 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1065 "WebContentsImpl::GetAllWebContents");
[email protected]95640212014-07-26 18:14:301066 std::vector<WebContentsImpl*> result;
dcheng59716272016-04-09 05:19:081067 std::unique_ptr<RenderWidgetHostIterator> widgets(
[email protected]95640212014-07-26 18:14:301068 RenderWidgetHostImpl::GetRenderWidgetHosts());
[email protected]95640212014-07-26 18:14:301069 while (RenderWidgetHost* rwh = widgets->GetNextHost()) {
[email protected]95640212014-07-26 18:14:301070 RenderViewHost* rvh = RenderViewHost::From(rwh);
1071 if (!rvh)
1072 continue;
1073 WebContents* web_contents = WebContents::FromRenderViewHost(rvh);
1074 if (!web_contents)
1075 continue;
avidf38c952015-10-27 13:45:131076 if (web_contents->GetRenderViewHost() != rvh)
1077 continue;
1078 // Because a WebContents can only have one current RVH at a time, there will
1079 // be no duplicate WebContents here.
1080 result.push_back(static_cast<WebContentsImpl*>(web_contents));
[email protected]95640212014-07-26 18:14:301081 }
1082 return result;
1083}
1084
clamya16aa8172015-05-26 13:07:251085// static
1086WebContentsImpl* WebContentsImpl::FromFrameTreeNode(
paulmeyerfeafc2d2017-04-25 21:46:401087 const FrameTreeNode* frame_tree_node) {
Alexander Timin5fdeff22020-09-08 09:20:371088 OPTIONAL_TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1089 "WebContentsImpl::FromFrameTreeNode", "frame_tree_node",
1090 frame_tree_node);
clamya16aa8172015-05-26 13:07:251091 return static_cast<WebContentsImpl*>(
1092 WebContents::FromRenderFrameHost(frame_tree_node->current_frame_host()));
1093}
1094
clamy0d32d6d2015-11-24 11:16:261095// static
Patrick Monette275a6f92b2020-01-09 21:05:041096WebContents* WebContentsImpl::FromRenderFrameHostID(
1097 GlobalFrameRoutingId render_frame_host_id) {
Alexander Timin5fdeff22020-09-08 09:20:371098 OPTIONAL_TRACE_EVENT2(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1099 "WebContentsImpl::FromRenderFrameHostID", "process_id",
1100 render_frame_host_id.child_id, "frame_id",
1101 render_frame_host_id.frame_routing_id);
Patrick Monette275a6f92b2020-01-09 21:05:041102 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI) ||
1103 !BrowserThread::IsThreadInitialized(BrowserThread::UI));
Patrick Monette7364e6972020-01-09 22:56:021104 RenderFrameHost* render_frame_host =
1105 RenderFrameHost::FromID(render_frame_host_id);
1106 if (!render_frame_host)
1107 return nullptr;
1108
1109 return WebContents::FromRenderFrameHost(render_frame_host);
Patrick Monette275a6f92b2020-01-09 21:05:041110}
1111
1112// static
clamy0d32d6d2015-11-24 11:16:261113WebContents* WebContentsImpl::FromRenderFrameHostID(int render_process_host_id,
1114 int render_frame_host_id) {
Patrick Monette7364e6972020-01-09 22:56:021115 return FromRenderFrameHostID(
1116 GlobalFrameRoutingId(render_process_host_id, render_frame_host_id));
clamy0d32d6d2015-11-24 11:16:261117}
1118
paulmeyerfeafc2d2017-04-25 21:46:401119// static
1120WebContentsImpl* WebContentsImpl::FromOuterFrameTreeNode(
1121 const FrameTreeNode* frame_tree_node) {
Alexander Timin5fdeff22020-09-08 09:20:371122 OPTIONAL_TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1123 "WebContentsImpl::FromOuterFrameTreeNode",
1124 "frame_tree_node", frame_tree_node);
paulmeyerfeafc2d2017-04-25 21:46:401125 return WebContentsImpl::FromFrameTreeNode(frame_tree_node)
1126 ->node_.GetInnerWebContentsInFrame(frame_tree_node);
1127}
1128
[email protected]b0936d22013-11-28 06:47:361129RenderFrameHostManager* WebContentsImpl::GetRenderManagerForTesting() {
[email protected]fa944cb82013-11-15 17:51:211130 return GetRenderManager();
[email protected]765187182012-01-11 23:59:281131}
1132
nicka0ac8382016-12-15 23:59:231133bool WebContentsImpl::OnMessageReceived(RenderViewHostImpl* render_view_host,
[email protected]7bb761892012-07-20 09:32:471134 const IPC::Message& message) {
Alexander Timin5fdeff22020-09-08 09:20:371135 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnMessageReceived",
1136 "render_view_host", render_view_host);
Alexander Timin90c20c32020-08-12 15:28:321137 for (auto& observer : observers_.observer_list()) {
Lukasz Anforowicz89f2c1b2017-08-30 21:36:461138 // TODO(nick, creis): https://crbug.com/758026: Replace all uses of this
1139 // variant of OnMessageReceived with the version that takes a
1140 // RenderFrameHost, and then delete it.
nicka0ac8382016-12-15 23:59:231141 if (observer.OnMessageReceived(message))
1142 return true;
[email protected]64ffefa2014-05-10 12:06:331143 }
[email protected]403415a2011-01-10 18:57:531144
Henrique Ferreiroba535472020-04-21 11:38:361145#if BUILDFLAG(ENABLE_PLUGINS)
[email protected]724159a2010-12-30 01:11:181146 bool handled = true;
nicka0ac8382016-12-15 23:59:231147 IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(WebContentsImpl, message, render_view_host)
nicka0ac8382016-12-15 23:59:231148 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission,
1149 OnRequestPpapiBrokerPermission)
nicka0ac8382016-12-15 23:59:231150 IPC_MESSAGE_UNHANDLED(handled = false)
1151 IPC_END_MESSAGE_MAP()
nicka0ac8382016-12-15 23:59:231152 return handled;
Henrique Ferreiroba535472020-04-21 11:38:361153#else
1154 return false;
1155#endif
nicka0ac8382016-12-15 23:59:231156}
1157
1158bool WebContentsImpl::OnMessageReceived(RenderFrameHostImpl* render_frame_host,
1159 const IPC::Message& message) {
Alexander Timin5fdeff22020-09-08 09:20:371160 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnMessageReceived",
1161 "render_frame_host",
1162 base::trace_event::ToTracedValue(render_frame_host));
1163
Alexander Timin90c20c32020-08-12 15:28:321164 for (auto& observer : observers_.observer_list()) {
nicka0ac8382016-12-15 23:59:231165 if (observer.OnMessageReceived(message, render_frame_host))
1166 return true;
1167 }
1168
1169 bool handled = true;
brettw4b461082016-11-19 18:55:161170#if BUILDFLAG(ENABLE_PLUGINS)
Hiroki Nakagawa761b9b02020-07-13 11:12:021171 IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(WebContentsImpl, message, render_frame_host)
emaxxe70f5e12015-05-29 11:26:001172 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceCreated,
1173 OnPepperInstanceCreated)
1174 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceDeleted,
1175 OnPepperInstanceDeleted)
tommyclie6633ca72014-10-31 00:40:421176 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung, OnPepperPluginHung)
zqzhang181047e62016-07-01 13:37:171177 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperStartsPlayback,
1178 OnPepperStartsPlayback)
1179 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperStopsPlayback,
1180 OnPepperStopsPlayback)
tommyclie6633ca72014-10-31 00:40:421181 IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed, OnPluginCrashed)
[email protected]724159a2010-12-30 01:11:181182 IPC_MESSAGE_UNHANDLED(handled = false)
[email protected]e44d1342014-05-16 21:29:331183 IPC_END_MESSAGE_MAP()
Hiroki Nakagawa761b9b02020-07-13 11:12:021184#else
1185 handled = false;
1186#endif
[email protected]724159a2010-12-30 01:11:181187
[email protected]724159a2010-12-30 01:11:181188 return handled;
1189}
1190
[email protected]d1198fd2012-08-13 22:50:191191NavigationControllerImpl& WebContentsImpl::GetController() {
[email protected]f5fa20e2011-12-21 22:35:561192 return controller_;
1193}
1194
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411195BrowserContext* WebContentsImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:551196 return controller_.GetBrowserContext();
[email protected]627e0512011-12-21 22:55:301197}
1198
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411199const GURL& WebContentsImpl::GetURL() {
Peter Boström101d7672018-12-15 00:43:591200 return GetVisibleURL();
[email protected]be1f56ab2011-12-22 06:55:311201}
1202
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411203const GURL& WebContentsImpl::GetVisibleURL() {
[email protected]c854a7e2013-05-21 16:42:241204 // We may not have a navigation entry yet.
[email protected]59167c22013-06-03 18:07:321205 NavigationEntry* entry = controller_.GetVisibleEntry();
[email protected]c854a7e2013-05-21 16:42:241206 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
1207}
1208
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411209const GURL& WebContentsImpl::GetLastCommittedURL() {
[email protected]c854a7e2013-05-21 16:42:241210 // We may not have a navigation entry yet.
1211 NavigationEntry* entry = controller_.GetLastCommittedEntry();
1212 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
1213}
1214
[email protected]8ff00d72012-10-23 19:12:211215WebContentsDelegate* WebContentsImpl::GetDelegate() {
[email protected]be1f56ab2011-12-22 06:55:311216 return delegate_;
1217}
1218
[email protected]8ff00d72012-10-23 19:12:211219void WebContentsImpl::SetDelegate(WebContentsDelegate* delegate) {
Alexander Timin5fdeff22020-09-08 09:20:371220 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetDelegate", "delegate",
1221 delegate);
[email protected]be1f56ab2011-12-22 06:55:311222 // TODO(cbentzel): remove this debugging code?
1223 if (delegate == delegate_)
1224 return;
1225 if (delegate_)
1226 delegate_->Detach(this);
1227 delegate_ = delegate;
[email protected]a6b73c62013-02-11 23:05:081228 if (delegate_) {
[email protected]be1f56ab2011-12-22 06:55:311229 delegate_->Attach(this);
[email protected]a6b73c62013-02-11 23:05:081230 // Ensure the visible RVH reflects the new delegate's preferences.
[email protected]86f98a22013-03-20 14:35:001231 if (view_)
[email protected]e85165c642014-06-10 14:34:311232 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
Joel Einbinder848001c2017-09-19 21:39:311233 if (GetRenderViewHost())
1234 RenderFrameDevToolsAgentHost::WebContentsCreated(this);
[email protected]a6b73c62013-02-11 23:05:081235 }
[email protected]be1f56ab2011-12-22 06:55:311236}
1237
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411238RenderFrameHostImpl* WebContentsImpl::GetMainFrame() {
[email protected]94d0cc12013-12-18 00:07:411239 return frame_tree_.root()->current_frame_host();
[email protected]60eca4eb2013-12-06 00:02:161240}
1241
nick53d5cbf2015-04-23 22:50:141242RenderFrameHostImpl* WebContentsImpl::GetFocusedFrame() {
1243 FrameTreeNode* focused_node = frame_tree_.GetFocusedFrame();
1244 if (!focused_node)
1245 return nullptr;
1246 return focused_node->current_frame_host();
[email protected]9c9343b2014-03-08 02:56:071247}
1248
rob3e2a0732016-01-06 21:22:091249RenderFrameHostImpl* WebContentsImpl::FindFrameByFrameTreeNodeId(
creisf71a2632017-05-04 19:03:501250 int frame_tree_node_id,
1251 int process_id) {
Alexander Timin5fdeff22020-09-08 09:20:371252 OPTIONAL_TRACE_EVENT2(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1253 "WebContentsImpl::FindFrameByFrameTreeNodeId",
1254 "frame_tree_node_id", frame_tree_node_id, "process_id",
1255 process_id);
creisf71a2632017-05-04 19:03:501256 FrameTreeNode* frame = frame_tree_.FindByID(frame_tree_node_id);
1257
1258 // Sanity check that this is in the caller's expected process. Otherwise a
1259 // recent cross-process navigation may have led to a privilege change that the
1260 // caller is not expecting.
1261 if (!frame ||
1262 frame->current_frame_host()->GetProcess()->GetID() != process_id)
1263 return nullptr;
1264
1265 return frame->current_frame_host();
1266}
1267
1268RenderFrameHostImpl* WebContentsImpl::UnsafeFindFrameByFrameTreeNodeId(
rob3e2a0732016-01-06 21:22:091269 int frame_tree_node_id) {
Alexander Timin5fdeff22020-09-08 09:20:371270 OPTIONAL_TRACE_EVENT1("content",
1271 "WebContentsImpl::UnsafeFindFrameByFrameTreeNodeId",
1272 "frame_tree_node_id", frame_tree_node_id);
creisf71a2632017-05-04 19:03:501273 // Beware using this! The RenderFrameHost may have changed since the caller
1274 // obtained frame_tree_node_id.
rob3e2a0732016-01-06 21:22:091275 FrameTreeNode* frame = frame_tree_.FindByID(frame_tree_node_id);
1276 return frame ? frame->current_frame_host() : nullptr;
1277}
1278
[email protected]a86c0e962013-12-17 17:10:391279void WebContentsImpl::ForEachFrame(
Lei Zhangebcc6302018-01-12 19:46:451280 const base::RepeatingCallback<void(RenderFrameHost*)>& on_frame) {
Alexander Timin5fdeff22020-09-08 09:20:371281 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1282 "WebContentsImpl::ForEachFrame");
dcheng57e39e22016-01-21 00:25:381283 for (FrameTreeNode* node : frame_tree_.Nodes()) {
1284 on_frame.Run(node->current_frame_host());
1285 }
[email protected]a86c0e962013-12-17 17:10:391286}
1287
dchengafb53e22016-02-04 08:11:081288std::vector<RenderFrameHost*> WebContentsImpl::GetAllFrames() {
Xuehui Xieb2300ae42020-06-09 20:25:051289 return GetAllFramesImpl(frame_tree_, /*include_pending=*/false);
1290}
1291
1292std::vector<RenderFrameHost*> WebContentsImpl::GetAllFramesIncludingPending() {
1293 return GetAllFramesImpl(frame_tree_, /*include_pending=*/true);
dchengafb53e22016-02-04 08:11:081294}
1295
lukaszacbdf52e2016-01-15 21:19:511296int WebContentsImpl::SendToAllFrames(IPC::Message* message) {
Alexander Timin5fdeff22020-09-08 09:20:371297 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SendToAllFrames");
Xuehui Xieb2300ae42020-06-09 20:25:051298 return SendToAllFramesImpl(frame_tree_, /*include_pending=*/false, message);
1299}
lukasza1a9ab2422016-03-02 18:47:251300
Xuehui Xieb2300ae42020-06-09 20:25:051301int WebContentsImpl::SendToAllFramesIncludingPending(IPC::Message* message) {
Alexander Timin5fdeff22020-09-08 09:20:371302 OPTIONAL_TRACE_EVENT0("content",
1303 "WebContentsImpl::SentToAllFramesIncludingPending");
Xuehui Xieb2300ae42020-06-09 20:25:051304 return SendToAllFramesImpl(frame_tree_, /*include_pending=*/true, message);
[email protected]a86c0e962013-12-17 17:10:391305}
1306
lfgdb5c4ed2016-03-04 23:09:071307void WebContentsImpl::SendPageMessage(IPC::Message* msg) {
Alexander Timin5fdeff22020-09-08 09:20:371308 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SendPageMessage");
alexmos136fd6e62016-08-15 20:58:411309 frame_tree_.root()->render_manager()->SendPageMessage(msg, nullptr);
lfgdb5c4ed2016-03-04 23:09:071310}
1311
Gyuyoung Kim877e86d2020-07-21 04:01:021312void WebContentsImpl::ExecutePageBroadcastMethod(
1313 PageBroadcastMethodCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:371314 OPTIONAL_TRACE_EVENT0("content",
1315 "WebContentsImpl::ExecutePageBroadcastMethod");
Gyuyoung Kim877e86d2020-07-21 04:01:021316 frame_tree_.root()->render_manager()->ExecutePageBroadcastMethod(callback);
1317}
1318
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411319RenderViewHostImpl* WebContentsImpl::GetRenderViewHost() {
[email protected]fa944cb82013-11-15 17:51:211320 return GetRenderManager()->current_host();
[email protected]be1f56ab2011-12-22 06:55:311321}
1322
creis89a0f782015-05-27 16:13:171323void WebContentsImpl::CancelActiveAndPendingDialogs() {
Alexander Timin5fdeff22020-09-08 09:20:371324 OPTIONAL_TRACE_EVENT0("content",
1325 "WebContentsImpl::CancelActiveAndPendingDialogs");
Evan Stade753fc202020-07-13 18:09:541326 if (dialog_manager_) {
avi6879fcf2017-01-21 05:27:531327 dialog_manager_->CancelDialogs(this, /*reset_state=*/false);
Evan Stade753fc202020-07-13 18:09:541328 }
creis89a0f782015-05-27 16:13:171329 if (browser_plugin_embedder_)
1330 browser_plugin_embedder_->CancelGuestDialogs();
1331}
1332
naskoc0fceff2015-04-30 15:53:521333void WebContentsImpl::ClosePage() {
Alexander Timin5fdeff22020-09-08 09:20:371334 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ClosePage");
naskoc0fceff2015-04-30 15:53:521335 GetRenderViewHost()->ClosePage();
1336}
1337
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411338RenderWidgetHostView* WebContentsImpl::GetRenderWidgetHostView() {
[email protected]fa944cb82013-11-15 17:51:211339 return GetRenderManager()->GetRenderWidgetHostView();
[email protected]be1f56ab2011-12-22 06:55:311340}
1341
lfg265a2672016-04-23 03:11:021342RenderWidgetHostView* WebContentsImpl::GetTopLevelRenderWidgetHostView() {
1343 if (GetOuterWebContents())
1344 return GetOuterWebContents()->GetTopLevelRenderWidgetHostView();
1345 return GetRenderManager()->GetRenderWidgetHostView();
1346}
1347
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411348RenderWidgetHostView* WebContentsImpl::GetFullscreenRenderWidgetHostView() {
vmpstr6d9996c82017-02-23 00:43:251349 if (auto* widget_host = GetFullscreenRenderWidgetHost())
ekaramadaeb3c5c2016-11-09 03:22:351350 return widget_host->GetView();
1351 return nullptr;
[email protected]4aebbca2013-09-17 22:26:491352}
1353
[email protected]8ff00d72012-10-23 19:12:211354WebContentsView* WebContentsImpl::GetView() const {
[email protected]be1f56ab2011-12-22 06:55:311355 return view_.get();
1356}
1357
Mike Wasserman5a3cc61d2020-08-27 21:12:031358void WebContentsImpl::OnScreensChange(bool is_multi_screen_changed) {
Alexander Timin5fdeff22020-09-08 09:20:371359 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnScreensChange",
1360 "is_multi_screen_changed", is_multi_screen_changed);
Mike Wasserman5a3cc61d2020-08-27 21:12:031361 // Send |is_multi_screen_changed| events to all visible frames, but limit
1362 // other events to frames with the Window Placement permission. This obviates
1363 // the most pressing need for sites to poll isMultiScreen(), which is exposed
1364 // without explicit permission, while also protecting privacy.
1365 // TODO(crbug.com/1109989): Postpone events; refine utility/privacy balance.
Mike Wassermanb213b9352020-04-16 00:32:341366 for (FrameTreeNode* node : frame_tree_.Nodes()) {
1367 RenderFrameHostImpl* rfh = node->current_frame_host();
Mike Wasserman5a3cc61d2020-08-27 21:12:031368 if ((is_multi_screen_changed &&
1369 rfh->GetVisibilityState() == PageVisibilityState::kVisible) ||
1370 WindowPlacementGranted(rfh)) {
1371 rfh->GetAssociatedLocalFrame()->OnScreensChange();
1372 }
Mike Wassermanb213b9352020-04-16 00:32:341373 }
1374}
1375
leon.han552e9de2017-02-09 14:37:301376void WebContentsImpl::OnScreenOrientationChange() {
Alexander Timin5fdeff22020-09-08 09:20:371377 OPTIONAL_TRACE_EVENT0("content",
1378 "WebContentsImpl::OnScreenOrientationChange");
leon.han552e9de2017-02-09 14:37:301379 DCHECK(screen_orientation_provider_);
Lan Weif81c6e7c2020-02-12 16:46:091380 DidChangeScreenOrientation();
Becca Hughese9e27952018-06-25 17:08:271381 screen_orientation_provider_->OnOrientationChange();
leon.hane4db177a2017-02-07 14:19:161382}
1383
Alan Cutter92d59252019-03-29 02:32:331384base::Optional<SkColor> WebContentsImpl::GetThemeColor() {
Carlos Caballero1215f882019-10-29 15:58:431385 return GetRenderViewHost()->theme_color();
yusufod41c5f92015-03-06 00:14:281386}
1387
Alan Cutterd73a15d92020-08-21 07:12:451388base::Optional<SkColor> WebContentsImpl::GetBackgroundColor() {
1389 return GetRenderViewHost()->background_color();
1390}
1391
Doug Turner63f3c7b2017-07-29 05:10:011392void WebContentsImpl::SetAccessibilityMode(ui::AXMode mode) {
Alexander Timin5fdeff22020-09-08 09:20:371393 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetAccessibilityMode",
1394 "mode", mode.ToString(), "previous_mode",
1395 accessibility_mode_.ToString());
1396
[email protected]95640212014-07-26 18:14:301397 if (mode == accessibility_mode_)
1398 return;
1399
dmazzonif8a31042016-12-03 00:52:131400 // Don't allow accessibility to be enabled for WebContents that are never
danakj77eb7e82020-01-09 19:38:461401 // user-visible, like background pages.
1402 if (IsNeverComposited())
dmazzonif8a31042016-12-03 00:52:131403 return;
1404
[email protected]95640212014-07-26 18:14:301405 accessibility_mode_ = mode;
dcheng57e39e22016-01-21 00:25:381406
1407 for (FrameTreeNode* node : frame_tree_.Nodes()) {
dmazzonif8a31042016-12-03 00:52:131408 UpdateAccessibilityModeOnFrame(node->current_frame_host());
clamy610c63b32017-12-22 15:05:181409 // Also update accessibility mode on the speculative RenderFrameHost for
1410 // this FrameTreeNode, if one exists.
Alex Moshchuk3d8a1f392017-10-24 19:01:261411 RenderFrameHost* speculative_frame_host =
1412 node->render_manager()->speculative_frame_host();
1413 if (speculative_frame_host)
1414 UpdateAccessibilityModeOnFrame(speculative_frame_host);
dcheng57e39e22016-01-21 00:25:381415 }
[email protected]95640212014-07-26 18:14:301416}
1417
Doug Turner63f3c7b2017-07-29 05:10:011418void WebContentsImpl::AddAccessibilityMode(ui::AXMode mode) {
1419 ui::AXMode new_mode(accessibility_mode_);
dougtcd3dad732017-03-14 03:26:231420 new_mode |= mode;
1421 SetAccessibilityMode(new_mode);
[email protected]95640212014-07-26 18:14:301422}
1423
Avi Drissman1e620f32018-03-16 13:57:291424// Helper class used by WebContentsImpl::RequestAXTreeSnapshot.
1425// Handles the callbacks from parallel snapshot requests to each frame,
1426// and feeds the results to an AXTreeCombiner, which converts them into a
1427// single combined accessibility tree.
1428class WebContentsImpl::AXTreeSnapshotCombiner
1429 : public base::RefCounted<AXTreeSnapshotCombiner> {
1430 public:
1431 explicit AXTreeSnapshotCombiner(AXTreeSnapshotCallback callback)
1432 : callback_(std::move(callback)) {}
1433
1434 AXTreeSnapshotCallback AddFrame(bool is_root) {
1435 // Adds a reference to |this|.
1436 return base::BindOnce(&AXTreeSnapshotCombiner::ReceiveSnapshot, this,
1437 is_root);
1438 }
1439
1440 void ReceiveSnapshot(bool is_root, const ui::AXTreeUpdate& snapshot) {
1441 combiner_.AddTree(snapshot, is_root);
1442 }
1443
1444 private:
1445 friend class base::RefCounted<AXTreeSnapshotCombiner>;
1446
1447 // This is called automatically after the last call to ReceiveSnapshot
1448 // when there are no more references to this object.
1449 ~AXTreeSnapshotCombiner() {
1450 combiner_.Combine();
1451 std::move(callback_).Run(combiner_.combined());
1452 }
1453
1454 ui::AXTreeCombiner combiner_;
1455 AXTreeSnapshotCallback callback_;
1456};
1457
1458void WebContentsImpl::RequestAXTreeSnapshot(AXTreeSnapshotCallback callback,
1459 ui::AXMode ax_mode) {
Alexander Timin5fdeff22020-09-08 09:20:371460 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RequestAXTreeSnapshot",
1461 "mode", ax_mode.ToString());
dmazzonid95ae842016-04-12 21:17:391462 // Send a request to each of the frames in parallel. Each one will return
1463 // an accessibility tree snapshot, and AXTreeSnapshotCombiner will combine
1464 // them into a single tree and call |callback| with that result, then
1465 // delete |combiner|.
Avi Drissman1e620f32018-03-16 13:57:291466 FrameTreeNode* root_node = frame_tree_.root();
tzik58faa742018-08-01 10:54:181467 auto combiner =
1468 base::MakeRefCounted<AXTreeSnapshotCombiner>(std::move(callback));
Avi Drissman1e620f32018-03-16 13:57:291469
tzik58faa742018-08-01 10:54:181470 RecursiveRequestAXTreeSnapshotOnFrame(root_node, combiner.get(), ax_mode);
Avi Drissman1e620f32018-03-16 13:57:291471}
1472
1473void WebContentsImpl::RecursiveRequestAXTreeSnapshotOnFrame(
1474 FrameTreeNode* root_node,
1475 AXTreeSnapshotCombiner* combiner,
1476 ui::AXMode ax_mode) {
Alexander Timin5fdeff22020-09-08 09:20:371477 OPTIONAL_TRACE_EVENT0(
1478 "content", "WebContentsImpl::RecursiveRequestAXTreeSnapshotOnFrame");
dmazzonid95ae842016-04-12 21:17:391479 for (FrameTreeNode* frame_tree_node : frame_tree_.Nodes()) {
Avi Drissman1e620f32018-03-16 13:57:291480 WebContentsImpl* inner_contents =
1481 node_.GetInnerWebContentsInFrame(frame_tree_node);
1482 if (inner_contents) {
1483 inner_contents->RecursiveRequestAXTreeSnapshotOnFrame(root_node, combiner,
1484 ax_mode);
1485 } else {
1486 bool is_root = frame_tree_node == root_node;
1487 frame_tree_node->current_frame_host()->RequestAXTreeSnapshot(
1488 combiner->AddFrame(is_root), ax_mode);
1489 }
dmazzonid95ae842016-04-12 21:17:391490 }
dmazzoni83ba5c82015-04-14 07:11:511491}
1492
Becca Hughes3b5a43482018-07-17 22:31:551493void WebContentsImpl::NotifyViewportFitChanged(
1494 blink::mojom::ViewportFit value) {
Alexander Timin5fdeff22020-09-08 09:20:371495 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::NotifyViewportFitChanged",
1496 "value", static_cast<int>(value));
Alexander Timin90c20c32020-08-12 15:28:321497 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1498 observer->ViewportFitChanged(value);
1499 });
Becca Hughes3b5a43482018-07-17 22:31:551500}
1501
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411502FindRequestManager* WebContentsImpl::GetFindRequestManagerForTesting() {
Ehsan Karamad6beb2ea2018-11-25 18:15:131503 return GetFindRequestManager();
1504}
1505
mcnee336ea2c2017-05-23 22:50:591506#if !defined(OS_ANDROID)
akabac6bd1212018-06-25 20:10:481507void WebContentsImpl::UpdateZoom() {
Alexander Timin5fdeff22020-09-08 09:20:371508 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::UpdateZoom");
akabac6bd1212018-06-25 20:10:481509 RenderWidgetHostImpl* rwh = GetRenderViewHost()->GetWidget();
1510 if (rwh->GetView())
1511 rwh->SynchronizeVisualProperties();
wjmaclean64951902016-04-29 20:59:121512}
1513
wjmaclean64951902016-04-29 20:59:121514
1515void WebContentsImpl::UpdateZoomIfNecessary(const std::string& scheme,
akabac6bd1212018-06-25 20:10:481516 const std::string& host) {
Alexander Timin5fdeff22020-09-08 09:20:371517 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::UpdateZoomIfNecessary",
1518 "scheme", scheme, "host", host);
wjmaclean64951902016-04-29 20:59:121519 NavigationEntry* entry = GetController().GetLastCommittedEntry();
1520 if (!entry)
1521 return;
1522
1523 GURL url = HostZoomMap::GetURLFromEntry(entry);
1524 if (host != net::GetHostOrSpecFromURL(url) ||
1525 (!scheme.empty() && !url.SchemeIs(scheme))) {
1526 return;
1527 }
1528
akabac6bd1212018-06-25 20:10:481529 UpdateZoom();
wjmaclean64951902016-04-29 20:59:121530}
mcnee336ea2c2017-05-23 22:50:591531#endif // !defined(OS_ANDROID)
wjmaclean64951902016-04-29 20:59:121532
Julie Jeongeun Kim7d0986172019-12-04 03:17:251533base::OnceClosure WebContentsImpl::AddReceiverSet(
rockotf62002a2016-09-15 00:08:591534 const std::string& interface_name,
Julie Jeongeun Kim7d0986172019-12-04 03:17:251535 WebContentsReceiverSet* receiver_set) {
Alexander Timin5fdeff22020-09-08 09:20:371536 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::AddReceiverSet",
1537 "interface_name", interface_name);
rockotf62002a2016-09-15 00:08:591538 auto result =
Julie Jeongeun Kim7d0986172019-12-04 03:17:251539 receiver_sets_.insert(std::make_pair(interface_name, receiver_set));
rockotf62002a2016-09-15 00:08:591540 DCHECK(result.second);
Julie Jeongeun Kim7d0986172019-12-04 03:17:251541 return base::BindOnce(&WebContentsImpl::RemoveReceiverSet,
danakjf4b9e942019-11-29 15:43:041542 weak_factory_.GetWeakPtr(), interface_name);
rockotf62002a2016-09-15 00:08:591543}
1544
Julie Jeongeun Kim7d0986172019-12-04 03:17:251545WebContentsReceiverSet* WebContentsImpl::GetReceiverSet(
rockot8bbad222017-03-22 04:34:051546 const std::string& interface_name) {
Julie Jeongeun Kim7d0986172019-12-04 03:17:251547 auto it = receiver_sets_.find(interface_name);
1548 if (it == receiver_sets_.end())
rockot8bbad222017-03-22 04:34:051549 return nullptr;
1550 return it->second;
1551}
1552
John Delaney732721e92020-02-07 23:11:271553void WebContentsImpl::RemoveReceiverSetForTesting(
1554 const std::string& interface_name) {
Alexander Timin5fdeff22020-09-08 09:20:371555 OPTIONAL_TRACE_EVENT1("content",
1556 "WebContentsImpl::RemoveReceiverSetForTesting",
1557 "interface_name", interface_name);
John Delaney732721e92020-02-07 23:11:271558 RemoveReceiverSet(interface_name);
1559}
1560
paulmeyerfeafc2d2017-04-25 21:46:401561std::vector<WebContentsImpl*> WebContentsImpl::GetWebContentsAndAllInner() {
1562 std::vector<WebContentsImpl*> all_contents(1, this);
1563
1564 for (size_t i = 0; i != all_contents.size(); ++i) {
1565 for (auto* inner_contents : all_contents[i]->GetInnerWebContents()) {
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:161566 all_contents.push_back(static_cast<WebContentsImpl*>(inner_contents));
paulmeyerfeafc2d2017-04-25 21:46:401567 }
1568 }
1569
1570 return all_contents;
1571}
1572
Sam McNally145fb172017-05-10 00:13:231573void WebContentsImpl::NotifyManifestUrlChanged(
Yuzu Saijo0c263c702020-06-08 03:41:241574 RenderFrameHost* rfh,
Sam McNally145fb172017-05-10 00:13:231575 const base::Optional<GURL>& manifest_url) {
Alexander Timin5fdeff22020-09-08 09:20:371576 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::NotifyManifestUrlChanged",
1577 "render_frame_host",
1578 base::trace_event::ToTracedValue(rfh), "manifest_url",
1579 base::trace_event::ValueToString(manifest_url));
Alexander Timin90c20c32020-08-12 15:28:321580 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1581 observer->DidUpdateWebManifestURL(rfh, manifest_url);
1582 });
Sam McNally145fb172017-05-10 00:13:231583}
1584
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411585WebUI* WebContentsImpl::GetWebUI() {
Nasko Oskov2f7d2112019-10-29 03:26:571586 WebUI* committed_web_ui = GetCommittedWebUI();
1587 if (committed_web_ui)
1588 return committed_web_ui;
1589
1590 if (GetRenderManager()->speculative_frame_host())
1591 return GetRenderManager()->speculative_frame_host()->web_ui();
1592
1593 return nullptr;
[email protected]be1f56ab2011-12-22 06:55:311594}
1595
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411596WebUI* WebContentsImpl::GetCommittedWebUI() {
carlosk35f35af2015-12-01 10:55:401597 return frame_tree_.root()->current_frame_host()->web_ui();
[email protected]d5f942ba2008-09-26 19:30:341598}
1599
Maks Orlovich73f374d2020-04-02 12:46:131600void WebContentsImpl::SetUserAgentOverride(
1601 const blink::UserAgentOverride& ua_override,
1602 bool override_in_new_tabs) {
Alexander Timin5fdeff22020-09-08 09:20:371603 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetUserAgentOverride",
1604 "ua_override", ua_override.ua_string_override,
1605 "override_in_new_tabs", override_in_new_tabs);
Maks Orlovich73f374d2020-04-02 12:46:131606 DCHECK(!ua_override.ua_metadata_override.has_value() ||
1607 !ua_override.ua_string_override.empty());
1608
1609 if (GetUserAgentOverride() == ua_override)
[email protected]bf70edce2012-06-20 22:32:221610 return;
1611
Changwan Ryuc1134a82018-03-07 02:10:141612 should_override_user_agent_in_new_tabs_ = override_in_new_tabs;
1613
Maks Orlovich73f374d2020-04-02 12:46:131614 renderer_preferences_.user_agent_override = ua_override;
[email protected]bf70edce2012-06-20 22:32:221615
Bruce Long1e3e1f542019-10-16 17:56:281616 // Send the new override string to all renderers in the current page.
1617 SyncRendererPrefs();
[email protected]bf70edce2012-06-20 22:32:221618
1619 // Reload the page if a load is currently in progress to avoid having
1620 // different parts of the page loaded using different user agents.
Scott Violete1d58cc2020-04-28 23:07:171621 // No need to reload if the current entry matches that of the
1622 // NavigationRequest supplied to DidStartNavigation() as NavigationRequest
1623 // handles it.
[email protected]6286a372013-10-09 04:03:271624 NavigationEntry* entry = controller_.GetVisibleEntry();
Scott Violete1d58cc2020-04-28 23:07:171625 if (IsLoading() && entry != nullptr && entry->GetIsOverridingUserAgent() &&
1626 (!frame_tree_.root()->navigation_request() ||
1627 frame_tree_.root()->navigation_request()->ua_change_requires_reload())) {
toyoshim6142d96f2016-12-19 09:07:251628 controller_.Reload(ReloadType::BYPASSING_CACHE, true);
Scott Violete1d58cc2020-04-28 23:07:171629 }
[email protected]8d0f3312012-08-18 01:47:531630
Alexander Timin90c20c32020-08-12 15:28:321631 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1632 observer->UserAgentOverrideSet(ua_override);
1633 });
[email protected]86ef6a392012-05-11 22:03:111634}
1635
Scott Violet2a6c5bff2020-04-29 23:59:061636void WebContentsImpl::SetRendererInitiatedUserAgentOverrideOption(
1637 NavigationController::UserAgentOverrideOption option) {
Alexander Timin5fdeff22020-09-08 09:20:371638 OPTIONAL_TRACE_EVENT0(
1639 "content",
1640 "WebContentsImpl::SetRendererInitiatedUserAgentOverrideOption");
Scott Violet2a6c5bff2020-04-29 23:59:061641 renderer_initiated_user_agent_override_option_ = option;
1642}
1643
Maks Orlovich73f374d2020-04-02 12:46:131644const blink::UserAgentOverride& WebContentsImpl::GetUserAgentOverride() {
[email protected]bf70edce2012-06-20 22:32:221645 return renderer_preferences_.user_agent_override;
[email protected]86ef6a392012-05-11 22:03:111646}
1647
Scott Violet2a6c5bff2020-04-29 23:59:061648bool WebContentsImpl::ShouldOverrideUserAgentForRendererInitiatedNavigation() {
1649 NavigationEntryImpl* current_entry = controller_.GetLastCommittedEntry();
1650 if (!current_entry)
1651 return should_override_user_agent_in_new_tabs_;
1652
1653 switch (renderer_initiated_user_agent_override_option_) {
1654 case NavigationController::UA_OVERRIDE_INHERIT:
1655 return current_entry->GetIsOverridingUserAgent();
1656 case NavigationController::UA_OVERRIDE_TRUE:
1657 return true;
1658 case NavigationController::UA_OVERRIDE_FALSE:
1659 return false;
1660 default:
1661 break;
1662 }
1663 return false;
Changwan Ryuc1134a82018-03-07 02:10:141664}
1665
dmazzonidd3d51a72016-12-14 18:41:011666void WebContentsImpl::EnableWebContentsOnlyAccessibilityMode() {
Alexander Timin5fdeff22020-09-08 09:20:371667 OPTIONAL_TRACE_EVENT0(
1668 "content", "WebContentsImpl::EnableWebContentsOnlyAccessibilityMode");
Dominic Mazzonid9fda172019-03-07 17:12:071669 // If accessibility is already enabled, we'll need to force a reset
1670 // in order to ensure new observers of accessibility events get the
1671 // full accessibility tree from scratch.
1672 bool need_reset = GetAccessibilityMode().has_mode(ui::AXMode::kWebContents);
1673
1674 ui::AXMode desired_mode =
1675 GetContentClient()->browser()->GetAXModeForBrowserContext(
1676 GetBrowserContext());
1677 desired_mode |= ui::kAXModeWebContentsOnly;
1678 AddAccessibilityMode(desired_mode);
1679
1680 if (need_reset) {
dchengafb53e22016-02-04 08:11:081681 for (RenderFrameHost* rfh : GetAllFrames())
1682 ResetAccessibility(rfh);
dchengafb53e22016-02-04 08:11:081683 }
[email protected]95640212014-07-26 18:14:301684}
1685
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411686bool WebContentsImpl::IsWebContentsOnlyAccessibilityModeForTesting() {
Doug Turner63f3c7b2017-07-29 05:10:011687 return accessibility_mode_ == ui::kAXModeWebContentsOnly;
[email protected]95640212014-07-26 18:14:301688}
1689
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411690bool WebContentsImpl::IsFullAccessibilityModeForTesting() {
Doug Turner63f3c7b2017-07-29 05:10:011691 return accessibility_mode_ == ui::kAXModeComplete;
[email protected]95640212014-07-26 18:14:301692}
1693
Becca Hughes6daf5662018-06-27 16:50:541694#if defined(OS_ANDROID)
1695
1696void WebContentsImpl::SetDisplayCutoutSafeArea(gfx::Insets insets) {
Alexander Timin5fdeff22020-09-08 09:20:371697 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetDisplayCutoutSafeArea");
Becca Hughes86334622018-07-09 21:29:381698 if (display_cutout_host_impl_)
1699 display_cutout_host_impl_->SetDisplayCutoutSafeArea(insets);
Becca Hughes6daf5662018-06-27 16:50:541700}
1701
1702#endif
1703
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411704const base::string16& WebContentsImpl::GetTitle() {
Nasko Oskov2f7d2112019-10-29 03:26:571705 WebUI* our_web_ui =
1706 GetRenderManager()->speculative_frame_host()
1707 ? GetRenderManager()->speculative_frame_host()->web_ui()
1708 : GetRenderManager()->current_frame_host()->web_ui();
[email protected]7ade2732011-02-10 00:13:581709 if (our_web_ui) {
[email protected]96d185d2009-04-24 03:28:541710 // Don't override the title in view source mode.
Carlos IL4dea8902020-05-26 15:14:291711 NavigationEntry* entry = controller_.GetVisibleEntry();
[email protected]96d185d2009-04-24 03:28:541712 if (!(entry && entry->IsViewSourceMode())) {
[email protected]e0112912011-02-02 22:54:351713 // Give the Web UI the chance to override our title.
[email protected]fcf75d42013-12-03 20:11:261714 const base::string16& title = our_web_ui->GetOverriddenTitle();
[email protected]96d185d2009-04-24 03:28:541715 if (!title.empty())
1716 return title;
1717 }
1718 }
1719
1720 // We use the title for the last committed entry rather than a pending
1721 // navigation entry. For example, when the user types in a URL, we want to
1722 // keep the old page's title until the new load has committed and we get a new
1723 // title.
Carlos IL4dea8902020-05-26 15:14:291724 NavigationEntry* entry = controller_.GetLastCommittedEntry();
[email protected]59167c22013-06-03 18:07:321725
creis072b61f2015-09-28 20:52:241726 // We make an exception for initial navigations. We only want to use the title
1727 // from the visible entry if:
1728 // 1. The pending entry has been explicitly assigned a title to display.
1729 // 2. The user is doing a history navigation in a new tab (e.g., Ctrl+Back),
1730 // which case there is a pending entry index other than -1.
1731 //
1732 // Otherwise, we want to stick with the last committed entry's title during
1733 // new navigations, which have pending entries at index -1 with no title.
1734 if (controller_.IsInitialNavigation() &&
1735 ((controller_.GetVisibleEntry() &&
1736 !controller_.GetVisibleEntry()->GetTitle().empty()) ||
1737 controller_.GetPendingEntryIndex() != -1)) {
1738 entry = controller_.GetVisibleEntry();
[email protected]9eeafc012013-11-25 23:49:471739 }
[email protected]59167c22013-06-03 18:07:321740
[email protected]45d0ef7f2011-01-05 13:46:231741 if (entry) {
jshin1fb76462016-04-05 22:13:031742 return entry->GetTitleForDisplay();
[email protected]45d0ef7f2011-01-05 13:46:231743 }
[email protected]987fc3a2011-05-26 14:18:091744
1745 // |page_title_when_no_navigation_entry_| is finally used
1746 // if no title cannot be retrieved.
1747 return page_title_when_no_navigation_entry_;
[email protected]96d185d2009-04-24 03:28:541748}
1749
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411750SiteInstanceImpl* WebContentsImpl::GetSiteInstance() {
[email protected]fa944cb82013-11-15 17:51:211751 return GetRenderManager()->current_host()->GetSiteInstance();
[email protected]96d185d2009-04-24 03:28:541752}
1753
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411754bool WebContentsImpl::IsLoading() {
Carlos ILd51e7702020-05-07 18:51:391755 return frame_tree_.IsLoading();
[email protected]3c9e1872010-11-18 16:17:491756}
1757
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411758double WebContentsImpl::GetLoadProgress() {
Peter Boström18a40fa2018-10-31 19:03:501759 return frame_tree_.load_progress();
1760}
1761
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411762bool WebContentsImpl::IsLoadingToDifferentDocument() {
clamy44e84ce2016-02-22 15:38:251763 return IsLoading() && is_load_to_different_document_;
[email protected]6dfed692014-05-22 04:18:031764}
1765
Alexander Timindd0fa0c52019-11-06 13:03:371766bool WebContentsImpl::IsDocumentOnLoadCompletedInMainFrame() {
1767 return GetRenderViewHost()->IsDocumentOnLoadCompletedInMainFrame();
1768}
1769
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411770bool WebContentsImpl::IsWaitingForResponse() {
Peter Boströma9a27f6e2018-11-21 13:12:191771 NavigationRequest* ongoing_navigation_request =
1772 frame_tree_.root()->navigation_request();
1773
1774 // An ongoing navigation request means we're waiting for a response.
1775 return ongoing_navigation_request != nullptr;
[email protected]be1f56ab2011-12-22 06:55:311776}
1777
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411778const net::LoadStateWithParam& WebContentsImpl::GetLoadState() {
[email protected]be1f56ab2011-12-22 06:55:311779 return load_state_;
1780}
1781
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411782const base::string16& WebContentsImpl::GetLoadStateHost() {
[email protected]be1f56ab2011-12-22 06:55:311783 return load_state_host_;
1784}
1785
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411786uint64_t WebContentsImpl::GetUploadSize() {
[email protected]be1f56ab2011-12-22 06:55:311787 return upload_size_;
1788}
1789
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411790uint64_t WebContentsImpl::GetUploadPosition() {
[email protected]be1f56ab2011-12-22 06:55:311791 return upload_position_;
1792}
1793
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411794const std::string& WebContentsImpl::GetEncoding() {
Alexander Timine5f20e22019-10-09 23:22:351795 return GetMainFrame()->GetEncoding();
[email protected]be1f56ab2011-12-22 06:55:311796}
1797
Charles Zhaod72f99d2018-09-17 14:18:271798bool WebContentsImpl::WasDiscarded() {
1799 return GetFrameTree()->root()->was_discarded();
1800}
1801
Shubhie Panickerddf2a4e2018-03-06 00:09:061802void WebContentsImpl::SetWasDiscarded(bool was_discarded) {
1803 GetFrameTree()->root()->set_was_discarded();
1804}
1805
Collin Bakerc5259962019-11-14 17:51:581806void WebContentsImpl::IncrementCapturerCount(const gfx::Size& capture_size,
1807 bool stay_hidden) {
Alexander Timin5fdeff22020-09-08 09:20:371808 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::IncrementCapturerCount");
[email protected]5a652232013-02-12 06:15:251809 DCHECK(!is_being_destroyed_);
Xianzhu Wang724e08f2020-09-01 21:35:071810 if (stay_hidden) {
1811 // A hidden capture should not have side effect on the web contents, so it
1812 // should not pass a non-empty |capture_size| which will cause side effect.
1813 DCHECK(capture_size.IsEmpty());
Collin Bakerc5259962019-11-14 17:51:581814 ++hidden_capturer_count_;
Xianzhu Wang724e08f2020-09-01 21:35:071815 } else {
Collin Bakerc5259962019-11-14 17:51:581816 ++visible_capturer_count_;
Xianzhu Wang724e08f2020-09-01 21:35:071817 }
[email protected]222f5822014-02-05 23:40:491818
1819 // Note: This provides a hint to upstream code to size the views optimally
1820 // for quality (e.g., to avoid scaling).
1821 if (!capture_size.IsEmpty() && preferred_size_for_capture_.IsEmpty()) {
1822 preferred_size_for_capture_ = capture_size;
1823 OnPreferredSizeChanged(preferred_size_);
1824 }
ccameron8807c38f2015-01-17 00:29:191825
Collin Bakerc5259962019-11-14 17:51:581826 UpdateVisibilityAndNotifyPageAndView(GetVisibility());
[email protected]54597982013-02-06 01:59:551827}
1828
Collin Bakerc5259962019-11-14 17:51:581829void WebContentsImpl::DecrementCapturerCount(bool stay_hidden) {
Alexander Timin5fdeff22020-09-08 09:20:371830 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DecrementCapturerCount");
Collin Bakerc5259962019-11-14 17:51:581831 if (stay_hidden)
1832 --hidden_capturer_count_;
1833 else
1834 --visible_capturer_count_;
1835 DCHECK_GE(hidden_capturer_count_, 0);
1836 DCHECK_GE(visible_capturer_count_, 0);
[email protected]54597982013-02-06 01:59:551837
[email protected]5a652232013-02-12 06:15:251838 if (is_being_destroyed_)
1839 return;
1840
Francois Doray24fc62c2017-12-11 17:27:331841 if (!IsBeingCaptured()) {
[email protected]222f5822014-02-05 23:40:491842 const gfx::Size old_size = preferred_size_for_capture_;
1843 preferred_size_for_capture_ = gfx::Size();
1844 OnPreferredSizeChanged(old_size);
[email protected]54597982013-02-06 01:59:551845 }
Collin Bakerc5259962019-11-14 17:51:581846
1847 UpdateVisibilityAndNotifyPageAndView(GetVisibility());
[email protected]be1f56ab2011-12-22 06:55:311848}
1849
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411850bool WebContentsImpl::IsBeingCaptured() {
Collin Bakerc5259962019-11-14 17:51:581851 return visible_capturer_count_ + hidden_capturer_count_ > 0;
[email protected]f2bd40812013-07-20 04:30:441852}
1853
Xianzhu Wangc61434c2020-08-21 19:17:301854bool WebContentsImpl::IsBeingVisiblyCaptured() {
1855 return visible_capturer_count_ > 0;
1856}
1857
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411858bool WebContentsImpl::IsAudioMuted() {
Guido Urdanetaf8372942019-11-15 09:47:211859 return audio_stream_factory_ && audio_stream_factory_->IsMuted();
miu50f97892014-09-22 22:49:521860}
1861
1862void WebContentsImpl::SetAudioMuted(bool mute) {
Alexander Timin5fdeff22020-09-08 09:20:371863 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetAudioMuted", "mute",
1864 mute);
miu50f97892014-09-22 22:49:521865 DVLOG(1) << "SetAudioMuted(mute=" << mute << "), was " << IsAudioMuted()
1866 << " for WebContentsImpl@" << this;
1867
1868 if (mute == IsAudioMuted())
1869 return;
1870
Guido Urdanetaf8372942019-11-15 09:47:211871 GetAudioStreamFactory()->SetMuted(mute);
miu50f97892014-09-22 22:49:521872
Alexander Timin90c20c32020-08-12 15:28:321873 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1874 observer->DidUpdateAudioMutingState(mute);
1875 });
Jan Rucka442c83f2017-08-08 13:27:541876 // Notification for UI updates in response to the changed muting state.
Collin Bakeraf540cf2019-09-20 20:54:161877 NotifyNavigationStateChanged(INVALIDATE_TYPE_AUDIO);
Jan Rucka442c83f2017-08-08 13:27:541878}
1879
1880bool WebContentsImpl::IsCurrentlyAudible() {
Chris Hamiltondf0d72cd2018-05-29 16:23:531881 return is_currently_audible_;
miu50f97892014-09-22 22:49:521882}
1883
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411884bool WebContentsImpl::IsConnectedToBluetoothDevice() {
ortunodf4d7982016-04-08 02:33:351885 return bluetooth_connected_device_count_ > 0;
ortuno32e7db3c2016-03-29 16:14:201886}
1887
Ovidio Henriquez76696f62020-07-08 03:06:591888bool WebContentsImpl::IsScanningForBluetoothDevices() {
1889 return bluetooth_scanning_sessions_count_ > 0;
1890}
1891
Lucas Furukawa Gadani4b4eed02019-06-04 23:12:041892bool WebContentsImpl::IsConnectedToSerialPort() {
Reilly Grant5e7c79b22019-04-09 17:26:201893 return serial_active_frame_count_ > 0;
1894}
1895
Matt Reynoldse8c6c1f2019-11-02 09:53:531896bool WebContentsImpl::IsConnectedToHidDevice() {
1897 return hid_active_frame_count_ > 0;
1898}
1899
Marijn Kruisselbrink29051042019-08-06 22:56:551900bool WebContentsImpl::HasNativeFileSystemHandles() {
1901 return native_file_system_handle_count_ > 0;
1902}
Marijn Kruisselbrinkf1714aa22019-07-02 03:45:331903
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411904bool WebContentsImpl::HasPictureInPictureVideo() {
sawtellea7333a82018-05-31 02:36:361905 return has_picture_in_picture_video_;
1906}
1907
1908void WebContentsImpl::SetHasPictureInPictureVideo(
1909 bool has_picture_in_picture_video) {
Alexander Timin5fdeff22020-09-08 09:20:371910 OPTIONAL_TRACE_EVENT1("content",
1911 "WebContentsImpl::SetHasPictureInPictureVideo",
1912 "has_pip_video", has_picture_in_picture_video);
sawtellea7333a82018-05-31 02:36:361913 // If status of |this| is already accurate, there is no need to update.
1914 if (has_picture_in_picture_video == has_picture_in_picture_video_)
1915 return;
1916 has_picture_in_picture_video_ = has_picture_in_picture_video;
1917 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
Alexander Timin90c20c32020-08-12 15:28:321918 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1919 observer->MediaPictureInPictureChanged(has_picture_in_picture_video_);
1920 });
sawtellea7333a82018-05-31 02:36:361921}
1922
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411923bool WebContentsImpl::IsCrashed() {
Dominic Mazzoni73a48322018-05-25 18:14:071924 switch (crashed_status_) {
1925 case base::TERMINATION_STATUS_PROCESS_CRASHED:
1926 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
1927 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED:
1928 case base::TERMINATION_STATUS_OOM:
1929 case base::TERMINATION_STATUS_LAUNCH_FAILED:
Darin Fisher6cf20e782020-08-07 22:25:361930#if defined(OS_CHROMEOS) || BUILDFLAG(IS_LACROS)
Dominic Mazzoni73a48322018-05-25 18:14:071931 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM:
oshima620225722015-06-04 19:45:271932#endif
Dominic Mazzoni73a48322018-05-25 18:14:071933#if defined(OS_ANDROID)
1934 case base::TERMINATION_STATUS_OOM_PROTECTED:
1935#endif
Will Harris07925d12019-10-31 03:03:051936#if defined(OS_WIN)
1937 case base::TERMINATION_STATUS_INTEGRITY_FAILURE:
1938#endif
Dominic Mazzoni73a48322018-05-25 18:14:071939 return true;
1940 case base::TERMINATION_STATUS_NORMAL_TERMINATION:
1941 case base::TERMINATION_STATUS_STILL_RUNNING:
1942 return false;
1943 case base::TERMINATION_STATUS_MAX_ENUM:
1944 NOTREACHED();
1945 return false;
1946 }
1947
1948 NOTREACHED();
1949 return false;
[email protected]3c9e1872010-11-18 16:17:491950}
1951
[email protected]b172aee2012-04-10 17:05:261952void WebContentsImpl::SetIsCrashed(base::TerminationStatus status,
1953 int error_code) {
Alexander Timin5fdeff22020-09-08 09:20:371954 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetIsCrashed", "status",
1955 static_cast<int>(status), "old_status",
1956 static_cast<int>(crashed_status_));
[email protected]443b80e2010-12-14 00:42:231957 if (status == crashed_status_)
[email protected]d5f942ba2008-09-26 19:30:341958 return;
1959
[email protected]443b80e2010-12-14 00:42:231960 crashed_status_ = status;
1961 crashed_error_code_ = error_code;
[email protected]8ff00d72012-10-23 19:12:211962 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
[email protected]d5f942ba2008-09-26 19:30:341963}
1964
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411965base::TerminationStatus WebContentsImpl::GetCrashedStatus() {
[email protected]be1f56ab2011-12-22 06:55:311966 return crashed_status_;
1967}
1968
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411969int WebContentsImpl::GetCrashedErrorCode() {
afakhry98241832016-03-11 19:27:471970 return crashed_error_code_;
1971}
1972
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411973bool WebContentsImpl::IsBeingDestroyed() {
[email protected]be1f56ab2011-12-22 06:55:311974 return is_being_destroyed_;
1975}
1976
[email protected]7f924832014-08-09 05:57:221977void WebContentsImpl::NotifyNavigationStateChanged(
1978 InvalidateTypes changed_flags) {
Alexander Timin5fdeff22020-09-08 09:20:371979 TRACE_EVENT1("content,navigation",
1980 "WebContentsImpl::NotifyNavigationStateChanged", "changed_flags",
1981 static_cast<int>(changed_flags));
dalecurtis88c240072015-12-09 02:11:181982 // Notify the media observer of potential audibility changes.
Collin Bakeraf540cf2019-09-20 20:54:161983 if (changed_flags & INVALIDATE_TYPE_AUDIO) {
mlamouri44e4ef42016-01-20 18:42:271984 media_web_contents_observer_->MaybeUpdateAudibleState();
dalecurtisbc6572e12014-09-12 19:22:301985 }
1986
[email protected]d5f942ba2008-09-26 19:30:341987 if (delegate_)
1988 delegate_->NavigationStateChanged(this, changed_flags);
wjmaclean1dabf3e32016-05-13 23:34:441989
1990 if (GetOuterWebContents())
1991 GetOuterWebContents()->NotifyNavigationStateChanged(changed_flags);
[email protected]d5f942ba2008-09-26 19:30:341992}
1993
W. James MacLean6f34b042019-07-12 19:25:301994RenderFrameHostImpl* WebContentsImpl::GetFocusedFrameFromFocusedDelegate() {
1995 FrameTreeNode* focused_node =
1996 GetFocusedWebContents()->frame_tree_.GetFocusedFrame();
1997 return focused_node ? focused_node->current_frame_host() : nullptr;
1998}
1999
David Black9cca3592019-11-06 23:02:222000void WebContentsImpl::OnVerticalScrollDirectionChanged(
2001 viz::VerticalScrollDirection scroll_direction) {
Alexander Timin5fdeff22020-09-08 09:20:372002 OPTIONAL_TRACE_EVENT1("content",
2003 "WebContentsImpl::OnVerticalScrollDirectionChanged",
2004 "scroll_direction", static_cast<int>(scroll_direction));
Alexander Timin90c20c32020-08-12 15:28:322005 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2006 observer->DidChangeVerticalScrollDirection(scroll_direction);
2007 });
David Black9cca3592019-11-06 23:02:222008}
2009
Chris Hamiltondf0d72cd2018-05-29 16:23:532010void WebContentsImpl::OnAudioStateChanged() {
2011 // This notification can come from any embedded contents or from this
2012 // WebContents' stream monitor. Aggregate these signals to get the actual
2013 // state.
Jeremy Roman03ce13ce2020-05-29 22:16:572014 //
2015 // Note that guests may not be attached as inner contents, and so may need to
2016 // be checked separately.
Chris Hamiltondf0d72cd2018-05-29 16:23:532017 bool is_currently_audible =
2018 audio_stream_monitor_.IsCurrentlyAudible() ||
2019 (browser_plugin_embedder_ &&
Jeremy Roman03ce13ce2020-05-29 22:16:572020 browser_plugin_embedder_->AreAnyGuestsCurrentlyAudible()) ||
2021 AnyInnerWebContents(this, [](WebContents* inner_contents) {
2022 return inner_contents->IsCurrentlyAudible();
2023 });
Alexander Timin5fdeff22020-09-08 09:20:372024 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnAudioStateChanged",
2025 "is_currently_audible", is_currently_audible,
2026 "was_audible", is_currently_audible_);
Chris Hamiltondf0d72cd2018-05-29 16:23:532027 if (is_currently_audible == is_currently_audible_)
2028 return;
2029
2030 // Update internal state.
2031 is_currently_audible_ = is_currently_audible;
2032 was_ever_audible_ = was_ever_audible_ || is_currently_audible_;
2033
Gyuyoung Kim877e86d2020-07-21 04:01:022034 ExecutePageBroadcastMethod(base::BindRepeating(
2035 [](bool is_currently_audible, RenderViewHostImpl* rvh) {
2036 if (auto& broadcast = rvh->GetAssociatedPageBroadcast())
2037 broadcast->AudioStateChanged(is_currently_audible);
2038 },
2039 is_currently_audible_));
altimind8bd26c2016-11-04 11:44:542040
altiminec87fd1f2016-11-17 20:22:492041 // Notification for UI updates in response to the changed audio state.
Collin Bakeraf540cf2019-09-20 20:54:162042 NotifyNavigationStateChanged(INVALIDATE_TYPE_AUDIO);
Jan Rucka442c83f2017-08-08 13:27:542043
Chris Hamiltondf0d72cd2018-05-29 16:23:532044 // Ensure that audio state changes propagate from innermost to outermost
2045 // WebContents.
2046 if (GetOuterWebContents())
2047 GetOuterWebContents()->OnAudioStateChanged();
Tommy Steimel18360512017-11-01 00:38:192048
Alexander Timin90c20c32020-08-12 15:28:322049 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2050 observer->OnAudioStateChanged(is_currently_audible_);
2051 });
altimind8bd26c2016-11-04 11:44:542052}
2053
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:412054base::TimeTicks WebContentsImpl::GetLastActiveTime() {
[email protected]9a890452014-02-13 22:21:022055 return last_active_time_;
[email protected]3e324142012-06-25 18:26:332056}
2057
[email protected]9e2e4632012-07-27 16:38:412058void WebContentsImpl::WasShown() {
Alexander Timin5fdeff22020-09-08 09:20:372059 TRACE_EVENT0("content", "WebContentsImpl::WasShown");
Collin Baker989e0882019-11-01 01:27:172060 UpdateVisibilityAndNotifyPageAndView(Visibility::VISIBLE);
[email protected]be1f56ab2011-12-22 06:55:312061}
2062
[email protected]b172aee2012-04-10 17:05:262063void WebContentsImpl::WasHidden() {
Alexander Timin5fdeff22020-09-08 09:20:372064 TRACE_EVENT0("content", "WebContentsImpl::WasHidden");
Collin Baker989e0882019-11-01 01:27:172065 UpdateVisibilityAndNotifyPageAndView(Visibility::HIDDEN);
[email protected]375fa1b2012-05-22 22:05:372066}
2067
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:412068bool WebContentsImpl::HasRecentInteractiveInputEvent() {
Daniel Cheng90196c82018-04-25 21:49:142069 static constexpr base::TimeDelta kMaxInterval =
2070 base::TimeDelta::FromSeconds(5);
2071 base::TimeDelta delta =
2072 ui::EventTimeForNow() - last_interactive_input_event_time_;
2073 // Note: the expectation is that the caller is typically expecting an input
2074 // event, e.g. validating that a WebUI message that requires a gesture is
Daniel Chenge81030b32019-07-17 20:20:232075 // actually attached to a gesture.
Daniel Cheng90196c82018-04-25 21:49:142076 return delta <= kMaxInterval;
2077}
2078
Avi Drissman738ea192018-08-29 20:24:162079void WebContentsImpl::SetIgnoreInputEvents(bool ignore_input_events) {
Alexander Timin5fdeff22020-09-08 09:20:372080 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetIgnoreInputEvents",
2081 "ignore_input_events", ignore_input_events);
Avi Drissman738ea192018-08-29 20:24:162082 ignore_input_events_ = ignore_input_events;
2083}
2084
Bo Liu168c8642017-08-28 18:26:022085#if defined(OS_ANDROID)
Bo Liu16dd7b8322018-05-02 21:19:502086void WebContentsImpl::SetMainFrameImportance(
2087 ChildProcessImportance importance) {
Alexander Timin5fdeff22020-09-08 09:20:372088 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetMainFrameImportance",
2089 "importance", static_cast<int>(importance));
Bo Liu16dd7b8322018-05-02 21:19:502090 GetMainFrame()->GetRenderWidgetHost()->SetImportance(importance);
Bo Liu7c6779e92017-08-16 02:02:282091}
Bo Liu168c8642017-08-28 18:26:022092#endif
Bo Liu7c6779e92017-08-16 02:02:282093
ccameron8807c38f2015-01-17 00:29:192094void WebContentsImpl::WasOccluded() {
Alexander Timin5fdeff22020-09-08 09:20:372095 TRACE_EVENT0("content", "WebContentsImpl::WasOccluded");
Collin Baker989e0882019-11-01 01:27:172096 UpdateVisibilityAndNotifyPageAndView(Visibility::OCCLUDED);
ccameron8807c38f2015-01-17 00:29:192097}
2098
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:412099Visibility WebContentsImpl::GetVisibility() {
Francois Doraye6161152018-03-27 22:05:372100 return visibility_;
Francois Dorayfe4a1772018-02-17 04:17:092101}
2102
Rakina Zata Amni26e8d8a2020-08-05 06:06:062103bool WebContentsImpl::NeedToFireBeforeUnloadOrUnloadEvents() {
Alexander Timinc7bee322020-05-19 17:54:342104 if (!notify_disconnection_)
Alex Moshchuk6fcaca752018-07-14 02:13:592105 return false;
2106
2107 // Don't fire if the main frame's RenderViewHost indicates that beforeunload
2108 // and unload have already executed (e.g., after receiving a ClosePage ACK)
2109 // or should be ignored.
2110 if (GetRenderViewHost()->SuddenTerminationAllowed())
2111 return false;
2112
Alex Moshchukc78dbc722019-10-31 20:00:502113 // Check whether any frame in the frame tree needs to run beforeunload or
Rakina Zata Amni26e8d8a2020-08-05 06:06:062114 // unload-time event handlers.
Alex Moshchukc78dbc722019-10-31 20:00:502115 for (FrameTreeNode* node : frame_tree_.Nodes()) {
2116 RenderFrameHostImpl* rfh = node->current_frame_host();
2117
Rakina Zata Amni26e8d8a2020-08-05 06:06:062118 // No need to run beforeunload/unload-time events if the RenderFrame isn't
2119 // live.
Alex Moshchukc78dbc722019-10-31 20:00:502120 if (!rfh->IsRenderFrameLive())
2121 continue;
Rakina Zata Amni26e8d8a2020-08-05 06:06:062122 bool should_run_before_unload_handler =
Dave Tapuska97d22ab2019-12-03 17:56:362123 rfh->GetSuddenTerminationDisablerState(
Rakina Zata Amni26e8d8a2020-08-05 06:06:062124 blink::mojom::SuddenTerminationDisablerType::kBeforeUnloadHandler);
2125 bool should_run_unload_handler = rfh->GetSuddenTerminationDisablerState(
2126 blink::mojom::SuddenTerminationDisablerType::kUnloadHandler);
2127 bool should_run_page_hide_handler = rfh->GetSuddenTerminationDisablerState(
2128 blink::mojom::SuddenTerminationDisablerType::kPageHideHandler);
2129 auto* rvh = static_cast<RenderViewHostImpl*>(rfh->GetRenderViewHost());
2130 // If the tab is already hidden, we should not run visibilitychange
2131 // handlers.
2132 bool is_page_visible = rvh->GetPageLifecycleStateManager()
2133 ->CalculatePageLifecycleState()
2134 ->visibility == PageVisibilityState::kVisible;
2135
2136 bool should_run_visibility_change_handler =
2137 is_page_visible && rfh->GetSuddenTerminationDisablerState(
2138 blink::mojom::SuddenTerminationDisablerType::
2139 kVisibilityChangeHandler);
2140 if (should_run_before_unload_handler || should_run_unload_handler ||
2141 should_run_page_hide_handler || should_run_visibility_change_handler) {
Alex Moshchukc78dbc722019-10-31 20:00:502142 return true;
2143 }
Aditya Keerthi34f37e62019-03-08 15:54:532144 }
Alex Moshchuk6fcaca752018-07-14 02:13:592145
Alex Moshchukc78dbc722019-10-31 20:00:502146 return false;
[email protected]be1f56ab2011-12-22 06:55:312147}
2148
Chris Hamilton3b3e315d2018-09-19 13:16:212149void WebContentsImpl::DispatchBeforeUnload(bool auto_cancel) {
Alexander Timin5fdeff22020-09-08 09:20:372150 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DispatchBeforeUnload",
2151 "auto_cancel", auto_cancel);
Chris Hamilton3b3e315d2018-09-19 13:16:212152 auto before_unload_type =
2153 auto_cancel ? RenderFrameHostImpl::BeforeUnloadType::DISCARD
2154 : RenderFrameHostImpl::BeforeUnloadType::TAB_CLOSE;
2155 GetMainFrame()->DispatchBeforeUnload(before_unload_type, false);
[email protected]1c3f80bd2014-04-08 23:02:062156}
2157
W. James MacLean2539adb32019-12-13 00:40:442158bool WebContentsImpl::IsInnerWebContentsForGuest() {
2159 return !!browser_plugin_guest_;
2160}
2161
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502162void WebContentsImpl::AttachInnerWebContents(
2163 std::unique_ptr<WebContents> inner_web_contents,
W. James MacLean62883982019-11-12 20:39:002164 RenderFrameHost* render_frame_host,
2165 bool is_full_page) {
Alexander Timin5fdeff22020-09-08 09:20:372166 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::AttachInnerWebContents",
2167 "inner_web_contents", inner_web_contents.get(),
2168 "is_full_page", is_full_page);
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502169 WebContentsImpl* inner_web_contents_impl =
2170 static_cast<WebContentsImpl*>(inner_web_contents.get());
2171 DCHECK(!inner_web_contents_impl->node_.outer_web_contents());
2172 auto* render_frame_host_impl =
2173 static_cast<RenderFrameHostImpl*>(render_frame_host);
Fergal Daly445af932020-06-02 06:37:232174 DCHECK_EQ(&frame_tree_, render_frame_host_impl->frame_tree());
Lucas Furukawa Gadani105de1e812018-05-31 19:38:392175
Yuzu Saijo3f86fb22020-06-11 03:51:102176 // Mark |render_frame_host_impl| as outer delegate frame.
2177 render_frame_host_impl->SetIsOuterDelegateFrame(true);
2178
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502179 RenderFrameHostManager* inner_render_manager =
2180 inner_web_contents_impl->GetRenderManager();
2181 RenderFrameHostImpl* inner_main_frame =
2182 inner_render_manager->current_frame_host();
2183 RenderViewHostImpl* inner_render_view_host =
2184 inner_render_manager->current_host();
2185 auto* outer_render_manager =
2186 render_frame_host_impl->frame_tree_node()->render_manager();
lfg91a79e12016-04-01 23:52:192187
Lucas Furukawa Gadani105de1e812018-05-31 19:38:392188 // When attaching a WebContents as an inner WebContents, we need to replace
2189 // the Webcontents' view with a WebContentsViewChildFrame.
Fergal Daly55b6d722020-09-11 07:56:332190 inner_web_contents_impl->view_ = std::make_unique<WebContentsViewChildFrame>(
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502191 inner_web_contents_impl,
2192 GetContentClient()->browser()->GetWebContentsViewDelegate(
2193 inner_web_contents_impl),
Fergal Daly55b6d722020-09-11 07:56:332194 &inner_web_contents_impl->render_view_host_delegate_view_);
Lucas Furukawa Gadani105de1e812018-05-31 19:38:392195
lfg91a79e12016-04-01 23:52:192196 // When the WebContents being initialized has an opener, the browser side
2197 // Render{View,Frame}Host must be initialized and the RenderWidgetHostView
2198 // created. This is needed because the usual initialization happens during
2199 // the first navigation, but when attaching a new window we don't navigate
2200 // before attaching. If the browser side is already initialized, the calls
2201 // below will just early return.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502202 inner_render_manager->InitRenderView(inner_render_view_host, nullptr);
2203 inner_main_frame->Init();
2204 if (!inner_render_manager->GetRenderWidgetHostView()) {
2205 inner_web_contents_impl->CreateRenderWidgetHostViewForRenderManager(
2206 inner_render_view_host);
2207 }
lfg91a79e12016-04-01 23:52:192208
Adithya Srinivasane6e7f842019-12-16 18:41:362209 inner_web_contents_impl->RecursivelyUnregisterFrameSinkIds();
2210
lazyboy6ec48b2a2015-06-29 15:18:142211 // Create a link to our outer WebContents.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502212 node_.AttachInnerWebContents(std::move(inner_web_contents),
2213 render_frame_host_impl);
lazyboy6ec48b2a2015-06-29 15:18:142214
lazyboy6ec48b2a2015-06-29 15:18:142215 // Create a proxy in top-level RenderFrameHostManager, pointing to the
2216 // SiteInstance of the outer WebContents. The proxy will be used to send
2217 // postMessage to the inner WebContents.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502218 auto* proxy = inner_render_manager->CreateOuterDelegateProxy(
2219 render_frame_host_impl->GetSiteInstance());
lazyboy6ec48b2a2015-06-29 15:18:142220
Lucas Furukawa Gadani99125822019-01-03 15:41:492221 // When attaching a GuestView as an inner WebContents, there should already be
2222 // a live RenderFrame, which has to be swapped. When attaching a portal, there
2223 // will not be a live RenderFrame before creating the proxy.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502224 if (render_frame_host_impl->IsRenderFrameLive()) {
2225 inner_render_manager->SwapOuterDelegateFrame(render_frame_host_impl, proxy);
Lucas Furukawa Gadani99125822019-01-03 15:41:492226
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502227 inner_web_contents_impl->ReattachToOuterWebContentsFrame();
Lucas Furukawa Gadani99125822019-01-03 15:41:492228 }
ekaramadadd882292016-06-08 15:22:562229
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502230 if (frame_tree_.GetFocusedFrame() ==
2231 render_frame_host_impl->frame_tree_node()) {
2232 inner_web_contents_impl->SetFocusedFrame(
2233 inner_web_contents_impl->frame_tree_.root(),
2234 render_frame_host_impl->GetSiteInstance());
avallee7529b2a2017-04-26 11:37:512235 }
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502236 outer_render_manager->set_attach_complete();
W. James MacLean62883982019-11-12 20:39:002237
2238 // If the inner WebContents is full frame, give it focus.
2239 if (is_full_page) {
2240 // There should only ever be one inner WebContents when |is_full_page| is
2241 // true, and it is the one we just attached.
2242 DCHECK_EQ(1u, node_.GetInnerWebContents().size());
2243 inner_web_contents_impl->SetAsFocusedWebContentsIfNecessary();
2244 }
Chris Hamilton16b5d1d2020-06-04 00:08:122245
Alexander Timin90c20c32020-08-12 15:28:322246 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2247 observer->InnerWebContentsAttached(inner_web_contents_impl,
2248 render_frame_host, is_full_page);
2249 });
lazyboy6ec48b2a2015-06-29 15:18:142250}
2251
Lucas Furukawa Gadani99125822019-01-03 15:41:492252std::unique_ptr<WebContents> WebContentsImpl::DetachFromOuterWebContents() {
Alexander Timin5fdeff22020-09-08 09:20:372253 OPTIONAL_TRACE_EVENT0("content",
2254 "WebContentsImpl::DetachFromOuterWebContents");
Chris Hamilton16b5d1d2020-06-04 00:08:122255 auto* outer_web_contents = GetOuterWebContents();
2256 DCHECK(outer_web_contents);
Yuzu Saijo3f86fb22020-06-11 03:51:102257 GetMainFrame()->ParentOrOuterDelegateFrame()->SetIsOuterDelegateFrame(false);
Chris Hamilton16b5d1d2020-06-04 00:08:122258
Adithya Srinivasane6e7f842019-12-16 18:41:362259 RecursivelyUnregisterFrameSinkIds();
Lucas Gadanid29952582020-06-09 21:24:002260
2261 // Each RenderViewHost has a RenderWidgetHost which can have a
2262 // RenderWidgetHostView, and it needs to be re-created with the appropriate
2263 // platform view. It is important to re-create all child views, not only the
2264 // current one, since the view can be swapped due to a cross-origin
2265 // navigation.
2266 std::set<RenderViewHostImpl*> render_view_hosts;
2267 for (auto& render_view_host : GetFrameTree()->render_view_hosts()) {
2268 if (render_view_host.second->GetWidget() &&
2269 render_view_host.second->GetWidget()->GetView()) {
2270 DCHECK(render_view_host.second->GetWidget()
2271 ->GetView()
2272 ->IsRenderWidgetHostViewChildFrame());
2273 render_view_hosts.insert(render_view_host.second);
Kevin McNee6471a702020-01-27 18:23:072274 }
2275 }
Lucas Gadanid29952582020-06-09 21:24:002276
2277 for (auto* render_view_host : render_view_hosts)
2278 render_view_host->GetWidget()->GetView()->Destroy();
2279
Lucas Furukawa Gadani99125822019-01-03 15:41:492280 GetRenderManager()->DeleteOuterDelegateProxy(
2281 node_.OuterContentsFrameTreeNode()
2282 ->current_frame_host()
2283 ->GetSiteInstance());
2284 view_.reset(CreateWebContentsView(
2285 this, GetContentClient()->browser()->GetWebContentsViewDelegate(this),
2286 &render_view_host_delegate_view_));
danakjfc5184932019-09-12 18:08:322287 view_->CreateView(nullptr);
Lucas Furukawa Gadani99125822019-01-03 15:41:492288 std::unique_ptr<WebContents> web_contents =
2289 node_.DisconnectFromOuterWebContents();
2290 DCHECK_EQ(web_contents.get(), this);
2291 node_.SetFocusedWebContents(this);
Lucas Gadanid29952582020-06-09 21:24:002292
2293 for (auto* render_view_host : render_view_hosts)
2294 CreateRenderWidgetHostViewForRenderManager(render_view_host);
2295
Adithya Srinivasane6e7f842019-12-16 18:41:362296 RecursivelyRegisterFrameSinkIds();
Adithya Srinivasan6f0f67b2019-12-19 01:26:462297 // TODO(adithyas): |browser_plugin_embedder_ax_tree_id| should either not be
2298 // used for portals, or it should get a different name.
2299 GetMainFrame()->set_browser_plugin_embedder_ax_tree_id(ui::AXTreeIDUnknown());
2300 GetMainFrame()->UpdateAXTreeData();
Chris Hamilton16b5d1d2020-06-04 00:08:122301
2302 // Invoke on the *outer* web contents observers for symmetry.
Alexander Timin90c20c32020-08-12 15:28:322303 outer_web_contents->observers_.ForEachObserver(
2304 [&](WebContentsObserver* observer) {
2305 observer->InnerWebContentsDetached(this);
2306 });
Chris Hamilton16b5d1d2020-06-04 00:08:122307
Lucas Furukawa Gadani99125822019-01-03 15:41:492308 return web_contents;
2309}
2310
W. James MacLean2dc75ed42019-03-06 14:31:092311void WebContentsImpl::RecursivelyRegisterFrameSinkIds() {
Alexander Timin5fdeff22020-09-08 09:20:372312 OPTIONAL_TRACE_EVENT0("content",
2313 "WebContentsImpl::RecursivelyRegisterFrameSinkIds");
Adithya Srinivasane6e7f842019-12-16 18:41:362314 for (auto* view : GetRenderWidgetHostViewsInWebContentsTree()) {
2315 auto* rwhvb = static_cast<RenderWidgetHostViewBase*>(view);
2316 if (rwhvb->IsRenderWidgetHostViewChildFrame())
2317 static_cast<RenderWidgetHostViewChildFrame*>(view)->RegisterFrameSinkId();
2318 }
2319}
W. James MacLean2dc75ed42019-03-06 14:31:092320
Adithya Srinivasane6e7f842019-12-16 18:41:362321void WebContentsImpl::RecursivelyUnregisterFrameSinkIds() {
Alexander Timin5fdeff22020-09-08 09:20:372322 OPTIONAL_TRACE_EVENT0("content",
2323 "WebContentsImpl::RecursivelyUnregisterFrameSinkIds");
Adithya Srinivasane6e7f842019-12-16 18:41:362324 for (auto* view : GetRenderWidgetHostViewsInWebContentsTree()) {
2325 auto* rwhvb = static_cast<RenderWidgetHostViewBase*>(view);
2326 if (rwhvb->IsRenderWidgetHostViewChildFrame()) {
2327 static_cast<RenderWidgetHostViewChildFrame*>(view)
2328 ->UnregisterFrameSinkId();
2329 }
W. James MacLean2dc75ed42019-03-06 14:31:092330 }
2331}
2332
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:142333void WebContentsImpl::ReattachToOuterWebContentsFrame() {
Alexander Timin5fdeff22020-09-08 09:20:372334 OPTIONAL_TRACE_EVENT0("content",
2335 "WebContentsImpl::ReattachToOuterWebContentsFrame");
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:142336 DCHECK(node_.outer_web_contents());
2337 auto* render_manager = GetRenderManager();
2338 auto* parent_frame =
2339 node_.OuterContentsFrameTreeNode()->current_frame_host()->GetParent();
2340 render_manager->SetRWHViewForInnerContents(
2341 render_manager->GetRenderWidgetHostView());
2342
W. James MacLean2dc75ed42019-03-06 14:31:092343 RecursivelyRegisterFrameSinkIds();
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:142344
2345 // Set up the the guest's AX tree to point back at the embedder's AX tree.
2346 GetMainFrame()->set_browser_plugin_embedder_ax_tree_id(
2347 parent_frame->GetAXTreeID());
2348 GetMainFrame()->UpdateAXTreeData();
2349}
2350
Lucas Gadani972985622020-05-28 20:52:512351void WebContentsImpl::DidActivatePortal(
2352 WebContentsImpl* predecessor_web_contents,
2353 base::TimeTicks activation_time) {
Alexander Timin5fdeff22020-09-08 09:20:372354 TRACE_EVENT2("content", "WebContentsImpl::DidActivatePortal", "predecessor",
2355 predecessor_web_contents, "activation_time", activation_time);
Lucas Gadani972985622020-05-28 20:52:512356 DCHECK(predecessor_web_contents);
Kevin McNeef8eb64c2020-04-21 21:36:062357 NotifyInsidePortal(false);
Alexander Timin90c20c32020-08-12 15:28:322358 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2359 observer->DidActivatePortal(predecessor_web_contents, activation_time);
2360 });
Lucas Gadani972985622020-05-28 20:52:512361 GetDelegate()->WebContentsBecamePortal(predecessor_web_contents);
Kevin McNeef8eb64c2020-04-21 21:36:062362}
2363
Adithya Srinivasan11af2c52019-12-16 22:52:552364void WebContentsImpl::NotifyInsidePortal(bool inside_portal) {
Alexander Timin5fdeff22020-09-08 09:20:372365 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::NotifyInsidePortal",
2366 "inside_portal", inside_portal);
Gyuyoung Kim1c029712020-07-22 09:21:062367 ExecutePageBroadcastMethod(base::BindRepeating(
2368 [](bool inside_portal, RenderViewHostImpl* rvh) {
2369 if (auto& broadcast = rvh->GetAssociatedPageBroadcast())
2370 broadcast->SetInsidePortal(inside_portal);
2371 },
2372 inside_portal));
Adithya Srinivasan11af2c52019-12-16 22:52:552373}
2374
dalecurtis6c58ed02016-10-28 23:02:372375void WebContentsImpl::DidChangeVisibleSecurityState() {
Alexander Timin5fdeff22020-09-08 09:20:372376 OPTIONAL_TRACE_EVENT0("content",
2377 "WebContentsImpl::DidChangeVisibleSecurityState");
Emily Starkc663b0242019-04-26 19:34:452378 if (delegate_)
dalecurtis6c58ed02016-10-28 23:02:372379 delegate_->VisibleSecurityStateChanged(this);
Alexander Timin90c20c32020-08-12 15:28:322380 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2381 observer->DidChangeVisibleSecurityState();
2382 });
dalecurtis6c58ed02016-10-28 23:02:372383}
2384
Gyuyoung Kim1ac4ca782020-09-11 03:32:512385const blink::web_pref::WebPreferences WebContentsImpl::ComputeWebPreferences() {
Alexander Timin5fdeff22020-09-08 09:20:372386 OPTIONAL_TRACE_EVENT0("browser", "WebContentsImpl::ComputeWebPreferences");
2387
Gyuyoung Kim1ac4ca782020-09-11 03:32:512388 blink::web_pref::WebPreferences prefs;
Rakina Zata Amni4029b6d2020-07-28 02:36:202389
2390 const base::CommandLine& command_line =
2391 *base::CommandLine::ForCurrentProcess();
2392
2393 SetSlowWebPreferences(command_line, &prefs);
2394
2395 prefs.web_security_enabled =
2396 !command_line.HasSwitch(switches::kDisableWebSecurity);
2397
2398 prefs.remote_fonts_enabled =
2399 !command_line.HasSwitch(switches::kDisableRemoteFonts);
2400 prefs.application_cache_enabled =
2401 base::FeatureList::IsEnabled(blink::features::kAppCache);
2402 prefs.local_storage_enabled =
2403 !command_line.HasSwitch(switches::kDisableLocalStorage);
2404 prefs.databases_enabled =
2405 !command_line.HasSwitch(switches::kDisableDatabases);
2406
2407 prefs.webgl1_enabled = !command_line.HasSwitch(switches::kDisable3DAPIs) &&
2408 !command_line.HasSwitch(switches::kDisableWebGL);
2409 prefs.webgl2_enabled = !command_line.HasSwitch(switches::kDisable3DAPIs) &&
2410 !command_line.HasSwitch(switches::kDisableWebGL) &&
2411 !command_line.HasSwitch(switches::kDisableWebGL2);
2412
2413 prefs.pepper_3d_enabled = !command_line.HasSwitch(switches::kDisablePepper3d);
2414
2415 prefs.flash_3d_enabled = !command_line.HasSwitch(switches::kDisableFlash3d);
2416 prefs.flash_stage3d_enabled =
2417 !command_line.HasSwitch(switches::kDisableFlashStage3d);
2418 prefs.flash_stage3d_baseline_enabled =
2419 !command_line.HasSwitch(switches::kDisableFlashStage3d);
2420
2421 prefs.allow_file_access_from_file_urls =
2422 command_line.HasSwitch(switches::kAllowFileAccessFromFiles);
2423
2424 prefs.accelerated_2d_canvas_enabled =
2425 !command_line.HasSwitch(switches::kDisableAccelerated2dCanvas);
2426 prefs.new_canvas_2d_api_enabled =
Rakina Zata Amniea8d0c22020-07-30 17:22:502427 command_line.HasSwitch(switches::kEnableNewCanvas2DAPI) ||
2428 base::FeatureList::IsEnabled(features::kEnableNewCanvas2DAPI);
Rakina Zata Amni4029b6d2020-07-28 02:36:202429 prefs.antialiased_2d_canvas_disabled =
2430 command_line.HasSwitch(switches::kDisable2dCanvasAntialiasing);
2431 prefs.antialiased_clips_2d_canvas_enabled =
2432 !command_line.HasSwitch(switches::kDisable2dCanvasClipAntialiasing);
2433
2434 prefs.disable_ipc_flooding_protection =
2435 command_line.HasSwitch(switches::kDisableIpcFloodingProtection) ||
2436 command_line.HasSwitch(switches::kDisablePushStateThrottle);
2437
2438 prefs.accelerated_video_decode_enabled =
2439 !command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode);
2440
2441 std::string autoplay_policy = media::GetEffectiveAutoplayPolicy(command_line);
2442 if (autoplay_policy == switches::autoplay::kNoUserGestureRequiredPolicy) {
Gyuyoung Kim1ac4ca782020-09-11 03:32:512443 prefs.autoplay_policy =
2444 blink::web_pref::AutoplayPolicy::kNoUserGestureRequired;
Rakina Zata Amni4029b6d2020-07-28 02:36:202445 } else if (autoplay_policy ==
2446 switches::autoplay::kUserGestureRequiredPolicy) {
Gyuyoung Kim1ac4ca782020-09-11 03:32:512447 prefs.autoplay_policy =
2448 blink::web_pref::AutoplayPolicy::kUserGestureRequired;
Rakina Zata Amni4029b6d2020-07-28 02:36:202449 } else if (autoplay_policy ==
2450 switches::autoplay::kDocumentUserActivationRequiredPolicy) {
Gyuyoung Kim1ac4ca782020-09-11 03:32:512451 prefs.autoplay_policy =
2452 blink::web_pref::AutoplayPolicy::kDocumentUserActivationRequired;
Rakina Zata Amni4029b6d2020-07-28 02:36:202453 } else {
2454 NOTREACHED();
2455 }
2456
2457 prefs.dont_send_key_events_to_javascript =
2458 base::FeatureList::IsEnabled(features::kDontSendKeyEventsToJavascript);
2459
2460// TODO(dtapuska): Enable barrel button selection drag support on Android.
2461// crbug.com/758042
2462#if defined(OS_WIN)
2463 prefs.barrel_button_for_drag_enabled =
2464 base::FeatureList::IsEnabled(features::kDirectManipulationStylus);
2465#endif // defined(OS_WIN)
2466
Rakina Zata Amni4029b6d2020-07-28 02:36:202467 prefs.enable_scroll_animator =
2468 command_line.HasSwitch(switches::kEnableSmoothScrolling) ||
2469 (!command_line.HasSwitch(switches::kDisableSmoothScrolling) &&
2470 gfx::Animation::ScrollAnimationsEnabledBySystem());
2471
2472 prefs.prefers_reduced_motion = gfx::Animation::PrefersReducedMotion();
2473
2474 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
2475 GetRenderViewHost()->GetProcess()->GetID())) {
2476 prefs.loads_images_automatically = true;
2477 prefs.javascript_enabled = true;
2478 }
2479
2480 prefs.viewport_enabled = command_line.HasSwitch(switches::kEnableViewport);
2481
2482 if (IsOverridingUserAgent())
2483 prefs.viewport_meta_enabled = false;
2484
2485 prefs.main_frame_resizes_are_orientation_changes =
2486 command_line.HasSwitch(switches::kMainFrameResizesAreOrientationChanges);
2487
2488 prefs.spatial_navigation_enabled =
2489 command_line.HasSwitch(switches::kEnableSpatialNavigation);
2490
2491 if (IsSpatialNavigationDisabled())
2492 prefs.spatial_navigation_enabled = false;
2493
Rakina Zata Amni4029b6d2020-07-28 02:36:202494 prefs.disable_reading_from_canvas =
2495 command_line.HasSwitch(switches::kDisableReadingFromCanvas);
2496
2497 prefs.strict_mixed_content_checking =
2498 command_line.HasSwitch(switches::kEnableStrictMixedContentChecking);
2499
2500 prefs.strict_powerful_feature_restrictions = command_line.HasSwitch(
2501 switches::kEnableStrictPowerfulFeatureRestrictions);
2502
2503 const std::string blockable_mixed_content_group =
2504 base::FieldTrialList::FindFullName("BlockableMixedContent");
2505 prefs.strictly_block_blockable_mixed_content =
2506 blockable_mixed_content_group == "StrictlyBlockBlockableMixedContent";
2507
2508 const std::string plugin_mixed_content_status =
2509 base::FieldTrialList::FindFullName("PluginMixedContentStatus");
2510 prefs.block_mixed_plugin_content =
2511 plugin_mixed_content_status == "BlockableMixedContent";
2512
2513 prefs.v8_cache_options = GetV8CacheOptions();
2514
2515 prefs.user_gesture_required_for_presentation = !command_line.HasSwitch(
2516 switches::kDisableGestureRequirementForPresentation);
2517
2518 if (HideDownloadUI())
2519 prefs.hide_download_ui = true;
2520
2521 // `media_controls_enabled` is `true` by default.
2522 if (HasPersistentVideo())
2523 prefs.media_controls_enabled = false;
2524
2525#if defined(OS_ANDROID)
2526 display::Display display = display::Screen::GetScreen()->GetPrimaryDisplay();
2527 gfx::Size size = display.GetSizeInPixel();
2528 int min_width = size.width() < size.height() ? size.width() : size.height();
2529 prefs.device_scale_adjustment = GetDeviceScaleAdjustment(
2530 static_cast<int>(min_width / display.device_scale_factor()));
2531#endif // OS_ANDROID
2532
2533 GetContentClient()->browser()->OverrideWebkitPrefs(GetRenderViewHost(),
2534 &prefs);
2535 return prefs;
2536}
2537
2538void WebContentsImpl::SetSlowWebPreferences(
2539 const base::CommandLine& command_line,
Gyuyoung Kim1ac4ca782020-09-11 03:32:512540 blink::web_pref::WebPreferences* prefs) {
Alexander Timin5fdeff22020-09-08 09:20:372541 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetSlowWebPreferences");
2542
Rakina Zata Amni4029b6d2020-07-28 02:36:202543 if (web_preferences_.get()) {
2544#define SET_FROM_CACHE(prefs, field) prefs->field = web_preferences_->field
2545
2546 SET_FROM_CACHE(prefs, touch_event_feature_detection_enabled);
2547 SET_FROM_CACHE(prefs, available_pointer_types);
2548 SET_FROM_CACHE(prefs, available_hover_types);
2549 SET_FROM_CACHE(prefs, primary_pointer_type);
2550 SET_FROM_CACHE(prefs, primary_hover_type);
2551 SET_FROM_CACHE(prefs, pointer_events_max_touch_points);
2552 SET_FROM_CACHE(prefs, number_of_cpu_cores);
2553
2554#if defined(OS_ANDROID)
2555 SET_FROM_CACHE(prefs, video_fullscreen_orientation_lock_enabled);
2556 SET_FROM_CACHE(prefs, video_rotate_to_fullscreen_enabled);
2557#endif
2558
2559#undef SET_FROM_CACHE
2560 } else {
2561 // Every prefs->field modified below should have a SET_FROM_CACHE entry
2562 // above.
2563
2564 // On Android, Touch event feature detection is enabled by default,
2565 // Otherwise default is disabled.
2566 std::string touch_enabled_default_switch =
2567 switches::kTouchEventFeatureDetectionDisabled;
2568#if defined(OS_ANDROID)
2569 touch_enabled_default_switch = switches::kTouchEventFeatureDetectionEnabled;
2570#endif // defined(OS_ANDROID)
2571 const std::string touch_enabled_switch =
2572 command_line.HasSwitch(switches::kTouchEventFeatureDetection)
2573 ? command_line.GetSwitchValueASCII(
2574 switches::kTouchEventFeatureDetection)
2575 : touch_enabled_default_switch;
2576
2577 prefs->touch_event_feature_detection_enabled =
2578 (touch_enabled_switch == switches::kTouchEventFeatureDetectionAuto)
2579 ? (ui::GetTouchScreensAvailability() ==
2580 ui::TouchScreensAvailability::ENABLED)
2581 : (touch_enabled_switch.empty() ||
2582 touch_enabled_switch ==
2583 switches::kTouchEventFeatureDetectionEnabled);
2584
2585 std::tie(prefs->available_pointer_types, prefs->available_hover_types) =
2586 ui::GetAvailablePointerAndHoverTypes();
2587 prefs->primary_pointer_type =
2588 ui::GetPrimaryPointerType(prefs->available_pointer_types);
2589 prefs->primary_hover_type =
2590 ui::GetPrimaryHoverType(prefs->available_hover_types);
2591
2592 prefs->pointer_events_max_touch_points = ui::MaxTouchPoints();
2593
2594 prefs->number_of_cpu_cores = base::SysInfo::NumberOfProcessors();
2595
2596#if defined(OS_ANDROID)
2597 const bool device_is_phone =
2598 ui::GetDeviceFormFactor() == ui::DEVICE_FORM_FACTOR_PHONE;
2599 prefs->video_fullscreen_orientation_lock_enabled = device_is_phone;
2600 prefs->video_rotate_to_fullscreen_enabled = device_is_phone;
2601#endif
2602 }
2603}
2604
2605void WebContentsImpl::OnWebPreferencesChanged() {
Alexander Timin5fdeff22020-09-08 09:20:372606 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnWebPreferencesChanged");
2607
Rakina Zata Amni4029b6d2020-07-28 02:36:202608 // This is defensive code to avoid infinite loops due to code run inside
2609 // SetWebPreferences() accidentally updating more preferences and thus
2610 // calling back into this code. See crbug.com/398751 for one past example.
2611 if (updating_web_preferences_)
2612 return;
2613 updating_web_preferences_ = true;
2614 SetWebPreferences(ComputeWebPreferences());
2615#if defined(OS_ANDROID)
2616 for (FrameTreeNode* node : frame_tree_.Nodes()) {
2617 RenderFrameHostImpl* rfh = node->current_frame_host();
2618 if (rfh->is_local_root()) {
2619 if (auto* rwh = rfh->GetRenderWidgetHost())
2620 rwh->SetForceEnableZoom(web_preferences_->force_enable_zoom);
2621 }
2622 }
2623#endif
2624 updating_web_preferences_ = false;
2625}
2626
Ahmed Fakhryd70bf37b2018-04-04 17:07:242627void WebContentsImpl::NotifyPreferencesChanged() {
Alexander Timin5fdeff22020-09-08 09:20:372628 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::NotifyPreferencesChanged");
2629
Rakina Zata Amni347b70902020-07-22 10:49:042630 // Recompute the WebPreferences based on the current state of the WebContents,
Rakina Zata Amni4029b6d2020-07-28 02:36:202631 // etc. Note that OnWebPreferencesChanged will also call SetWebPreferences and
2632 // send the updated WebPreferences to all RenderViews for this WebContents.
2633 OnWebPreferencesChanged();
Ahmed Fakhryd70bf37b2018-04-04 17:07:242634}
2635
Bruce Long1e3e1f542019-10-16 17:56:282636void WebContentsImpl::SyncRendererPrefs() {
Alexander Timin5fdeff22020-09-08 09:20:372637 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SyncRendererPrefs");
2638
Peter Marshall2dc74e92020-07-29 20:02:302639 blink::mojom::RendererPreferences renderer_preferences = GetRendererPrefs();
Bruce Long1e3e1f542019-10-16 17:56:282640 RenderViewHostImpl::GetPlatformSpecificPrefs(&renderer_preferences);
2641 SendPageMessage(
2642 new PageMsg_SetRendererPrefs(MSG_ROUTING_NONE, renderer_preferences));
2643}
2644
Alexander Timin1cc31f42020-05-12 16:26:012645void WebContentsImpl::OnCookiesAccessed(NavigationHandle* navigation,
2646 const CookieAccessDetails& details) {
Alexander Timin5fdeff22020-09-08 09:20:372647 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnCookiesAccessed",
2648 "navigation_handle", navigation);
Alexander Timin90c20c32020-08-12 15:28:322649 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2650 observer->OnCookiesAccessed(navigation, details);
2651 });
Alexander Timin1cc31f42020-05-12 16:26:012652}
2653
2654void WebContentsImpl::OnCookiesAccessed(RenderFrameHostImpl* rfh,
2655 const CookieAccessDetails& details) {
Alexander Timin5fdeff22020-09-08 09:20:372656 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnCookiesAccessed",
2657 "render_frame_host",
2658 base::trace_event::ToTracedValue(rfh));
Alexander Timin90c20c32020-08-12 15:28:322659 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2660 observer->OnCookiesAccessed(rfh, details);
2661 });
Josh Karlindaba39322019-07-17 23:24:332662}
2663
[email protected]b172aee2012-04-10 17:05:262664void WebContentsImpl::Stop() {
Alexander Timin5fdeff22020-09-08 09:20:372665 TRACE_EVENT0("content", "WebContentsImpl::Stop");
dcheng57e39e22016-01-21 00:25:382666 for (FrameTreeNode* node : frame_tree_.Nodes())
2667 node->StopLoading();
Alexander Timin90c20c32020-08-12 15:28:322668 observers_.ForEachObserver(
2669 [&](WebContentsObserver* observer) { observer->NavigationStopped(); });
[email protected]0bfbf882011-12-22 18:19:272670}
2671
Francois Doray47f759d2018-06-11 18:13:512672void WebContentsImpl::SetPageFrozen(bool frozen) {
Alexander Timin5fdeff22020-09-08 09:20:372673 TRACE_EVENT1("content", "WebContentsImpl::SetPageFrozen", "frozen", frozen);
2674
Francois Doray47f759d2018-06-11 18:13:512675 // A visible page is never frozen.
2676 DCHECK_NE(Visibility::VISIBLE, GetVisibility());
2677
Yuzu Saijo4fa1e9a2020-05-20 02:53:262678 for (auto& entry : frame_tree_.render_view_hosts()) {
2679 entry.second->SetIsFrozen(frozen);
2680 }
Fadi Meawada6573e02018-03-10 00:52:112681}
2682
erikchen6c7df7f7a2018-05-03 18:13:592683std::unique_ptr<WebContents> WebContentsImpl::Clone() {
Alexander Timin5fdeff22020-09-08 09:20:372684 TRACE_EVENT0("content", "WebContentsImpl::Clone");
2685
[email protected]14392a52012-05-02 20:28:442686 // We use our current SiteInstance since the cloned entry will use it anyway.
alexmose201c7cd2015-06-10 17:14:212687 // We pass our own opener so that the cloned page can access it if it was set
[email protected]ed245db2012-12-18 08:00:452688 // before.
[email protected]54944cde2012-12-09 09:24:592689 CreateParams create_params(GetBrowserContext(), GetSiteInstance());
Ian Clelland5cbaaf82017-11-27 22:00:032690 FrameTreeNode* opener = frame_tree_.root()->opener();
2691 RenderFrameHostImpl* opener_rfh = nullptr;
2692 if (opener)
2693 opener_rfh = opener->current_frame_host();
erikchen6c7df7f7a2018-05-03 18:13:592694 std::unique_ptr<WebContentsImpl> tc =
erikchen50735fd2018-05-05 15:08:332695 CreateWithOpener(create_params, opener_rfh);
Lucas Furukawa Gadani5553a152019-01-08 18:55:572696 tc->GetController().CopyStateFrom(&controller_, true);
Alexander Timin90c20c32020-08-12 15:28:322697 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2698 observer->DidCloneToNewWebContents(this, tc.get());
2699 });
[email protected]0bfbf882011-12-22 18:19:272700 return tc;
2701}
2702
[email protected]14392a52012-05-02 20:28:442703void WebContentsImpl::Observe(int type,
[email protected]8ff00d72012-10-23 19:12:212704 const NotificationSource& source,
2705 const NotificationDetails& details) {
Alexander Timin5fdeff22020-09-08 09:20:372706 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::Observe", "type", type);
[email protected]14392a52012-05-02 20:28:442707 switch (type) {
[email protected]8ff00d72012-10-23 19:12:212708 case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: {
2709 RenderWidgetHost* host = Source<RenderWidgetHost>(source).ptr();
[email protected]0b431992014-06-24 00:08:032710 RenderWidgetHostView* view = host->GetView();
2711 if (view == GetFullscreenRenderWidgetHostView()) {
2712 // We cannot just call view_->RestoreFocus() here. On some platforms,
2713 // attempting to focus the currently-invisible WebContentsView will be
2714 // flat-out ignored. Therefore, this boolean is used to track whether
2715 // we will request focus after the fullscreen widget has been
2716 // destroyed.
2717 fullscreen_widget_had_focus_at_shutdown_ = (view && view->HasFocus());
2718 } else {
alexmosc2a8cec2016-05-23 22:19:532719 for (auto i = pending_widget_views_.begin();
[email protected]0b431992014-06-24 00:08:032720 i != pending_widget_views_.end(); ++i) {
2721 if (host->GetView() == i->second) {
2722 pending_widget_views_.erase(i);
2723 break;
2724 }
[email protected]bafe6cd2012-05-23 23:09:502725 }
2726 }
2727 break;
2728 }
[email protected]14392a52012-05-02 20:28:442729 default:
2730 NOTREACHED();
2731 }
2732}
2733
[email protected]ec6c05f2013-10-23 18:41:572734WebContents* WebContentsImpl::GetWebContents() {
2735 return this;
2736}
2737
[email protected]54944cde2012-12-09 09:24:592738void WebContentsImpl::Init(const WebContents::CreateParams& params) {
Alexander Timin5fdeff22020-09-08 09:20:372739 TRACE_EVENT0("content", "WebContentsImpl::Init");
2740
[email protected]fa944cb82013-11-15 17:51:212741 // This is set before initializing the render manager since
[email protected]b0936d22013-11-28 06:47:362742 // RenderFrameHostManager::Init calls back into us via its delegate to ask if
[email protected]fa944cb82013-11-15 17:51:212743 // it should be hidden.
Francois Doraye6161152018-03-27 22:05:372744 visibility_ =
2745 params.initially_hidden ? Visibility::HIDDEN : Visibility::VISIBLE;
[email protected]d6fa88f2013-10-18 16:00:432746
Sebastien Marchand28cf23182018-06-20 02:39:352747 if (!params.last_active_time.is_null())
2748 last_active_time_ = params.last_active_time;
2749
dcheng3ce04b62015-10-26 23:30:552750 scoped_refptr<SiteInstance> site_instance = params.site_instance;
2751 if (!site_instance)
2752 site_instance = SiteInstance::Create(params.browser_context);
Lukasz Anforowicz3caa8372018-06-05 17:22:072753 if (params.desired_renderer_state == CreateParams::kNoRendererProcess) {
2754 static_cast<SiteInstanceImpl*>(site_instance.get())
2755 ->PreventAssociationWithSpareProcess();
2756 }
dcheng3ce04b62015-10-26 23:30:552757
Fergal Dalycb0c1fdf2020-03-16 07:13:492758 GetRenderManager()->InitRoot(site_instance.get(),
2759 params.renderer_initiated_creation);
lukasza464d8692016-02-22 19:26:322760
lukasza5140a412016-09-15 21:12:302761 // blink::FrameTree::setName always keeps |unique_name| empty in case of a
2762 // main frame - let's do the same thing here.
2763 std::string unique_name;
lukasza464d8692016-02-22 19:26:322764 frame_tree_.root()->SetFrameName(params.main_frame_name, unique_name);
[email protected]d1198fd2012-08-13 22:50:192765
[email protected]fc2b46b2014-05-03 16:33:452766 WebContentsViewDelegate* delegate =
2767 GetContentClient()->browser()->GetWebContentsViewDelegate(this);
2768
W. James MacLean2539adb32019-12-13 00:40:442769 if (browser_plugin_guest_) {
Fergal Daly55b6d722020-09-11 07:56:332770 view_ = std::make_unique<WebContentsViewChildFrame>(
2771 this, delegate, &render_view_host_delegate_view_);
sky52a39e342016-12-17 17:23:222772 } else {
2773 view_.reset(CreateWebContentsView(this, delegate,
2774 &render_view_host_delegate_view_));
[email protected]d1198fd2012-08-13 22:50:192775 }
[email protected]fc2b46b2014-05-03 16:33:452776 CHECK(render_view_host_delegate_view_);
[email protected]d1198fd2012-08-13 22:50:192777 CHECK(view_.get());
2778
danakjfc5184932019-09-12 18:08:322779 view_->CreateView(params.context);
[email protected]d1198fd2012-08-13 22:50:192780
brettw4b461082016-11-19 18:55:162781#if BUILDFLAG(ENABLE_PLUGINS)
Fergal Daly55b6d722020-09-11 07:56:332782 plugin_content_origin_allowlist_ =
2783 std::make_unique<PluginContentOriginAllowlist>(this);
tommyclieb25b2a2014-11-03 19:45:092784#endif
2785
[email protected]d1198fd2012-08-13 22:50:192786 registrar_.Add(this,
[email protected]8ff00d72012-10-23 19:12:212787 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
2788 NotificationService::AllBrowserContextsAndSources());
[email protected]f28ef9a32014-05-12 16:36:102789
Fergal Daly55b6d722020-09-11 07:56:332790 screen_orientation_provider_ =
2791 std::make_unique<ScreenOrientationProvider>(this);
[email protected]01f83f92014-06-17 14:41:542792
mfomitchev2b8b066a2016-01-28 19:23:152793#if defined(OS_ANDROID)
Oksana Zhuravlova0b634332019-10-28 23:04:222794 DateTimeChooserAndroid::CreateForWebContents(this);
[email protected]583418cc2013-01-17 14:01:102795#endif
fsamuel7310a4262014-12-05 05:06:442796
2797 // BrowserPluginGuest::Init needs to be called after this WebContents has
W. James MacLean6e78da342019-12-13 15:13:232798 // a RenderWidgetHostViewChildFrame. That is, |view_->CreateView| above.
fsamuel7310a4262014-12-05 05:06:442799 if (browser_plugin_guest_)
2800 browser_plugin_guest_->Init();
nickf9acfbe2014-12-23 19:12:372801
Fergal Daly55b6d722020-09-11 07:56:332802 for (auto& i : g_created_callbacks.Get())
2803 i.Run(this);
naskob21fe4872015-02-24 14:15:562804
2805 // If the WebContents creation was renderer-initiated, it means that the
2806 // corresponding RenderView and main RenderFrame have already been created.
2807 // Ensure observers are notified about this.
2808 if (params.renderer_initiated_creation) {
Fergal Dalybb2d6592020-06-02 05:02:332809 GetRenderViewHost()->GetWidget()->set_renderer_initialized(true);
Alex Moshchuk27caae82017-09-11 23:11:182810 GetRenderViewHost()->DispatchRenderViewCreated();
naskob21fe4872015-02-24 14:15:562811 GetRenderManager()->current_frame_host()->SetRenderFrameCreated(true);
2812 }
naskof5940b9f2015-03-02 23:04:052813
lof84501da082016-05-23 21:22:542814 // Create the renderer process in advance if requested.
Lukasz Anforowicz3caa8372018-06-05 17:22:072815 if (params.desired_renderer_state ==
2816 CreateParams::kInitializeAndWarmupRendererProcess) {
lof84501da082016-05-23 21:22:542817 if (!GetRenderManager()->current_frame_host()->IsRenderFrameLive()) {
2818 GetRenderManager()->InitRenderView(GetRenderViewHost(), nullptr);
2819 }
2820 }
2821
naskof5940b9f2015-03-02 23:04:052822 // Ensure that observers are notified of the creation of this WebContents's
2823 // main RenderFrameHost. It must be done here for main frames, since the
2824 // NotifySwappedFromRenderManager expects view_ to already be created and that
2825 // happens after RenderFrameHostManager::Init.
2826 NotifySwappedFromRenderManager(
2827 nullptr, GetRenderManager()->current_frame_host(), true);
Albert J. Wonge76bf0b82019-09-27 07:47:062828
2829 // For WebContents that are never shown, do critical initialization here which
2830 // would normally only happen when the WebContents is shown.
2831 if (params.is_never_visible) {
2832 // This has just been created so there can only be one frame. Thus it is
2833 // safe to initialize the root.
2834 GetMainFrame()->Init();
2835 }
[email protected]d1198fd2012-08-13 22:50:192836}
2837
[email protected]7fff43e2013-05-21 20:21:102838void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl* web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:372839 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnWebContentsDestroyed");
2840
[email protected]7fff43e2013-05-21 20:21:102841 RemoveDestructionObserver(web_contents);
2842
[email protected]ceee8cd2013-03-08 04:59:512843 // Clear a pending contents that has been closed before being shown.
alexmosc2a8cec2016-05-23 22:19:532844 for (auto iter = pending_contents_.begin(); iter != pending_contents_.end();
[email protected]ceee8cd2013-03-08 04:59:512845 ++iter) {
Joel Hockey8c2011b22020-04-30 05:07:192846 if (iter->second.contents.get() != web_contents)
[email protected]ceee8cd2013-03-08 04:59:512847 continue;
erikchenbee5c9622018-04-27 19:30:252848
2849 // Someone else has deleted the WebContents. That should never happen!
2850 // TODO(erikchen): Fix semantics here. https://crbug.com/832879.
Joel Hockey8c2011b22020-04-30 05:07:192851 iter->second.contents.release();
[email protected]ceee8cd2013-03-08 04:59:512852 pending_contents_.erase(iter);
[email protected]ceee8cd2013-03-08 04:59:512853 return;
2854 }
2855 NOTREACHED();
[email protected]14392a52012-05-02 20:28:442856}
2857
[email protected]7fff43e2013-05-21 20:21:102858void WebContentsImpl::AddDestructionObserver(WebContentsImpl* web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:372859 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
2860 "WebContentsImpl::AddDestructionObserver");
2861
Jan Wilken Dörrie73c901e2019-06-12 09:02:322862 if (!base::Contains(destruction_observers_, web_contents)) {
[email protected]7fff43e2013-05-21 20:21:102863 destruction_observers_[web_contents] =
Jeremy Roman04f27c372017-10-27 15:20:552864 std::make_unique<DestructionObserver>(this, web_contents);
[email protected]7fff43e2013-05-21 20:21:102865 }
2866}
2867
2868void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl* web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:372869 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
2870 "WebContentsImpl::RemoveDestructionObserver");
avia8cf81982016-08-12 20:28:462871 destruction_observers_.erase(web_contents);
[email protected]7fff43e2013-05-21 20:21:102872}
2873
[email protected]b172aee2012-04-10 17:05:262874void WebContentsImpl::AddObserver(WebContentsObserver* observer) {
Alexander Timin5fdeff22020-09-08 09:20:372875 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
2876 "WebContentsImpl::AddObserver");
[email protected]be1f56ab2011-12-22 06:55:312877 observers_.AddObserver(observer);
2878}
2879
[email protected]b172aee2012-04-10 17:05:262880void WebContentsImpl::RemoveObserver(WebContentsObserver* observer) {
Alexander Timin5fdeff22020-09-08 09:20:372881 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
2882 "WebContentsImpl::RemoveObserver");
[email protected]be1f56ab2011-12-22 06:55:312883 observers_.RemoveObserver(observer);
2884}
2885
[email protected]948481d2014-06-11 18:32:222886std::set<RenderWidgetHostView*>
2887WebContentsImpl::GetRenderWidgetHostViewsInTree() {
2888 std::set<RenderWidgetHostView*> set;
Carlos IL07f282f2020-05-15 22:58:292889 for (RenderFrameHost* rfh : GetAllFrames()) {
2890 if (RenderWidgetHostView* rwhv = static_cast<RenderFrameHostImpl*>(rfh)
2891 ->frame_tree_node()
2892 ->render_manager()
2893 ->GetRenderWidgetHostView()) {
lfgf949e0e2017-05-10 22:18:112894 set.insert(rwhv);
dchengafb53e22016-02-04 08:11:082895 }
[email protected]948481d2014-06-11 18:32:222896 }
[email protected]de3c5d82014-05-28 22:12:592897 return set;
2898}
2899
Adithya Srinivasane6e7f842019-12-16 18:41:362900std::set<RenderWidgetHostView*>
2901WebContentsImpl::GetRenderWidgetHostViewsInWebContentsTree() {
2902 std::set<RenderWidgetHostView*> result;
2903 GetRenderWidgetHostViewsInWebContentsTree(result);
2904 return result;
2905}
2906
2907void WebContentsImpl::GetRenderWidgetHostViewsInWebContentsTree(
2908 std::set<RenderWidgetHostView*>& result) {
2909 std::set<RenderWidgetHostView*> views = GetRenderWidgetHostViewsInTree();
2910 result.insert(views.begin(), views.end());
2911 for (auto* inner_web_contents : GetInnerWebContents()) {
2912 static_cast<WebContentsImpl*>(inner_web_contents)
2913 ->GetRenderWidgetHostViewsInWebContentsTree(result);
2914 }
2915}
2916
[email protected]b172aee2012-04-10 17:05:262917void WebContentsImpl::Activate() {
Alexander Timin5fdeff22020-09-08 09:20:372918 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Activate");
[email protected]d5f942ba2008-09-26 19:30:342919 if (delegate_)
2920 delegate_->ActivateContents(this);
2921}
2922
avi3e4b8512015-11-11 01:55:492923void WebContentsImpl::LostCapture(RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:372924 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::LostCapture",
2925 "render_widget_host", render_widget_host);
avi3e4b8512015-11-11 01:55:492926 if (!RenderViewHostImpl::From(render_widget_host))
2927 return;
2928
[email protected]63954792011-07-11 04:17:482929 if (delegate_)
2930 delegate_->LostCapture();
2931}
2932
Yue Ru Sun979c4b162019-11-06 16:11:042933ukm::SourceId
2934WebContentsImpl::GetUkmSourceIdForLastCommittedSourceIncludingSameDocument()
2935 const {
2936 return last_committed_source_id_including_same_document_;
2937}
2938
Ahmed Fakhryfaa32d22018-10-05 15:56:162939void WebContentsImpl::SetTopControlsShownRatio(
2940 RenderWidgetHostImpl* render_widget_host,
2941 float ratio) {
Alexander Timin5fdeff22020-09-08 09:20:372942 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetTopControlsShownRatio",
2943 "render_widget_host", render_widget_host, "ratio",
2944 ratio);
Ahmed Fakhryfaa32d22018-10-05 15:56:162945 if (!delegate_)
2946 return;
2947
2948 RenderFrameHostImpl* rfh = GetMainFrame();
2949 if (!rfh || render_widget_host != rfh->GetRenderWidgetHost())
2950 return;
2951
2952 delegate_->SetTopControlsShownRatio(this, ratio);
Ahmed Fakhry58e6ef542018-09-04 18:05:382953}
2954
Ahmed Fakhry58e6ef542018-09-04 18:05:382955void WebContentsImpl::SetTopControlsGestureScrollInProgress(bool in_progress) {
Alexander Timin5fdeff22020-09-08 09:20:372956 OPTIONAL_TRACE_EVENT1(
2957 "content", "WebContentsImpl::SetTopControlsGestureScrollInProgress",
2958 "in_progress", in_progress);
Ahmed Fakhry58e6ef542018-09-04 18:05:382959 if (delegate_)
2960 delegate_->SetTopControlsGestureScrollInProgress(in_progress);
2961}
2962
lazyboy63f5b312015-11-23 20:19:522963void WebContentsImpl::RenderWidgetCreated(
2964 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:372965 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderWidgetCreated",
2966 "render_widget_host", render_widget_host);
lazyboy63f5b312015-11-23 20:19:522967 created_widgets_.insert(render_widget_host);
2968}
2969
[email protected]b24b68a2012-09-24 21:57:262970void WebContentsImpl::RenderWidgetDeleted(
2971 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:372972 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderWidgetDeleted",
2973 "render_widget_host", render_widget_host);
lazyboy63f5b312015-11-23 20:19:522974 // Note that |is_being_destroyed_| can be true at this point as
2975 // ~WebContentsImpl() calls RFHM::ClearRFHsPendingShutdown(), which might lead
2976 // us here.
2977 created_widgets_.erase(render_widget_host);
[email protected]b24b68a2012-09-24 21:57:262978
lazyboy63f5b312015-11-23 20:19:522979 if (is_being_destroyed_)
2980 return;
[email protected]44470a22013-01-24 01:21:542981
2982 if (render_widget_host &&
alexmosc9e76ec2016-05-16 22:59:372983 render_widget_host->GetRoutingID() == fullscreen_widget_routing_id_ &&
2984 render_widget_host->GetProcess()->GetID() ==
2985 fullscreen_widget_process_id_) {
[email protected]4aebbca2013-09-17 22:26:492986 if (delegate_ && delegate_->EmbedsFullscreenWidget())
mlamouri7a78d6fd2015-01-17 13:23:532987 delegate_->ExitFullscreenModeForTab(this);
Alexander Timin90c20c32020-08-12 15:28:322988 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2989 observer->DidDestroyFullscreenWidget();
2990 });
alexmosc9e76ec2016-05-16 22:59:372991 fullscreen_widget_process_id_ = ChildProcessHost::kInvalidUniqueID;
[email protected]44470a22013-01-24 01:21:542992 fullscreen_widget_routing_id_ = MSG_ROUTING_NONE;
[email protected]0b431992014-06-24 00:08:032993 if (fullscreen_widget_had_focus_at_shutdown_)
2994 view_->RestoreFocus();
[email protected]44470a22013-01-24 01:21:542995 }
lfgbee1e0a2016-06-08 21:24:212996
lfg7d4caad2017-03-22 09:01:452997 if (render_widget_host == mouse_lock_widget_)
lfgff8dfc8d2016-10-21 17:42:322998 LostMouseLock(mouse_lock_widget_);
Joe Downing192998b22018-03-22 15:51:362999
Joe Downingc1a57efe2018-05-09 18:23:543000 CancelKeyboardLock(render_widget_host);
[email protected]b24b68a2012-09-24 21:57:263001}
3002
miu9e14e492014-10-25 02:39:043003void WebContentsImpl::RenderWidgetGotFocus(
3004 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:373005 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderWidgetGotFocus",
3006 "render_widget_host", render_widget_host);
calamity7fe55ce2015-04-10 03:59:373007 // Notify the observers if an embedded fullscreen widget was focused.
3008 if (delegate_ && render_widget_host && delegate_->EmbedsFullscreenWidget() &&
3009 render_widget_host->GetView() == GetFullscreenRenderWidgetHostView()) {
Michael Thiessen896405db2017-07-20 17:52:323010 NotifyWebContentsFocused(render_widget_host);
calamity7fe55ce2015-04-10 03:59:373011 }
miu9e14e492014-10-25 02:39:043012}
3013
zijiehe3bee08e22017-05-17 04:14:463014void WebContentsImpl::RenderWidgetLostFocus(
3015 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:373016 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderWidgetLostFocus",
3017 "render_widget_host", render_widget_host);
Michael Thiessen896405db2017-07-20 17:52:323018 // Notify the observers if an embedded fullscreen widget lost focus.
3019 if (delegate_ && render_widget_host && delegate_->EmbedsFullscreenWidget() &&
3020 render_widget_host->GetView() == GetFullscreenRenderWidgetHostView()) {
3021 NotifyWebContentsLostFocus(render_widget_host);
3022 }
zijiehe3bee08e22017-05-17 04:14:463023}
3024
estaded0a0c992015-01-21 14:12:063025void WebContentsImpl::RenderWidgetWasResized(
rouslan2f5993f2015-01-29 00:18:313026 RenderWidgetHostImpl* render_widget_host,
3027 bool width_changed) {
Alexander Timin5fdeff22020-09-08 09:20:373028 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RenderWidgetWasResized",
3029 "render_widget_host", render_widget_host,
3030 "width_changed", width_changed);
creisc014b402015-04-23 16:41:453031 RenderFrameHostImpl* rfh = GetMainFrame();
estadece344ec2015-01-23 00:12:293032 if (!rfh || render_widget_host != rfh->GetRenderWidgetHost())
estaded0a0c992015-01-21 14:12:063033 return;
estaded0a0c992015-01-21 14:12:063034
Alexander Timin90c20c32020-08-12 15:28:323035 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3036 observer->MainFrameWasResized(width_changed);
3037 });
estaded0a0c992015-01-21 14:12:063038}
3039
skyf65d9bb2017-03-24 02:26:393040KeyboardEventProcessingResult WebContentsImpl::PreHandleKeyboardEvent(
3041 const NativeWebKeyboardEvent& event) {
Alexander Timin5fdeff22020-09-08 09:20:373042 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
3043 "WebContentsImpl::PreHandleKeyboardEvent");
W. James MacLeane1187272019-11-12 03:42:483044 auto* outermost_contents = GetOutermostWebContents();
3045 // TODO(wjmaclean): Generalize this to forward all key events to the outermost
3046 // delegate's handler.
Avi Drissman97aef042020-06-30 21:04:483047 if (outermost_contents != this && IsFullscreen() &&
W. James MacLeane1187272019-11-12 03:42:483048 event.windows_key_code == ui::VKEY_ESCAPE) {
3049 // When an inner WebContents has focus and is fullscreen, redirect <esc>
3050 // key events to the outermost WebContents so it can be handled by that
3051 // WebContents' delegate.
3052 if (outermost_contents->PreHandleKeyboardEvent(event) ==
3053 KeyboardEventProcessingResult::HANDLED) {
3054 return KeyboardEventProcessingResult::HANDLED;
3055 }
3056 }
skyf65d9bb2017-03-24 02:26:393057 return delegate_ ? delegate_->PreHandleKeyboardEvent(this, event)
3058 : KeyboardEventProcessingResult::NOT_HANDLED;
[email protected]63954792011-07-11 04:17:483059}
3060
Dave Tapuska344399e2019-09-09 15:18:263061bool WebContentsImpl::HandleMouseEvent(const blink::WebMouseEvent& event) {
Alexander Timin5fdeff22020-09-08 09:20:373062 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
3063 "WebContentsImpl::HandleMouseEvent");
Dave Tapuska344399e2019-09-09 15:18:263064 // Handle mouse button back/forward in the browser process after the render
3065 // process is done with the event. This ensures all renderer-initiated history
3066 // navigations can be treated consistently.
3067 if (event.GetType() == blink::WebInputEvent::Type::kMouseUp) {
3068 WebContentsImpl* outermost = GetOutermostWebContents();
3069 if (event.button == blink::WebPointerProperties::Button::kBack &&
3070 outermost->controller_.CanGoBack()) {
3071 outermost->controller_.GoBack();
3072 return true;
3073 } else if (event.button == blink::WebPointerProperties::Button::kForward &&
3074 outermost->controller_.CanGoForward()) {
3075 outermost->controller_.GoForward();
3076 return true;
3077 }
3078 }
3079 return false;
3080}
3081
Scott Violetd5caa872018-10-16 22:00:513082bool WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
Alexander Timin5fdeff22020-09-08 09:20:373083 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
3084 "WebContentsImpl::HandleKeyboardEvent");
[email protected]0b094002014-08-20 18:28:103085 if (browser_plugin_embedder_ &&
3086 browser_plugin_embedder_->HandleKeyboardEvent(event)) {
Scott Violetd5caa872018-10-16 22:00:513087 return true;
[email protected]0b094002014-08-20 18:28:103088 }
Scott Violetd5caa872018-10-16 22:00:513089 return delegate_ && delegate_->HandleKeyboardEvent(this, event);
[email protected]63954792011-07-11 04:17:483090}
3091
Alexander Timin5fdeff22020-09-08 09:20:373092bool WebContentsImpl::HandleWheelEvent(const blink::WebMouseWheelEvent& event) {
3093 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
3094 "WebContentsImpl::HandleWheelEvent");
Avi Drissman7c57be72020-07-29 20:09:463095#if !defined(OS_MAC)
lanweia93644f2015-01-21 22:00:333096 // On platforms other than Mac, control+mousewheel may change zoom. On Mac,
3097 // this isn't done for two reasons:
[email protected]bccc4472013-04-18 16:37:193098 // -the OS already has a gesture to do this through pinch-zoom
3099 // -if a user starts an inertial scroll, let's go, and presses control
3100 // (i.e. control+tab) then the OS's buffered scroll events will come in
3101 // with control key set which isn't what the user wants
Blink Reformat1c4d759e2017-04-09 16:34:543102 if (delegate_ && event.wheel_ticks_y &&
Ehsan Karamad0f83cb112018-09-06 22:07:363103 event.event_action == blink::WebMouseWheelEvent::EventAction::kPageZoom) {
w.shackleton49bcd392016-01-06 17:38:223104 // Count only integer cumulative scrolls as zoom events; this handles
3105 // smooth scroll and regular scroll device behavior.
Blink Reformat1c4d759e2017-04-09 16:34:543106 zoom_scroll_remainder_ += event.wheel_ticks_y;
w.shackleton49bcd392016-01-06 17:38:223107 int whole_zoom_scroll_remainder_ = std::lround(zoom_scroll_remainder_);
3108 zoom_scroll_remainder_ -= whole_zoom_scroll_remainder_;
3109 if (whole_zoom_scroll_remainder_ != 0) {
3110 delegate_->ContentsZoomChange(whole_zoom_scroll_remainder_ > 0);
3111 }
[email protected]fb3f066e2013-02-12 19:12:523112 return true;
3113 }
[email protected]bccc4472013-04-18 16:37:193114#endif
[email protected]fb3f066e2013-02-12 19:12:523115 return false;
3116}
3117
[email protected]04bce562014-01-30 05:34:543118bool WebContentsImpl::PreHandleGestureEvent(
3119 const blink::WebGestureEvent& event) {
Alexander Timin5fdeff22020-09-08 09:20:373120 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
3121 "WebContentsImpl::PreHandleGestureEvent");
[email protected]28042d32014-02-03 14:10:033122 return delegate_ && delegate_->PreHandleGestureEvent(this, event);
[email protected]04bce562014-01-30 05:34:543123}
3124
kenrb2a565f82015-09-02 20:24:593125RenderWidgetHostInputEventRouter* WebContentsImpl::GetInputEventRouter() {
wjmacleane31234f2015-12-14 17:20:453126 if (!is_being_destroyed_ && GetOuterWebContents())
3127 return GetOuterWebContents()->GetInputEventRouter();
3128
3129 if (!rwh_input_event_router_.get() && !is_being_destroyed_)
Fergal Daly55b6d722020-09-11 07:56:333130 rwh_input_event_router_ =
3131 std::make_unique<RenderWidgetHostInputEventRouter>();
kenrb2a565f82015-09-02 20:24:593132 return rwh_input_event_router_.get();
3133}
3134
alexmos3fcd0ca2015-10-23 18:18:333135void WebContentsImpl::ReplicatePageFocus(bool is_focused) {
Alexander Timin5fdeff22020-09-08 09:20:373136 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ReplicatePageFocus",
3137 "is_focused", is_focused);
alexmos3fcd0ca2015-10-23 18:18:333138 // Focus loss may occur while this WebContents is being destroyed. Don't
3139 // send the message in this case, as the main frame's RenderFrameHost and
3140 // other state has already been cleared.
3141 if (is_being_destroyed_)
3142 return;
3143
3144 frame_tree_.ReplicatePageFocus(is_focused);
3145}
3146
alexmosc4cbacb2015-11-21 01:29:223147RenderWidgetHostImpl* WebContentsImpl::GetFocusedRenderWidgetHost(
3148 RenderWidgetHostImpl* receiving_widget) {
alexmosc4cbacb2015-11-21 01:29:223149 // Events for widgets other than the main frame (e.g., popup menus) should be
3150 // forwarded directly to the widget they arrived on.
3151 if (receiving_widget != GetMainFrame()->GetRenderWidgetHost())
3152 return receiving_widget;
alexmosc4d183e2015-11-06 00:46:523153
paulmeyerfeafc2d2017-04-25 21:46:403154 // If the focused WebContents is a guest WebContents, then get the focused
3155 // frame in the embedder WebContents instead.
W. James MacLean13d834d2019-12-04 16:06:453156 FrameTreeNode* focused_frame =
3157 GetFocusedWebContents()->frame_tree_.GetFocusedFrame();
lfg1453e412017-04-11 00:48:503158
alexmosc4d183e2015-11-06 00:46:523159 if (!focused_frame)
alexmosc4cbacb2015-11-21 01:29:223160 return receiving_widget;
alexmosc4d183e2015-11-06 00:46:523161
alexmos732ca3a2015-12-08 02:01:023162 // The view may be null if a subframe's renderer process has crashed while
3163 // the subframe has focus. Drop the event in that case. Do not give
3164 // it to the main frame, so that the user doesn't unexpectedly type into the
3165 // wrong frame if a focused subframe renderer crashes while they type.
3166 RenderWidgetHostView* view = focused_frame->current_frame_host()->GetView();
3167 if (!view)
3168 return nullptr;
3169
3170 return RenderWidgetHostImpl::From(view->GetRenderWidgetHost());
alexmosc4d183e2015-11-06 00:46:523171}
3172
avallee9993fca2016-11-17 06:16:503173RenderWidgetHostImpl* WebContentsImpl::GetRenderWidgetHostWithPageFocus() {
lfg1453e412017-04-11 00:48:503174 WebContentsImpl* focused_web_contents = GetFocusedWebContents();
3175
lfg1453e412017-04-11 00:48:503176 return focused_web_contents->GetMainFrame()->GetRenderWidgetHost();
avallee9993fca2016-11-17 06:16:503177}
3178
Avi Drissmand1d25652020-03-06 21:28:583179bool WebContentsImpl::CanEnterFullscreenMode() {
Avi Drissman33972942020-06-19 14:16:013180 // It's possible that this WebContents was spawned while blocking UI was on
3181 // the screen, or that it was downstream from a WebContents when UI was
3182 // blocked. Therefore, disqualify it from fullscreen if it or any upstream
3183 // WebContents has an active blocker.
3184 auto openers = GetAllOpeningWebContents(this);
3185 return std::all_of(openers.begin(), openers.end(), [](auto* opener) {
3186 return opener->fullscreen_blocker_count_ == 0;
3187 });
Avi Drissmand1d25652020-03-06 21:28:583188}
3189
Dave Tapuska3ed44192018-05-01 18:53:303190void WebContentsImpl::EnterFullscreenMode(
Mike Wasserman4ca09792020-05-29 17:44:433191 RenderFrameHost* requesting_frame,
Dave Tapuskaa4189512019-10-15 20:27:343192 const blink::mojom::FullscreenOptions& options) {
Alexander Timin5fdeff22020-09-08 09:20:373193 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::EnterFullscreenMode");
Avi Drissmand1d25652020-03-06 21:28:583194 DCHECK(CanEnterFullscreenMode());
3195
mlamouri7a78d6fd2015-01-17 13:23:533196 // This method is being called to enter renderer-initiated fullscreen mode.
3197 // Make sure any existing fullscreen widget is shut down first.
[email protected]4aebbca2013-09-17 22:26:493198 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
avi85a4cef2015-12-18 20:13:373199 if (widget_view) {
3200 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())
3201 ->ShutdownAndDestroyWidget(true);
3202 }
[email protected]4aebbca2013-09-17 22:26:493203
Joe Downing13dd76b2018-04-09 18:32:153204 if (delegate_) {
Mike Wasserman4ca09792020-05-29 17:44:433205 delegate_->EnterFullscreenModeForTab(requesting_frame, options);
mlamouri7a78d6fd2015-01-17 13:23:533206
Joe Downing13dd76b2018-04-09 18:32:153207 if (keyboard_lock_widget_)
3208 delegate_->RequestKeyboardLock(this, esc_key_locked_);
3209 }
3210
Alexander Timin90c20c32020-08-12 15:28:323211 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3212 observer->DidToggleFullscreenModeForTab(IsFullscreen(), false);
3213 });
Avi Drissman33972942020-06-19 14:16:013214 FullscreenContentsSet(GetBrowserContext())->insert(this);
mlamouri7a78d6fd2015-01-17 13:23:533215}
3216
bokanece34a82016-01-28 19:49:463217void WebContentsImpl::ExitFullscreenMode(bool will_cause_resize) {
Alexander Timin5fdeff22020-09-08 09:20:373218 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ExitFullscreenMode",
3219 "will_cause_resize", will_cause_resize);
mlamouri7a78d6fd2015-01-17 13:23:533220 // This method is being called to leave renderer-initiated fullscreen mode.
3221 // Make sure any existing fullscreen widget is shut down first.
3222 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
avi85a4cef2015-12-18 20:13:373223 if (widget_view) {
3224 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())
3225 ->ShutdownAndDestroyWidget(true);
3226 }
mlamouri7a78d6fd2015-01-17 13:23:533227
Joe Downing13dd76b2018-04-09 18:32:153228 if (delegate_) {
mlamouri7a78d6fd2015-01-17 13:23:533229 delegate_->ExitFullscreenModeForTab(this);
[email protected]657c8e02014-03-19 19:18:373230
Joe Downing13dd76b2018-04-09 18:32:153231 if (keyboard_lock_widget_)
3232 delegate_->CancelKeyboardLockRequest(this);
3233 }
3234
bokanece34a82016-01-28 19:49:463235 // The fullscreen state is communicated to the renderer through a resize
3236 // message. If the change in fullscreen state doesn't cause a view resize
3237 // then we must ensure web contents exit the fullscreen state by explicitly
3238 // sending a resize message. This is required for the situation of the browser
3239 // moving the view into a "browser fullscreen" state and then the contents
3240 // entering "tab fullscreen". Exiting the contents "tab fullscreen" then won't
3241 // have the side effect of the view resizing, hence the explicit call here is
3242 // required.
3243 if (!will_cause_resize) {
3244 if (RenderWidgetHostView* rwhv = GetRenderWidgetHostView()) {
3245 if (RenderWidgetHost* render_widget_host = rwhv->GetRenderWidgetHost())
Fady Samuel0b911822018-04-25 13:22:163246 render_widget_host->SynchronizeVisualProperties();
bokanece34a82016-01-28 19:49:463247 }
scheib3dcb6c932015-02-23 10:55:583248 }
3249
Arthur Sonzogni929d29f2018-09-17 14:19:443250 current_fullscreen_frame_ = nullptr;
Becca Hughese9e27952018-06-25 17:08:273251
Alexander Timin90c20c32020-08-12 15:28:323252 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3253 observer->DidToggleFullscreenModeForTab(IsFullscreen(), will_cause_resize);
3254 });
Becca Hughesd11d6502018-07-31 17:01:283255
3256 if (display_cutout_host_impl_)
3257 display_cutout_host_impl_->DidExitFullscreen();
Avi Drissman33972942020-06-19 14:16:013258
3259 FullscreenContentsSet(GetBrowserContext())->erase(this);
[email protected]8a5e0ca2011-08-25 06:30:473260}
3261
Becca Hughesfd5d8f892018-06-14 18:23:363262void WebContentsImpl::FullscreenStateChanged(RenderFrameHost* rfh,
3263 bool is_fullscreen) {
Alexander Timin5fdeff22020-09-08 09:20:373264 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::FullscreenStateChanged",
3265 "render_frame_host", rfh, "is_fullscreen",
3266 is_fullscreen);
Arthur Sonzogni929d29f2018-09-17 14:19:443267 RenderFrameHostImpl* frame = static_cast<RenderFrameHostImpl*>(rfh);
Becca Hughesfd5d8f892018-06-14 18:23:363268
3269 if (is_fullscreen) {
Jan Wilken Dörrie531be7ca2019-06-07 10:05:573270 if (!base::Contains(fullscreen_frames_, frame)) {
Arthur Sonzogni929d29f2018-09-17 14:19:443271 fullscreen_frames_.insert(frame);
3272 FullscreenFrameSetUpdated();
Becca Hughesfd5d8f892018-06-14 18:23:363273 }
Arthur Sonzogni929d29f2018-09-17 14:19:443274 return;
3275 }
Becca Hughesfd5d8f892018-06-14 18:23:363276
Arthur Sonzogni929d29f2018-09-17 14:19:443277 // If |frame| is no longer in fullscreen, remove it and any descendants.
3278 // See https://fullscreen.spec.whatwg.org.
Arthur Sonzogni969a794e2018-10-11 08:56:093279 size_t size_before_deletion = fullscreen_frames_.size();
3280 base::EraseIf(fullscreen_frames_, [&](RenderFrameHostImpl* current) {
3281 return (current == frame || current->IsDescendantOf(frame));
Arthur Sonzogni929d29f2018-09-17 14:19:443282 });
3283
Arthur Sonzogni969a794e2018-10-11 08:56:093284 if (size_before_deletion != fullscreen_frames_.size())
Arthur Sonzogni929d29f2018-09-17 14:19:443285 FullscreenFrameSetUpdated();
3286}
3287
3288void WebContentsImpl::FullscreenFrameSetUpdated() {
Alexander Timin5fdeff22020-09-08 09:20:373289 OPTIONAL_TRACE_EVENT0("content",
3290 "WebContentsImpl::FullscreenFrameSetUpdated");
Arthur Sonzogni929d29f2018-09-17 14:19:443291 if (fullscreen_frames_.empty()) {
3292 current_fullscreen_frame_ = nullptr;
3293 return;
Becca Hughesfd5d8f892018-06-14 18:23:363294 }
3295
Arthur Sonzogni929d29f2018-09-17 14:19:443296 // Find the current fullscreen frame and call the observers.
3297 // If frame A is fullscreen, then frame B goes into inner fullscreen, then B
3298 // exits fullscreen - that will result in A being fullscreen.
3299 RenderFrameHostImpl* new_fullscreen_frame = *std::max_element(
3300 fullscreen_frames_.begin(), fullscreen_frames_.end(), FrameCompareDepth);
Becca Hughesfd5d8f892018-06-14 18:23:363301
Arthur Sonzogni929d29f2018-09-17 14:19:443302 // If we have already notified observers about this frame then we should not
3303 // fire the observers again.
3304 if (new_fullscreen_frame == current_fullscreen_frame_)
3305 return;
3306 current_fullscreen_frame_ = new_fullscreen_frame;
Becca Hughesfd5d8f892018-06-14 18:23:363307
Alexander Timin90c20c32020-08-12 15:28:323308 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3309 observer->DidAcquireFullscreen(new_fullscreen_frame);
3310 });
Arthur Sonzogni929d29f2018-09-17 14:19:443311 if (display_cutout_host_impl_)
3312 display_cutout_host_impl_->DidAcquireFullscreen(new_fullscreen_frame);
Becca Hughesfd5d8f892018-06-14 18:23:363313}
3314
Collin Baker989e0882019-11-01 01:27:173315void WebContentsImpl::UpdateVisibilityAndNotifyPageAndView(
3316 Visibility new_visibility) {
Alexander Timin5fdeff22020-09-08 09:20:373317 OPTIONAL_TRACE_EVENT1("content",
3318 "WebContentsImpl::UpdateVisibilityAndNotifyPageAndView",
3319 "new_visibility", static_cast<int>(new_visibility));
Collin Baker989e0882019-11-01 01:27:173320 // Only hide the page if there are no entities capturing screenshots
Collin Bakerc5259962019-11-14 17:51:583321 // or video (e.g. mirroring). If there are, apply the correct state of
3322 // kHidden or kHiddenButPainting.
3323 PageVisibilityState page_visibility;
3324 if (new_visibility == Visibility::VISIBLE || visible_capturer_count_ > 0)
3325 page_visibility = PageVisibilityState::kVisible;
3326 else if (hidden_capturer_count_ > 0)
3327 page_visibility = PageVisibilityState::kHiddenButPainting;
3328 else
3329 page_visibility = PageVisibilityState::kHidden;
Collin Baker989e0882019-11-01 01:27:173330 // If there are entities in Picture-in-Picture mode, don't activate
3331 // the "disable rendering" optimization.
Collin Bakerc5259962019-11-14 17:51:583332 const bool view_is_visible =
3333 page_visibility != PageVisibilityState::kHidden ||
3334 HasPictureInPictureVideo();
Collin Baker989e0882019-11-01 01:27:173335
Collin Bakerc5259962019-11-14 17:51:583336 if (page_visibility != PageVisibilityState::kHidden) {
Dana Friedcf3bc8e2019-11-13 20:00:243337 // We cannot show a page or capture video unless there is a valid renderer
3338 // associated with this web contents. The navigation controller for this
3339 // page must be set to active (allowing navigation to complete, a renderer
3340 // and its associated views to be created, etc.) if any of these conditions
3341 // holds.
3342 //
3343 // Previously, it was possible for browser-side code to try to capture video
3344 // from a restored tab (for a variety of reasons, including the browser
3345 // creating preview thumbnails) and the tab would never actually load. By
Collin Bakerc5259962019-11-14 17:51:583346 // keying this behavior off of |page_visibility| instead of just
Dana Friedcf3bc8e2019-11-13 20:00:243347 // |new_visibility| we avoid this case. See crbug.com/1020782 for more
3348 // context.
3349 controller_.SetActive(true);
3350
3351 // This shows the Page before showing the individual RenderWidgets, as
3352 // RenderWidgets will work to produce compositor frames and handle input
3353 // as soon as they are shown. But the Page and other classes do not expect
3354 // to be producing frames when the Page is hidden. So we make sure the Page
3355 // is shown first.
Yuzu Saijo232076f2020-05-29 07:14:023356 for (auto* rvh : GetRenderViewHostsIncludingBackForwardCached()) {
3357 rvh->SetVisibility(page_visibility);
Yuzu Saijobe024af02020-05-11 07:35:563358 }
Collin Baker98457b52019-11-06 21:34:293359 }
Collin Baker989e0882019-11-01 01:27:173360
3361 // |GetRenderWidgetHostView()| can be null if the user middle clicks a link to
3362 // open a tab in the background, then closes the tab before selecting it.
3363 // This is because closing the tab calls WebContentsImpl::Destroy(), which
3364 // removes the |GetRenderViewHost()|; then when we actually destroy the
3365 // window, OnWindowPosChanged() notices and calls WasHidden() (which
3366 // calls us).
3367 if (auto* view = GetRenderWidgetHostView()) {
3368 if (view_is_visible) {
3369 view->Show();
Collin Baker989e0882019-11-01 01:27:173370 } else if (new_visibility == Visibility::HIDDEN) {
3371 view->Hide();
3372 } else {
3373 view->WasOccluded();
3374 }
3375 }
3376
Carlos IL07f282f2020-05-15 22:58:293377 SetVisibilityForChildViews(view_is_visible);
Collin Baker989e0882019-11-01 01:27:173378
3379 // Make sure to call SetVisibilityAndNotifyObservers(VISIBLE) before notifying
3380 // the CrossProcessFrameConnector.
3381 if (new_visibility == Visibility::VISIBLE) {
3382 last_active_time_ = base::TimeTicks::Now();
3383 SetVisibilityAndNotifyObservers(new_visibility);
3384 }
3385
Collin Bakerc5259962019-11-14 17:51:583386 if (page_visibility == PageVisibilityState::kHidden) {
Collin Baker989e0882019-11-01 01:27:173387 // Similar to when showing the page, we only hide the page after
3388 // hiding the individual RenderWidgets.
Yuzu Saijo232076f2020-05-29 07:14:023389 for (auto* rvh : GetRenderViewHostsIncludingBackForwardCached()) {
3390 rvh->SetVisibility(page_visibility);
Yuzu Saijobe024af02020-05-11 07:35:563391 }
3392
Collin Baker989e0882019-11-01 01:27:173393 } else {
3394 for (FrameTreeNode* node : frame_tree_.Nodes()) {
3395 RenderFrameProxyHost* parent = node->render_manager()->GetProxyToParent();
3396 if (!parent)
3397 continue;
3398
3399 parent->cross_process_frame_connector()->DelegateWasShown();
3400 }
3401 }
3402
3403 if (new_visibility != Visibility::VISIBLE)
3404 SetVisibilityAndNotifyObservers(new_visibility);
3405}
3406
Clark DuValla0e42992018-09-17 17:00:113407#if defined(OS_ANDROID)
3408void WebContentsImpl::UpdateUserGestureCarryoverInfo() {
Alexander Timin5fdeff22020-09-08 09:20:373409 OPTIONAL_TRACE_EVENT0("content",
3410 "WebContentsImpl::UpdateUserGestureCarryoverInfo");
Clark DuValla0e42992018-09-17 17:00:113411 if (delegate_)
3412 delegate_->UpdateUserGestureCarryoverInfo(this);
3413}
3414#endif
3415
Avi Drissman97aef042020-06-30 21:04:483416bool WebContentsImpl::IsFullscreen() {
[email protected]199bba6e2012-04-04 16:19:383417 return delegate_ ? delegate_->IsFullscreenForTabOrPending(this) : false;
[email protected]5d5f7af2011-10-01 01:38:123418}
3419
Malay Keshav87c42c02019-01-15 08:37:473420bool WebContentsImpl::ShouldShowStaleContentOnEviction() {
3421 return GetDelegate() && GetDelegate()->ShouldShowStaleContentOnEviction(this);
3422}
3423
danakj45d42452020-04-08 17:24:183424blink::mojom::DisplayMode WebContentsImpl::GetDisplayMode() const {
mikhail.pozdnyakovc0e251b2015-04-15 06:51:123425 return delegate_ ? delegate_->GetDisplayMode(this)
Eric Willigers052f0432019-10-04 04:06:573426 : blink::mojom::DisplayMode::kBrowser;
mikhail.pozdnyakovc0e251b2015-04-15 06:51:123427}
3428
avic3aa8422015-11-09 20:57:223429void WebContentsImpl::RequestToLockMouse(
3430 RenderWidgetHostImpl* render_widget_host,
3431 bool user_gesture,
lfgad8244352016-07-13 16:55:513432 bool last_unlocked_by_target,
3433 bool privileged) {
Alexander Timin5fdeff22020-09-08 09:20:373434 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RequestToLockMouse",
3435 "render_widget_host", render_widget_host, "privileged",
3436 privileged);
lfgf0cd46e2017-01-04 00:05:233437 for (WebContentsImpl* current = this; current;
3438 current = current->GetOuterWebContents()) {
3439 if (current->mouse_lock_widget_) {
James Hollyerd5c9de462020-03-10 19:02:453440 render_widget_host->GotResponseToLockMouseRequest(
3441 blink::mojom::PointerLockResult::kAlreadyLocked);
lfgf0cd46e2017-01-04 00:05:233442 return;
3443 }
[email protected]e9621112011-10-17 05:38:373444 }
avic3aa8422015-11-09 20:57:223445
lfgad8244352016-07-13 16:55:513446 if (privileged) {
lfgf0cd46e2017-01-04 00:05:233447 DCHECK(!GetOuterWebContents());
lfgad8244352016-07-13 16:55:513448 mouse_lock_widget_ = render_widget_host;
James Hollyerd5c9de462020-03-10 19:02:453449 render_widget_host->GotResponseToLockMouseRequest(
3450 blink::mojom::PointerLockResult::kSuccess);
lfgad8244352016-07-13 16:55:513451 return;
3452 }
3453
lfgbee1e0a2016-06-08 21:24:213454 bool widget_in_frame_tree = false;
3455 for (FrameTreeNode* node : frame_tree_.Nodes()) {
3456 if (node->current_frame_host()->GetRenderWidgetHost() ==
3457 render_widget_host) {
3458 widget_in_frame_tree = true;
3459 break;
3460 }
3461 }
3462
3463 if (widget_in_frame_tree && delegate_) {
lfgf0cd46e2017-01-04 00:05:233464 for (WebContentsImpl* current = this; current;
3465 current = current->GetOuterWebContents()) {
3466 current->mouse_lock_widget_ = render_widget_host;
3467 }
3468
avic3aa8422015-11-09 20:57:223469 delegate_->RequestToLockMouse(this, user_gesture, last_unlocked_by_target);
lfgbee1e0a2016-06-08 21:24:213470 } else {
James Hollyerd5c9de462020-03-10 19:02:453471 render_widget_host->GotResponseToLockMouseRequest(
3472 blink::mojom::PointerLockResult::kWrongDocument);
lfgbee1e0a2016-06-08 21:24:213473 }
[email protected]e9621112011-10-17 05:38:373474}
3475
avi3e4b8512015-11-11 01:55:493476void WebContentsImpl::LostMouseLock(RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:373477 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::LostMouseLock",
3478 "render_widget_host", render_widget_host);
lfgbee1e0a2016-06-08 21:24:213479 CHECK(mouse_lock_widget_);
lfgf0cd46e2017-01-04 00:05:233480
3481 if (mouse_lock_widget_->delegate()->GetAsWebContents() != this)
3482 return mouse_lock_widget_->delegate()->LostMouseLock(render_widget_host);
3483
lfgbee1e0a2016-06-08 21:24:213484 mouse_lock_widget_->SendMouseLockLost();
lfgf0cd46e2017-01-04 00:05:233485 for (WebContentsImpl* current = this; current;
3486 current = current->GetOuterWebContents()) {
3487 current->mouse_lock_widget_ = nullptr;
3488 }
avi3e4b8512015-11-11 01:55:493489
[email protected]e9621112011-10-17 05:38:373490 if (delegate_)
3491 delegate_->LostMouseLock();
3492}
3493
lfgad8244352016-07-13 16:55:513494bool WebContentsImpl::HasMouseLock(RenderWidgetHostImpl* render_widget_host) {
3495 // To verify if the mouse is locked, the mouse_lock_widget_ needs to be
3496 // assigned to the widget that requested the mouse lock, and the top-level
3497 // platform RenderWidgetHostView needs to hold the mouse lock from the OS.
Lucas Gadania0ea0172018-09-20 18:31:373498 auto* widget_host = GetTopLevelRenderWidgetHostView();
3499 return mouse_lock_widget_ == render_widget_host && widget_host &&
3500 widget_host->IsMouseLocked();
lfgad8244352016-07-13 16:55:513501}
3502
lfg84763c92017-02-16 18:55:153503RenderWidgetHostImpl* WebContentsImpl::GetMouseLockWidget() {
Lucas Gadania0ea0172018-09-20 18:31:373504 auto* widget_host = GetTopLevelRenderWidgetHostView();
3505 if ((widget_host && widget_host->IsMouseLocked()) ||
lfge2176fb2017-03-26 00:45:473506 (GetFullscreenRenderWidgetHostView() &&
Lucas Gadania0ea0172018-09-20 18:31:373507 GetFullscreenRenderWidgetHostView()->IsMouseLocked())) {
lfg84763c92017-02-16 18:55:153508 return mouse_lock_widget_;
Lucas Gadania0ea0172018-09-20 18:31:373509 }
lfg84763c92017-02-16 18:55:153510
3511 return nullptr;
3512}
3513
Joe Downing192998b22018-03-22 15:51:363514bool WebContentsImpl::RequestKeyboardLock(
Joe Downing13dd76b2018-04-09 18:32:153515 RenderWidgetHostImpl* render_widget_host,
3516 bool esc_key_locked) {
Alexander Timin5fdeff22020-09-08 09:20:373517 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RequestKeyboardLock",
3518 "render_widget_host", render_widget_host,
3519 "esc_key_locked", esc_key_locked);
Joe Downing192998b22018-03-22 15:51:363520 DCHECK(render_widget_host);
Joe Downing192998b22018-03-22 15:51:363521 if (render_widget_host->delegate()->GetAsWebContents() != this) {
3522 NOTREACHED();
3523 return false;
3524 }
3525
3526 // KeyboardLock is only supported when called by the top-level browsing
3527 // context and is not supported in embedded content scenarios.
3528 if (GetOuterWebContents())
3529 return false;
3530
Joe Downing13dd76b2018-04-09 18:32:153531 esc_key_locked_ = esc_key_locked;
Joe Downing192998b22018-03-22 15:51:363532 keyboard_lock_widget_ = render_widget_host;
3533
Joe Downing13dd76b2018-04-09 18:32:153534 if (delegate_)
3535 delegate_->RequestKeyboardLock(this, esc_key_locked_);
Joe Downing192998b22018-03-22 15:51:363536 return true;
3537}
3538
3539void WebContentsImpl::CancelKeyboardLock(
3540 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:373541 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::CancelKeyboardLockRequest",
3542 "render_widget_host", render_widget_host);
Joe Downing192998b22018-03-22 15:51:363543 if (!keyboard_lock_widget_ || render_widget_host != keyboard_lock_widget_)
3544 return;
3545
3546 RenderWidgetHostImpl* old_keyboard_lock_widget = keyboard_lock_widget_;
3547 keyboard_lock_widget_ = nullptr;
3548
Joe Downing13dd76b2018-04-09 18:32:153549 if (delegate_)
3550 delegate_->CancelKeyboardLockRequest(this);
3551
Joe Downing192998b22018-03-22 15:51:363552 old_keyboard_lock_widget->CancelKeyboardLock();
3553}
3554
3555RenderWidgetHostImpl* WebContentsImpl::GetKeyboardLockWidget() {
3556 return keyboard_lock_widget_;
3557}
3558
Dave Tapuskac3344362019-02-20 17:54:283559void WebContentsImpl::OnRenderFrameProxyVisibilityChanged(
3560 blink::mojom::FrameVisibility visibility) {
Alexander Timin5fdeff22020-09-08 09:20:373561 OPTIONAL_TRACE_EVENT1("content",
3562 "WebContentsImpl::OnRenderFrameProxyVisibilityChanged",
3563 "visibility", static_cast<int>(visibility));
Dave Tapuskac3344362019-02-20 17:54:283564 switch (visibility) {
3565 case blink::mojom::FrameVisibility::kRenderedInViewport:
3566 WasShown();
3567 break;
3568 case blink::mojom::FrameVisibility::kNotRendered:
3569 WasHidden();
3570 break;
3571 case blink::mojom::FrameVisibility::kRenderedOutOfViewport:
3572 WasOccluded();
3573 break;
3574 }
ekaramada4f42692016-02-11 19:48:373575}
3576
Albert J. Wong65fe64d2019-09-20 02:48:143577RenderFrameHostDelegate* WebContentsImpl::CreateNewWindow(
csharrison95f01e922017-04-24 18:52:353578 RenderFrameHost* opener,
rockot5c478a72016-09-28 23:14:183579 const mojom::CreateNewWindowParams& params,
Albert J. Wong65fe64d2019-09-20 02:48:143580 bool is_new_browsing_instance,
Sergey Kuznetsov32257a22019-02-11 20:26:503581 bool has_user_gesture,
[email protected]97714c82012-06-06 10:15:133582 SessionStorageNamespace* session_storage_namespace) {
Alexander Timin5fdeff22020-09-08 09:20:373583 TRACE_EVENT2("browser,content,navigation", "WebContentsImpl::CreateNewWindow",
3584 "opener", base::trace_event::ToTracedValue(opener), "params",
3585 base::trace_event::ToTracedValue(params));
csharrison95f01e922017-04-24 18:52:353586 DCHECK(opener);
nick5ae4d2d2017-01-06 01:18:353587
csharrison95f01e922017-04-24 18:52:353588 int render_process_id = opener->GetProcess()->GetID();
csharrison95f01e922017-04-24 18:52:353589
Albert J. Wong65fe64d2019-09-20 02:48:143590 SiteInstance* source_site_instance = opener->GetSiteInstance();
nick5ae4d2d2017-01-06 01:18:353591
Aaron Colwelleb219982020-01-16 02:17:273592 const GURL source_site_url = source_site_instance->GetSiteURL();
[email protected]fdac6ade2013-07-20 01:06:303593 const std::string& partition_id =
Aaron Colwelleb219982020-01-16 02:17:273594 GetContentClient()->browser()->GetStoragePartitionIdForSite(
3595 GetBrowserContext(), source_site_url);
3596 {
3597 StoragePartition* partition = BrowserContext::GetStoragePartitionForSite(
3598 GetBrowserContext(), source_site_url);
3599 DOMStorageContextWrapper* dom_storage_context =
3600 static_cast<DOMStorageContextWrapper*>(
3601 partition->GetDOMStorageContext());
3602 SessionStorageNamespaceImpl* session_storage_namespace_impl =
3603 static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace);
3604 CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context));
3605 }
[email protected]dd6730412013-08-14 15:03:373606
Albert J. Wong1ceccef92019-10-08 08:25:203607 if (delegate_ && delegate_->IsWebContentsCreationOverridden(
3608 source_site_instance, params.window_container_type,
3609 opener->GetLastCommittedURL(), params.frame_name,
3610 params.target_url)) {
3611 return static_cast<WebContentsImpl*>(delegate_->CreateCustomWebContents(
3612 opener, source_site_instance, is_new_browsing_instance,
3613 opener->GetLastCommittedURL(), params.frame_name, params.target_url,
3614 partition_id, session_storage_namespace));
[email protected]dd6730412013-08-14 15:03:373615 }
3616
danakj22b4e8b2019-08-01 23:14:393617 bool renderer_started_hidden =
3618 params.disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB;
3619
Aaron Colwelleb219982020-01-16 02:17:273620 // We usually create the new window in the same BrowsingInstance (group of
3621 // script-related windows), by passing in the current SiteInstance. However,
3622 // if the opener is being suppressed (in a non-guest), we do not provide
3623 // a SiteInstance which causes a new one to get created in its own
3624 // BrowsingInstance.
3625 bool is_guest = BrowserPluginGuest::IsGuest(this);
3626 scoped_refptr<SiteInstance> site_instance =
3627 params.opener_suppressed && !is_guest ? nullptr : source_site_instance;
3628
[email protected]dd6730412013-08-14 15:03:373629 // Create the new web contents. This will automatically create the new
3630 // WebContentsView. In the future, we may want to create the view separately.
[email protected]fc72bb12013-06-02 21:13:463631 CreateParams create_params(GetBrowserContext(), site_instance.get());
nasko48321ca32015-07-02 20:44:123632 create_params.main_frame_name = params.frame_name;
alexmos4cf2aa32015-07-15 23:40:433633 create_params.opener_render_process_id = render_process_id;
csharrison95f01e922017-04-24 18:52:353634 create_params.opener_render_frame_id = opener->GetRoutingID();
[email protected]50d326e2014-05-20 17:59:063635 create_params.opener_suppressed = params.opener_suppressed;
danakj22b4e8b2019-08-01 23:14:393636 create_params.initially_hidden = renderer_started_hidden;
[email protected]50d326e2014-05-20 17:59:063637
Albert J. Wong65fe64d2019-09-20 02:48:143638 // Even though all codepaths leading here are in response to a renderer
3639 // tryng to open a new window, if the new window ends up in a different
3640 // browsing instance, then the RenderViewHost, RenderWidgetHost,
3641 // RenderFrameHost constellation is effectively browser initiated
3642 // the opener's process will not given the routing IDs for the new
3643 // objects.
3644 create_params.renderer_initiated_creation = !is_new_browsing_instance;
Albert J. Wong1ceccef92019-10-08 08:25:203645
Albert J. Wong65fe64d2019-09-20 02:48:143646 std::unique_ptr<WebContentsImpl> new_contents;
[email protected]c4538072013-03-18 02:17:553647 if (!is_guest) {
3648 create_params.context = view_->GetNativeView();
Albert J. Wong65fe64d2019-09-20 02:48:143649 new_contents = WebContentsImpl::Create(create_params);
3650 } else {
3651 new_contents = base::WrapUnique(static_cast<WebContentsImpl*>(
3652 GetBrowserPluginGuest()->CreateNewGuestWindow(create_params)));
[email protected]c4538072013-03-18 02:17:553653 }
Albert J. Wong65fe64d2019-09-20 02:48:143654 auto* new_contents_impl = new_contents.get();
danakje6c01622018-10-05 19:39:263655
3656 new_contents_impl->GetController().SetSessionStorageNamespace(
erikchenbee5c9622018-04-27 19:30:253657 partition_id, session_storage_namespace);
[email protected]d1198fd2012-08-13 22:50:193658
alexmos646fec02015-07-25 00:11:493659 // If the new frame has a name, make sure any SiteInstances that can find
3660 // this named frame have proxies for it. Must be called after
3661 // SetSessionStorageNamespace, since this calls CreateRenderView, which uses
3662 // GetSessionStorageNamespace.
3663 if (!params.frame_name.empty())
danakje6c01622018-10-05 19:39:263664 new_contents_impl->GetRenderManager()->CreateProxiesForNewNamedFrame();
alexmos646fec02015-07-25 00:11:493665
[email protected]c4538072013-03-18 02:17:553666 // Save the window for later if we're not suppressing the opener (since it
[email protected]d70bea92013-04-05 04:23:343667 // will be shown immediately).
3668 if (!params.opener_suppressed) {
3669 if (!is_guest) {
danakje6c01622018-10-05 19:39:263670 WebContentsView* new_view = new_contents_impl->view_.get();
[email protected]bafe6cd2012-05-23 23:09:503671
[email protected]d70bea92013-04-05 04:23:343672 // TODO(brettw): It seems bogus that we have to call this function on the
3673 // newly created object and give it one of its own member variables.
danakj22b4e8b2019-08-01 23:14:393674 RenderWidgetHostView* widget_view = new_view->CreateViewForWidget(
W. James MacLean13d834d2019-12-04 16:06:453675 new_contents_impl->GetRenderViewHost()->GetWidget());
danakj22b4e8b2019-08-01 23:14:393676 if (!renderer_started_hidden) {
3677 // RenderWidgets for frames always initialize as hidden. If the renderer
3678 // created this window as visible, then we show it here.
3679 widget_view->Show();
3680 }
[email protected]d70bea92013-04-05 04:23:343681 }
[email protected]bafe6cd2012-05-23 23:09:503682 // Save the created window associated with the route so we can show it
3683 // later.
Albert J. Wongcb004632018-07-10 22:58:253684 //
3685 // TODO(ajwong): This should be keyed off the RenderFrame routing id or the
3686 // FrameTreeNode id instead of the routing id of the Widget for the main
3687 // frame. https://crbug.com/545684
Fergal Daly052873a82020-03-11 14:45:493688 int32_t main_frame_routing_id = new_contents_impl->GetMainFrame()
3689 ->GetRenderWidgetHost()
3690 ->GetRoutingID();
3691 GlobalRoutingID id(render_process_id, main_frame_routing_id);
Joel Hockey8c2011b22020-04-30 05:07:193692 pending_contents_[id] =
3693 CreatedWindow(std::move(new_contents), params.target_url);
danakje6c01622018-10-05 19:39:263694 AddDestructionObserver(new_contents_impl);
[email protected]bafe6cd2012-05-23 23:09:503695 }
3696
3697 if (delegate_) {
Bryan McQuaded2b93c02017-07-14 22:26:313698 delegate_->WebContentsCreated(this, render_process_id,
3699 opener->GetRoutingID(), params.frame_name,
danakje6c01622018-10-05 19:39:263700 params.target_url, new_contents_impl);
[email protected]bafe6cd2012-05-23 23:09:503701 }
3702
Alexander Timin90c20c32020-08-12 15:28:323703 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3704 observer->DidOpenRequestedURL(new_contents_impl, opener, params.target_url,
3705 params.referrer.To<Referrer>(),
3706 params.disposition, ui::PAGE_TRANSITION_LINK,
3707 false, // started_from_context_menu
3708 true); // renderer_initiated
3709 });
pnolandaae574e2017-03-06 21:04:213710
[email protected]bafe6cd2012-05-23 23:09:503711 if (params.opener_suppressed) {
3712 // When the opener is suppressed, the original renderer cannot access the
3713 // new window. As a result, we need to show and navigate the window here.
[email protected]eda238a12012-09-07 23:44:003714 bool was_blocked = false;
erikchenbee5c9622018-04-27 19:30:253715
[email protected]eda238a12012-09-07 23:44:003716 if (delegate_) {
danakje6c01622018-10-05 19:39:263717 base::WeakPtr<WebContentsImpl> weak_new_contents =
3718 new_contents_impl->weak_factory_.GetWeakPtr();
nick0d558482017-02-13 22:27:223719
danakje6c01622018-10-05 19:39:263720 gfx::Rect initial_rect; // Report an empty initial rect.
Albert J. Wong65fe64d2019-09-20 02:48:143721 delegate_->AddNewContents(this, std::move(new_contents),
Joel Hockey891e88062020-04-30 05:38:443722 params.target_url, params.disposition,
3723 initial_rect, has_user_gesture, &was_blocked);
danakje6c01622018-10-05 19:39:263724 // The delegate may delete |new_contents_impl| during AddNewContents().
nick0d558482017-02-13 22:27:223725 if (!weak_new_contents)
Albert J. Wong65fe64d2019-09-20 02:48:143726 return nullptr;
[email protected]eda238a12012-09-07 23:44:003727 }
erikchenbee5c9622018-04-27 19:30:253728
[email protected]eda238a12012-09-07 23:44:003729 if (!was_blocked) {
Nasko Oskov83a8cf92018-10-19 14:58:563730 std::unique_ptr<NavigationController::LoadURLParams> load_params =
3731 std::make_unique<NavigationController::LoadURLParams>(
3732 params.target_url);
Nasko Oskov93e7c55c2018-12-19 01:59:293733 load_params->initiator_origin = opener->GetLastCommittedOrigin();
Lukasz Anforowiczd2629b42020-08-11 16:07:313734 // Avoiding setting |load_params->source_site_instance| when
3735 // |opener_suppressed| is true, because in that case we do not want to use
3736 // the old SiteInstance and/or BrowsingInstance. See also the test here:
3737 // NewPopupCOOP_SameOriginPolicyAndCrossOriginIframeSetsNoopener.
Leon Han963dc182018-11-06 05:41:483738 load_params->referrer = params.referrer.To<Referrer>();
Nasko Oskov83a8cf92018-10-19 14:58:563739 load_params->transition_type = ui::PAGE_TRANSITION_LINK;
3740 load_params->is_renderer_initiated = true;
Sergey Kuznetsov32257a22019-02-11 20:26:503741 load_params->has_user_gesture = has_user_gesture;
mariakhomenkoa4971c12015-07-21 19:04:373742
3743 if (delegate_ && !is_guest &&
3744 !delegate_->ShouldResumeRequestsForCreatedWindow()) {
Nasko Oskov83a8cf92018-10-19 14:58:563745 // We are in asynchronous add new contents path, delay navigation.
3746 DCHECK(!new_contents_impl->delayed_open_url_params_);
3747 new_contents_impl->delayed_load_url_params_ = std::move(load_params);
mariakhomenkoa4971c12015-07-21 19:04:373748 } else {
Nasko Oskov83a8cf92018-10-19 14:58:563749 new_contents_impl->controller_.LoadURLWithParams(*load_params.get());
Nasko Oskov28ebd5b2018-12-07 22:29:333750 if (!is_guest)
3751 new_contents_impl->Focus();
mariakhomenkoa4971c12015-07-21 19:04:373752 }
[email protected]eda238a12012-09-07 23:44:003753 }
[email protected]bafe6cd2012-05-23 23:09:503754 }
Albert J. Wong65fe64d2019-09-20 02:48:143755 return new_contents_impl;
[email protected]bafe6cd2012-05-23 23:09:503756}
3757
Dave Tapuskad9835622020-03-10 17:32:313758void WebContentsImpl::CreateNewWidget(
Tal Pressman5dcd2382020-08-26 07:13:053759 AgentSchedulingGroupHost& agent_scheduling_group,
3760 int32_t route_id,
Dave Tapuska8499eec2020-03-16 17:54:303761 mojo::PendingAssociatedReceiver<blink::mojom::WidgetHost> blink_widget_host,
3762 mojo::PendingAssociatedRemote<blink::mojom::Widget> blink_widget) {
Tal Pressman5dcd2382020-08-26 07:13:053763 CreateNewWidget(agent_scheduling_group, route_id,
3764 /*is_fullscreen=*/false, std::move(blink_widget_host),
3765 std::move(blink_widget));
[email protected]bafe6cd2012-05-23 23:09:503766}
3767
Julie Jeongeun Kimcaacf9102019-09-12 02:13:053768void WebContentsImpl::CreateNewFullscreenWidget(
Tal Pressman5dcd2382020-08-26 07:13:053769 AgentSchedulingGroupHost& agent_scheduling_group,
3770 int32_t route_id,
Dave Tapuska8499eec2020-03-16 17:54:303771 mojo::PendingAssociatedReceiver<blink::mojom::WidgetHost> blink_widget_host,
3772 mojo::PendingAssociatedRemote<blink::mojom::Widget> blink_widget) {
Tal Pressman5dcd2382020-08-26 07:13:053773 CreateNewWidget(agent_scheduling_group, route_id,
3774 /*is_fullscreen=*/true, std::move(blink_widget_host),
3775 std::move(blink_widget));
[email protected]bafe6cd2012-05-23 23:09:503776}
3777
Dave Tapuskad9835622020-03-10 17:32:313778void WebContentsImpl::CreateNewWidget(
Tal Pressman5dcd2382020-08-26 07:13:053779 AgentSchedulingGroupHost& agent_scheduling_group,
Dave Tapuskad9835622020-03-10 17:32:313780 int32_t route_id,
3781 bool is_fullscreen,
Dave Tapuska8499eec2020-03-16 17:54:303782 mojo::PendingAssociatedReceiver<blink::mojom::WidgetHost> blink_widget_host,
3783 mojo::PendingAssociatedRemote<blink::mojom::Widget> blink_widget) {
Alexander Timin5fdeff22020-09-08 09:20:373784 OPTIONAL_TRACE_EVENT1(
3785 "content", "WebContentsImpl::CreateNewWidget", "params",
3786 base::trace_event::TracedValue::Build(
3787 {{"route_id", route_id}, {"is_fullscreen", is_fullscreen}}));
Tal Pressman5dcd2382020-08-26 07:13:053788 RenderProcessHost* process = agent_scheduling_group.GetProcess();
kenrbb46f86a2015-12-07 07:53:233789 // A message to create a new widget can only come from an active process for
[email protected]a8504022013-12-04 20:23:513790 // this WebContentsImpl instance. If any other process sends the request,
3791 // it is invalid and the process must be terminated.
Tal Pressman5dcd2382020-08-26 07:13:053792 if (!HasMatchingProcess(&frame_tree_, process->GetID())) {
Lukasz Anforowicz6f746282018-01-04 23:24:513793 ReceivedBadMessage(process, bad_message::WCI_NEW_WIDGET_PROCESS_MISMATCH);
[email protected]a8504022013-12-04 20:23:513794 return;
3795 }
3796
Tal Pressman5dcd2382020-08-26 07:13:053797 RenderWidgetHostImpl* widget_host = new RenderWidgetHostImpl(
3798 this, agent_scheduling_group, route_id, IsHidden(),
3799 std::make_unique<FrameTokenMessageQueue>());
Dave Tapuska8499eec2020-03-16 17:54:303800
3801 widget_host->BindWidgetInterfaces(std::move(blink_widget_host),
3802 std::move(blink_widget));
[email protected]cfd80b02014-05-01 17:46:483803 RenderWidgetHostViewBase* widget_view =
3804 static_cast<RenderWidgetHostViewBase*>(
danakj0b246942018-09-17 21:30:273805 view_->CreateViewForChildWidget(widget_host));
[email protected]83918ec2013-01-10 15:37:193806 if (!widget_view)
3807 return;
danakj0b246942018-09-17 21:30:273808 // Fullscreen child widgets are frames, other child widgets are popups, and
3809 // popups should not get activated.
3810 if (!is_fullscreen)
3811 widget_view->SetWidgetType(WidgetType::kPopup);
[email protected]bafe6cd2012-05-23 23:09:503812 // Save the created widget associated with the route so we can show it later.
Tal Pressman5dcd2382020-08-26 07:13:053813 pending_widget_views_[GlobalRoutingID(process->GetID(), route_id)] =
alexmosc2a8cec2016-05-23 22:19:533814 widget_view;
[email protected]bafe6cd2012-05-23 23:09:503815}
3816
Mike Wassermandabad612020-08-13 04:26:273817void WebContentsImpl::ShowCreatedWindow(RenderFrameHost* opener,
nick5ae4d2d2017-01-06 01:18:353818 int main_frame_widget_route_id,
[email protected]bafe6cd2012-05-23 23:09:503819 WindowOpenDisposition disposition,
bokan107a47f2015-02-03 23:23:393820 const gfx::Rect& initial_rect,
[email protected]bafe6cd2012-05-23 23:09:503821 bool user_gesture) {
Alexander Timin5fdeff22020-09-08 09:20:373822 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::ShowCreatedWindow",
3823 "opener", base::trace_event::ToTracedValue(opener),
3824 "main_frame_widget_route_id",
3825 main_frame_widget_route_id);
danakje6c01622018-10-05 19:39:263826 // This method is the renderer requesting an existing top level window to
3827 // show a new top level window that the renderer created. Each top level
3828 // window is associated with a WebContents. In this case it was created
3829 // earlier but showing it was deferred until the renderer requested for it
3830 // to be shown. We find that previously created WebContents here.
3831 // TODO(danakj): Why do we defer this show step until the renderer asks for it
3832 // when it will always do so. What needs to happen in the renderer before we
3833 // reach here?
Mike Wassermandabad612020-08-13 04:26:273834 base::Optional<CreatedWindow> owned_created = GetCreatedWindow(
3835 opener->GetProcess()->GetID(), main_frame_widget_route_id);
Joel Hockey8c2011b22020-04-30 05:07:193836
danakje6c01622018-10-05 19:39:263837 // The browser may have rejected the request to make a new window, or the
3838 // renderer could be sending an invalid route id. Ignore the request then.
Joel Hockey8c2011b22020-04-30 05:07:193839 if (!owned_created || !owned_created->contents)
danakje6c01622018-10-05 19:39:263840 return;
mariakhomenko44bdc4732015-04-29 01:55:383841
Joel Hockey8c2011b22020-04-30 05:07:193842 WebContentsImpl* created = owned_created->contents.get();
3843
danakje6c01622018-10-05 19:39:263844 // This uses the delegate for the WebContents where the window was created
3845 // from, to control how to show the newly created window.
3846 WebContentsDelegate* delegate = GetDelegate();
nick5ae4d2d2017-01-06 01:18:353847
Mike Wassermanb6bc0152020-08-25 22:46:203848 // Individual members of |initial_rect| may be 0 to indicate that the
3849 // window.open() feature string did not specify a value. This code does not
3850 // have the ability to distinguish between an unspecified value and 0.
3851 // Assume that if any single value is non-zero, all values should be used.
3852 // TODO(crbug.com/897300): Plumb values as specified; set defaults here?
3853 gfx::Rect adjusted_rect = initial_rect;
3854 int64_t display_id = display::kInvalidDisplayId;
3855 if (adjusted_rect != gfx::Rect())
3856 display_id = AdjustRequestedWindowBounds(&adjusted_rect, opener);
3857
3858 // Drop fullscreen when opening a WebContents to prohibit deceptive behavior.
3859 // Only drop fullscreen on the specific destination display, if it is known.
3860 // This supports sites using cross-screen window placement capabilities to
3861 // retain fullscreen and open a window on another screen.
3862 ForSecurityDropFullscreen(display_id).RunAndReset();
3863
danakje6c01622018-10-05 19:39:263864 // The delegate can be null in tests, so we must check for it :(.
3865 if (delegate) {
3866 // Mark the web contents as pending resume, then immediately do
3867 // the resume if the delegate wants it.
3868 created->is_resume_pending_ = true;
3869 if (delegate->ShouldResumeRequestsForCreatedWindow())
3870 created->ResumeLoadingCreatedWebContents();
3871
3872 base::WeakPtr<WebContentsImpl> weak_created =
3873 created->weak_factory_.GetWeakPtr();
Joel Hockey8c2011b22020-04-30 05:07:193874 delegate->AddNewContents(this, std::move(owned_created->contents),
Joel Hockey891e88062020-04-30 05:38:443875 std::move(owned_created->target_url), disposition,
Mike Wassermandabad612020-08-13 04:26:273876 adjusted_rect, user_gesture, nullptr);
danakje6c01622018-10-05 19:39:263877 // The delegate may delete |created| during AddNewContents().
3878 if (!weak_created)
3879 return;
[email protected]eda238a12012-09-07 23:44:003880 }
danakje6c01622018-10-05 19:39:263881
3882 RenderWidgetHostImpl* rwh = created->GetMainFrame()->GetRenderWidgetHost();
3883 DCHECK_EQ(main_frame_widget_route_id, rwh->GetRoutingID());
3884 rwh->Send(new WidgetMsg_SetBounds_ACK(rwh->GetRoutingID()));
[email protected]bafe6cd2012-05-23 23:09:503885}
3886
alexmosc2a8cec2016-05-23 22:19:533887void WebContentsImpl::ShowCreatedWidget(int process_id,
Albert J. Wongf6e13ed2018-09-18 15:25:473888 int widget_route_id,
bokan107a47f2015-02-03 23:23:393889 const gfx::Rect& initial_rect) {
Alexander Timin5fdeff22020-09-08 09:20:373890 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::ShowCreatedWidget",
3891 "process_id", process_id, "widget_route_id",
3892 widget_route_id);
Albert J. Wongf6e13ed2018-09-18 15:25:473893 ShowCreatedWidget(process_id, widget_route_id, false, initial_rect);
[email protected]bafe6cd2012-05-23 23:09:503894}
3895
alexmosc2a8cec2016-05-23 22:19:533896void WebContentsImpl::ShowCreatedFullscreenWidget(int process_id,
Albert J. Wongf6e13ed2018-09-18 15:25:473897 int widget_route_id) {
Alexander Timin5fdeff22020-09-08 09:20:373898 OPTIONAL_TRACE_EVENT2(
3899 "content", "WebContentsImpl::ShowCreatedFullscreenWidget", "process_id",
3900 process_id, "widget_route_id", widget_route_id);
Albert J. Wongf6e13ed2018-09-18 15:25:473901 ShowCreatedWidget(process_id, widget_route_id, true, gfx::Rect());
[email protected]bafe6cd2012-05-23 23:09:503902}
3903
alexmosc2a8cec2016-05-23 22:19:533904void WebContentsImpl::ShowCreatedWidget(int process_id,
3905 int route_id,
[email protected]bafe6cd2012-05-23 23:09:503906 bool is_fullscreen,
bokan107a47f2015-02-03 23:23:393907 const gfx::Rect& initial_rect) {
[email protected]cfd80b02014-05-01 17:46:483908 RenderWidgetHostViewBase* widget_host_view =
alexmosc2a8cec2016-05-23 22:19:533909 static_cast<RenderWidgetHostViewBase*>(
3910 GetCreatedWidget(process_id, route_id));
[email protected]bafe6cd2012-05-23 23:09:503911 if (!widget_host_view)
3912 return;
[email protected]cfd80b02014-05-01 17:46:483913
W. James MacLeanec4125c2019-09-27 18:56:003914 // GetOutermostWebContents() returns |this| if there are no outer WebContents.
W. James MacLean3c5f50462019-10-28 16:24:213915 auto* outer_web_contents = GetOuterWebContents();
3916 auto* outermost_web_contents = GetOutermostWebContents();
W. James MacLeanec4125c2019-09-27 18:56:003917 RenderWidgetHostView* view =
W. James MacLean3c5f50462019-10-28 16:24:213918 outermost_web_contents->GetRenderWidgetHostView();
3919 // It's not entirely obvious why we need the transform only in the case where
3920 // the outer webcontents is not the same as the outermost webcontents. It may
3921 // be due to the fact that oopifs that are children of the mainframe get
3922 // correct values for their screenrects, but deeper cross-process frames do
3923 // not. Hopefully this can be resolved with https://crbug.com/928825.
3924 // Handling these cases separately is needed for http://crbug.com/1015298.
3925 bool needs_transform = this != outermost_web_contents &&
3926 outermost_web_contents != outer_web_contents;
W. James MacLeanec4125c2019-09-27 18:56:003927
3928 gfx::Rect transformed_rect(initial_rect);
3929 RenderWidgetHostView* this_view = GetRenderWidgetHostView();
W. James MacLean3c5f50462019-10-28 16:24:213930 if (needs_transform) {
W. James MacLeanec4125c2019-09-27 18:56:003931 // We need to transform the coordinates of initial_rect.
3932 gfx::Point origin =
3933 this_view->TransformPointToRootCoordSpace(initial_rect.origin());
3934 gfx::Point bottom_right =
3935 this_view->TransformPointToRootCoordSpace(initial_rect.bottom_right());
3936 transformed_rect =
3937 gfx::Rect(origin.x(), origin.y(), bottom_right.x() - origin.x(),
3938 bottom_right.y() - origin.y());
[email protected]cfd80b02014-05-01 17:46:483939 }
3940
danakj0b246942018-09-17 21:30:273941 // Fullscreen child widgets are frames, other child widgets are popups.
[email protected]4aebbca2013-09-17 22:26:493942 if (is_fullscreen) {
[email protected]d7f80ba2013-10-12 07:42:313943 DCHECK_EQ(MSG_ROUTING_NONE, fullscreen_widget_routing_id_);
[email protected]0b431992014-06-24 00:08:033944 view_->StoreFocus();
alexmosc9e76ec2016-05-16 22:59:373945 fullscreen_widget_process_id_ =
3946 widget_host_view->GetRenderWidgetHost()->GetProcess()->GetID();
[email protected]d7f80ba2013-10-12 07:42:313947 fullscreen_widget_routing_id_ = route_id;
[email protected]4aebbca2013-09-17 22:26:493948 if (delegate_ && delegate_->EmbedsFullscreenWidget()) {
3949 widget_host_view->InitAsChild(GetRenderWidgetHostView()->GetNativeView());
Mike Wasserman4ca09792020-05-29 17:44:433950 delegate_->EnterFullscreenModeForTab(GetMainFrame(),
Dave Tapuskaa4189512019-10-15 20:27:343951 blink::mojom::FullscreenOptions());
[email protected]4aebbca2013-09-17 22:26:493952 } else {
[email protected]cfd80b02014-05-01 17:46:483953 widget_host_view->InitAsFullscreen(view);
[email protected]4aebbca2013-09-17 22:26:493954 }
Alexander Timin90c20c32020-08-12 15:28:323955 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3956 observer->DidShowFullscreenWidget();
3957 });
[email protected]4aebbca2013-09-17 22:26:493958 if (!widget_host_view->HasFocus())
3959 widget_host_view->Focus();
3960 } else {
W. James MacLeanec4125c2019-09-27 18:56:003961 widget_host_view->InitAsPopup(view, transformed_rect);
[email protected]4aebbca2013-09-17 22:26:493962 }
[email protected]89054502012-06-03 10:29:243963
yiyixcb1fbc4f2018-03-16 19:54:083964 RenderWidgetHostImpl* render_widget_host_impl = widget_host_view->host();
[email protected]89054502012-06-03 10:29:243965 render_widget_host_impl->Init();
[email protected]d7f80ba2013-10-12 07:42:313966 // Only allow privileged mouse lock for fullscreen render widget, which is
3967 // used to implement Pepper Flash fullscreen.
3968 render_widget_host_impl->set_allow_privileged_mouse_lock(is_fullscreen);
[email protected]bafe6cd2012-05-23 23:09:503969}
3970
Joel Hockey8c2011b22020-04-30 05:07:193971base::Optional<CreatedWindow> WebContentsImpl::GetCreatedWindow(
nick5ae4d2d2017-01-06 01:18:353972 int process_id,
3973 int main_frame_widget_route_id) {
Alexander Timin5fdeff22020-09-08 09:20:373974 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::GetCreatedWindow",
3975 "process_id", process_id, "main_frame_widget_route_id",
3976 main_frame_widget_route_id);
3977
Lukasz Anforowicz09060bdf72018-08-23 15:53:173978 auto key = GlobalRoutingID(process_id, main_frame_widget_route_id);
nick5ae4d2d2017-01-06 01:18:353979 auto iter = pending_contents_.find(key);
[email protected]bafe6cd2012-05-23 23:09:503980
3981 // Certain systems can block the creation of new windows. If we didn't succeed
3982 // in creating one, just return NULL.
alexmosc2a8cec2016-05-23 22:19:533983 if (iter == pending_contents_.end())
Joel Hockey8c2011b22020-04-30 05:07:193984 return base::nullopt;
[email protected]bafe6cd2012-05-23 23:09:503985
Joel Hockey8c2011b22020-04-30 05:07:193986 CreatedWindow result = std::move(iter->second);
3987 WebContentsImpl* new_contents = result.contents.get();
nick5ae4d2d2017-01-06 01:18:353988 pending_contents_.erase(key);
Joel Hockey8c2011b22020-04-30 05:07:193989 RemoveDestructionObserver(new_contents);
[email protected]bafe6cd2012-05-23 23:09:503990
[email protected]d70bea92013-04-05 04:23:343991 // Don't initialize the guest WebContents immediately.
Joel Hockey8c2011b22020-04-30 05:07:193992 if (BrowserPluginGuest::IsGuest(new_contents))
3993 return result;
[email protected]d70bea92013-04-05 04:23:343994
Lukasz Anforowicz5510ed652018-06-06 16:16:193995 if (!new_contents->GetMainFrame()->GetProcess()->IsInitializedAndNotDead() ||
nick5ae4d2d2017-01-06 01:18:353996 !new_contents->GetMainFrame()->GetView()) {
Joel Hockey8c2011b22020-04-30 05:07:193997 return base::nullopt;
nick5ae4d2d2017-01-06 01:18:353998 }
[email protected]bafe6cd2012-05-23 23:09:503999
Joel Hockey8c2011b22020-04-30 05:07:194000 return result;
[email protected]bafe6cd2012-05-23 23:09:504001}
4002
alexmosc2a8cec2016-05-23 22:19:534003RenderWidgetHostView* WebContentsImpl::GetCreatedWidget(int process_id,
4004 int route_id) {
Alexander Timin5fdeff22020-09-08 09:20:374005 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::GetCreatedWidget",
4006 "process_id", process_id, "route_id", route_id);
4007
Lukasz Anforowicz09060bdf72018-08-23 15:53:174008 auto iter = pending_widget_views_.find(GlobalRoutingID(process_id, route_id));
[email protected]bafe6cd2012-05-23 23:09:504009 if (iter == pending_widget_views_.end()) {
4010 DCHECK(false);
alexmosc2a8cec2016-05-23 22:19:534011 return nullptr;
[email protected]bafe6cd2012-05-23 23:09:504012 }
4013
4014 RenderWidgetHostView* widget_host_view = iter->second;
Lukasz Anforowicz09060bdf72018-08-23 15:53:174015 pending_widget_views_.erase(GlobalRoutingID(process_id, route_id));
[email protected]bafe6cd2012-05-23 23:09:504016
4017 RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
Lukasz Anforowicz5510ed652018-06-06 16:16:194018 if (!widget_host->GetProcess()->IsInitializedAndNotDead()) {
[email protected]bafe6cd2012-05-23 23:09:504019 // The view has gone away or the renderer crashed. Nothing to do.
alexmosc2a8cec2016-05-23 22:19:534020 return nullptr;
[email protected]bafe6cd2012-05-23 23:09:504021 }
4022
4023 return widget_host_view;
4024}
4025
[email protected]f13b4202012-06-12 23:53:234026void WebContentsImpl::RequestMediaAccessPermission(
[email protected]33662e52013-01-07 21:31:094027 const MediaStreamRequest& request,
Mark Pilgrim57499082018-06-12 12:38:304028 MediaResponseCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:374029 OPTIONAL_TRACE_EVENT2("content",
4030 "WebContentsImpl::RequestMediaAccessPermission",
4031 "render_process_id", request.render_process_id,
4032 "render_frame_id", request.render_frame_id);
4033
[email protected]d19b84b2014-03-14 11:52:374034 if (delegate_) {
Mark Pilgrim57499082018-06-12 12:38:304035 delegate_->RequestMediaAccessPermission(this, request, std::move(callback));
[email protected]d19b84b2014-03-14 11:52:374036 } else {
Antonio Gomes0d42960a2019-06-05 12:35:514037 std::move(callback).Run(
4038 blink::MediaStreamDevices(),
4039 blink::mojom::MediaStreamRequestResult::FAILED_DUE_TO_SHUTDOWN,
4040 std::unique_ptr<MediaStreamUI>());
[email protected]d19b84b2014-03-14 11:52:374041 }
[email protected]f13b4202012-06-12 23:53:234042}
4043
Chandan Padhia4b8bcb72017-09-12 16:41:044044bool WebContentsImpl::CheckMediaAccessPermission(
Raymes Khouryad7c24a12018-03-05 23:22:584045 RenderFrameHost* render_frame_host,
Chandan Padhia4b8bcb72017-09-12 16:41:044046 const url::Origin& security_origin,
Antonio Gomesc8b734b2019-06-05 18:22:164047 blink::mojom::MediaStreamType type) {
Alexander Timin5fdeff22020-09-08 09:20:374048 OPTIONAL_TRACE_EVENT2("content",
4049 "WebContentsImpl::CheckMediaAccessPermission",
4050 "render_frame_host", render_frame_host,
4051 "security_origin", security_origin.Serialize());
4052
Antonio Gomesc8b734b2019-06-05 18:22:164053 DCHECK(type == blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE ||
4054 type == blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE);
Chandan Padhia4b8bcb72017-09-12 16:41:044055 return delegate_ && delegate_->CheckMediaAccessPermission(
Raymes Khouryad7c24a12018-03-05 23:22:584056 render_frame_host, security_origin.GetURL(), type);
grunell657d4d82014-09-18 00:09:434057}
4058
Guido Urdaneta73fa6632019-01-14 18:46:264059std::string WebContentsImpl::GetDefaultMediaDeviceID(
Antonio Gomesc8b734b2019-06-05 18:22:164060 blink::mojom::MediaStreamType type) {
Alexander Timin5fdeff22020-09-08 09:20:374061 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::GetDefaultMediaDeviceID",
4062 "type", static_cast<int>(type));
4063
guidou8a440b842017-01-30 13:58:434064 if (!delegate_)
4065 return std::string();
4066 return delegate_->GetDefaultMediaDeviceID(this, type);
4067}
4068
[email protected]cc9200432013-07-23 23:02:404069SessionStorageNamespace* WebContentsImpl::GetSessionStorageNamespace(
4070 SiteInstance* instance) {
4071 return controller_.GetSessionStorageNamespace(instance);
4072}
4073
[email protected]6de7fc482014-06-06 10:46:444074SessionStorageNamespaceMap WebContentsImpl::GetSessionStorageNamespaceMap() {
4075 return controller_.GetSessionStorageNamespaceMap();
4076}
4077
[email protected]9b159a52013-10-03 17:24:554078FrameTree* WebContentsImpl::GetFrameTree() {
4079 return &frame_tree_;
4080}
4081
aelias5252baa2016-04-10 01:18:024082bool WebContentsImpl::IsOverridingUserAgent() {
4083 return GetController().GetVisibleEntry() &&
4084 GetController().GetVisibleEntry()->GetIsOverridingUserAgent();
4085}
4086
avi85ee8362016-10-08 02:09:084087bool WebContentsImpl::IsJavaScriptDialogShowing() const {
4088 return is_showing_javascript_dialog_;
4089}
4090
avic031d392017-03-03 03:09:424091bool WebContentsImpl::ShouldIgnoreUnresponsiveRenderer() {
Dominique Fauteux-Chapleau99244382020-07-08 20:37:004092 if (suppress_unresponsive_renderer_count_ > 0)
4093 return true;
4094
avic031d392017-03-03 03:09:424095 // Ignore unresponsive renderers if the debugger is attached to them since the
4096 // unresponsiveness might be a result of the renderer sitting on a breakpoint.
4097 //
David Bienvenu525f8a02019-02-15 02:02:424098#ifdef OS_WIN
4099 // Check if a windows debugger is attached to the renderer process.
4100 base::ProcessHandle process_handle =
4101 GetMainFrame()->GetProcess()->GetProcess().Handle();
4102 BOOL debugger_present = FALSE;
4103 if (CheckRemoteDebuggerPresent(process_handle, &debugger_present) &&
4104 debugger_present)
4105 return true;
4106#endif // OS_WIN
4107
avic031d392017-03-03 03:09:424108 // TODO(pfeldman): Fix this to only return true if the renderer is *actually*
4109 // sitting on a breakpoint. https://crbug.com/684202
4110 return DevToolsAgentHost::IsDebuggerAttached(this);
4111}
4112
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414113ui::AXMode WebContentsImpl::GetAccessibilityMode() {
[email protected]95640212014-07-26 18:14:304114 return accessibility_mode_;
4115}
4116
Mario Sanchez Prada5d7f1ac2020-07-16 17:18:404117void WebContentsImpl::AXTreeIDForMainFrameHasChanged() {
Alexander Timin5fdeff22020-09-08 09:20:374118 OPTIONAL_TRACE_EVENT0("content",
4119 "WebContentsImpl::AXTreeIDForMainFrameHasChanged");
4120
Mario Sanchez Prada5d7f1ac2020-07-16 17:18:404121 RenderWidgetHostViewBase* rwhv =
4122 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
4123 if (rwhv)
4124 rwhv->SetMainFrameAXTreeID(GetMainFrame()->GetAXTreeID());
4125
Alexander Timin90c20c32020-08-12 15:28:324126 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4127 observer->AXTreeIDForMainFrameHasChanged();
4128 });
Mario Sanchez Prada5d7f1ac2020-07-16 17:18:404129}
4130
Dominic Mazzonia7b0edb22017-08-09 16:32:514131void WebContentsImpl::AccessibilityEventReceived(
Dominic Mazzoniccbaa9b2018-06-06 07:44:234132 const AXEventNotificationDetails& details) {
Alexander Timin5fdeff22020-09-08 09:20:374133 OPTIONAL_TRACE_EVENT0("content",
4134 "WebContentsImpl::AccessibilityEventReceived");
Alexander Timin90c20c32020-08-12 15:28:324135 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4136 observer->AccessibilityEventReceived(details);
4137 });
[email protected]31a71eaf2014-03-13 01:47:364138}
4139
dmazzoni2400c462016-08-23 15:07:134140void WebContentsImpl::AccessibilityLocationChangesReceived(
4141 const std::vector<AXLocationChangeNotificationDetails>& details) {
Alexander Timin5fdeff22020-09-08 09:20:374142 OPTIONAL_TRACE_EVENT0(
4143 "content", "WebContentsImpl::AccessibilityLocationChangesReceived");
Alexander Timin90c20c32020-08-12 15:28:324144 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4145 observer->AccessibilityLocationChangesReceived(details);
4146 });
dmazzoni2400c462016-08-23 15:07:134147}
4148
Alexander Surkov2ab51622020-09-02 12:01:424149std::string WebContentsImpl::DumpAccessibilityTree(
Abigail Kleinabb428332019-09-13 18:26:214150 bool internal,
4151 std::vector<AccessibilityTreeFormatter::PropertyFilter> property_filters) {
Alexander Timin5fdeff22020-09-08 09:20:374152 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DumpAccessibilityTree");
James Wallace-Leeeafc94cb92018-07-23 21:35:094153 auto* ax_mgr = GetOrCreateRootBrowserAccessibilityManager();
4154 DCHECK(ax_mgr);
Lei Zhangc98caa3822019-11-07 19:17:274155 return AccessibilityTreeFormatterBase::DumpAccessibilityTreeFromManager(
Abigail Kleinabb428332019-09-13 18:26:214156 ax_mgr, internal, property_filters);
James Wallace-Leeeafc94cb92018-07-23 21:35:094157}
4158
Abigail Kleinaa898742019-11-01 02:31:254159void WebContentsImpl::RecordAccessibilityEvents(
Abigail Kleinbb8304bd2020-05-18 21:44:184160 bool start_recording,
4161 base::Optional<AccessibilityEventCallback> callback) {
Alexander Timin5fdeff22020-09-08 09:20:374162 OPTIONAL_TRACE_EVENT0("content",
4163 "WebContentsImpl::RecordAccessibilityEvents");
Abigail Kleinbb8304bd2020-05-18 21:44:184164 // Only pass a callback to RecordAccessibilityEvents when starting to record.
4165 DCHECK_EQ(start_recording, callback.has_value());
4166 if (start_recording) {
Abigail Kleinaa898742019-11-01 02:31:254167 SetAccessibilityMode(ui::AXMode::kWebContents);
4168 auto* ax_mgr = GetOrCreateRootBrowserAccessibilityManager();
4169 DCHECK(ax_mgr);
4170 base::ProcessId pid = base::Process::Current().Pid();
4171 event_recorder_ = content::AccessibilityEventRecorder::Create(
4172 ax_mgr, pid, base::StringPiece{});
Abigail Kleinbb8304bd2020-05-18 21:44:184173 event_recorder_->ListenToEvents(*callback);
Abigail Kleinaa898742019-11-01 02:31:254174 } else {
Abigail Kleinbb8304bd2020-05-18 21:44:184175 if (event_recorder_) {
4176 event_recorder_->FlushAsyncEvents();
4177 event_recorder_.reset(nullptr);
4178 }
Abigail Kleinaa898742019-11-01 02:31:254179 }
4180}
4181
dmazzonia656928e2014-09-15 20:28:544182RenderFrameHost* WebContentsImpl::GetGuestByInstanceID(
fsamuel833ee7c2015-02-13 23:40:404183 RenderFrameHost* render_frame_host,
dmazzonia656928e2014-09-15 20:28:544184 int browser_plugin_instance_id) {
Alexander Timin5fdeff22020-09-08 09:20:374185 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GetGuestByInstanceID");
dmazzonia656928e2014-09-15 20:28:544186 BrowserPluginGuestManager* guest_manager =
4187 GetBrowserContext()->GetGuestManager();
fsamuel9cbc00a2015-04-17 20:30:204188 if (!guest_manager)
4189 return nullptr;
4190
dmazzonia656928e2014-09-15 20:28:544191 WebContents* guest = guest_manager->GetGuestByInstanceID(
fsamuel2e9413d2015-02-25 01:25:444192 render_frame_host->GetProcess()->GetID(), browser_plugin_instance_id);
dmazzonia656928e2014-09-15 20:28:544193 if (!guest)
fsamuel9cbc00a2015-04-17 20:30:204194 return nullptr;
4195
dmazzonia656928e2014-09-15 20:28:544196 return guest->GetMainFrame();
4197}
4198
Ke He7319dbe2017-11-09 05:54:444199device::mojom::GeolocationContext* WebContentsImpl::GetGeolocationContext() {
Alexander Timin5fdeff22020-09-08 09:20:374200 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GetGeolocationContext");
Ella Ge3e375b702020-06-05 15:57:164201 if (delegate_) {
4202 auto* installed_webapp_context =
4203 delegate_->GetInstalledWebappGeolocationContext();
4204 if (installed_webapp_context)
4205 return installed_webapp_context;
4206 }
4207
Ken Rockotce010f02019-12-12 23:32:324208 if (!geolocation_context_) {
4209 GetDeviceService().BindGeolocationContext(
4210 geolocation_context_.BindNewPipeAndPassReceiver());
4211 }
Conley Owens6894c4f2017-07-10 19:29:134212 return geolocation_context_.get();
blundellc57b93f2014-10-29 13:19:574213}
4214
ke.he98b761e2017-05-09 05:59:174215device::mojom::WakeLockContext* WebContentsImpl::GetWakeLockContext() {
blundelld8cd72b2017-03-28 07:18:384216 if (!wake_lock_context_host_)
Fergal Daly55b6d722020-09-11 07:56:334217 wake_lock_context_host_ = std::make_unique<WakeLockContextHost>(this);
blundelle75a8f92017-03-27 08:11:174218 return wake_lock_context_host_->GetWakeLockContext();
alogvinovf50445a2015-10-30 13:00:124219}
4220
blundellf5316fc2017-05-15 11:49:034221#if defined(OS_ANDROID)
Miyoung Shin59f39ff2019-09-17 07:23:204222void WebContentsImpl::GetNFC(
Reilly Grantafbe2242020-02-20 21:14:554223 RenderFrameHost* render_frame_host,
Miyoung Shin59f39ff2019-09-17 07:23:204224 mojo::PendingReceiver<device::mojom::NFC> receiver) {
Reilly Grantafbe2242020-02-20 21:14:554225 if (!nfc_host_)
4226 nfc_host_ = std::make_unique<NFCHost>(this);
4227 nfc_host_->GetNFC(render_frame_host, std::move(receiver));
blundellf5316fc2017-05-15 11:49:034228}
4229#endif
4230
Evan Stade5e750ad02017-08-07 21:59:274231void WebContentsImpl::SetNotWaitingForResponse() {
Alexander Timin5fdeff22020-09-08 09:20:374232 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetNotWaitingForResponse",
4233 "was_waiting_for_response", waiting_for_response_);
Evan Stade5e750ad02017-08-07 21:59:274234 if (waiting_for_response_ == false)
4235 return;
4236
4237 waiting_for_response_ = false;
Alexander Timin90c20c32020-08-12 15:28:324238 observers_.ForEachObserver(
4239 [&](WebContentsObserver* observer) { observer->DidReceiveResponse(); });
Bruce Dawsone1c5c842020-09-15 02:09:144240
4241 // LoadingStateChanged must be called last in case it triggers deletion of
4242 // |this| due to recursive message pumps.
4243 if (delegate_)
4244 delegate_->LoadingStateChanged(this, is_load_to_different_document_);
Evan Stade5e750ad02017-08-07 21:59:274245}
4246
lfgbb9c28a2016-03-01 03:19:494247void WebContentsImpl::SendScreenRects() {
Alexander Timin5fdeff22020-09-08 09:20:374248 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SendScreenRects");
kenrbc52e1b4e2016-03-20 01:03:374249 for (FrameTreeNode* node : frame_tree_.Nodes()) {
kenrb0e8dc202016-05-30 19:51:404250 if (node->current_frame_host()->is_local_root())
kenrbc52e1b4e2016-03-20 01:03:374251 node->current_frame_host()->GetRenderWidgetHost()->SendScreenRects();
4252 }
[email protected]32deec62013-05-15 23:55:044253}
4254
ekaramadadd882292016-06-08 15:22:564255TextInputManager* WebContentsImpl::GetTextInputManager() {
4256 if (GetOuterWebContents())
4257 return GetOuterWebContents()->GetTextInputManager();
4258
Ehsan Karamadc179dc02018-12-15 03:09:294259 if (!text_input_manager_ && !browser_plugin_guest_) {
Fergal Daly55b6d722020-09-11 07:56:334260 text_input_manager_ = std::make_unique<TextInputManager>(
Darren Shenca53d5f2018-05-15 04:56:014261 GetBrowserContext() &&
Fergal Daly55b6d722020-09-11 07:56:334262 !GetBrowserContext()->IsOffTheRecord() /* should_do_learning */);
Darren Shenca53d5f2018-05-15 04:56:014263 }
ekaramadadd882292016-06-08 15:22:564264
4265 return text_input_manager_.get();
4266}
4267
paulmeyer7f6f1d4f2016-11-15 00:00:274268bool WebContentsImpl::OnUpdateDragCursor() {
Alexander Timin5fdeff22020-09-08 09:20:374269 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnUpdateDragCursor");
Lei Zhang6410ec1a2019-01-31 21:38:584270 return browser_plugin_embedder_ &&
4271 browser_plugin_embedder_->OnUpdateDragCursor();
paulmeyer7f6f1d4f2016-11-15 00:00:274272}
4273
kenrb11f213a2017-03-24 18:12:064274bool WebContentsImpl::IsWidgetForMainFrame(
4275 RenderWidgetHostImpl* render_widget_host) {
4276 return render_widget_host == GetMainFrame()->GetRenderWidgetHost();
4277}
4278
[email protected]95640212014-07-26 18:14:304279BrowserAccessibilityManager*
Alexander Timin5fdeff22020-09-08 09:20:374280WebContentsImpl::GetRootBrowserAccessibilityManager() {
Carlos ILd51e7702020-05-07 18:51:394281 RenderFrameHostImpl* rfh = static_cast<RenderFrameHostImpl*>(GetMainFrame());
creisc014b402015-04-23 16:41:454282 return rfh ? rfh->browser_accessibility_manager() : nullptr;
[email protected]95640212014-07-26 18:14:304283}
4284
4285BrowserAccessibilityManager*
Alexander Timin5fdeff22020-09-08 09:20:374286WebContentsImpl::GetOrCreateRootBrowserAccessibilityManager() {
Carlos ILd51e7702020-05-07 18:51:394287 RenderFrameHostImpl* rfh = static_cast<RenderFrameHostImpl*>(GetMainFrame());
creisc014b402015-04-23 16:41:454288 return rfh ? rfh->GetOrCreateBrowserAccessibilityManager() : nullptr;
[email protected]95640212014-07-26 18:14:304289}
4290
Dave Tapuskab336b922017-07-06 19:24:054291void WebContentsImpl::ExecuteEditCommand(
4292 const std::string& command,
4293 const base::Optional<base::string16>& value) {
Alexander Timin5fdeff22020-09-08 09:20:374294 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ExecuteEditCommand");
Dave Tapuska58a099e2020-06-08 21:48:404295 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514296 if (!input_handler)
Dave Tapuskab336b922017-07-06 19:24:054297 return;
4298
Dave Tapuskae782bea2019-07-09 16:21:514299 input_handler->ExecuteEditCommand(command, value);
Dave Tapuskab336b922017-07-06 19:24:054300}
4301
mohsen7ab1ec16ec2015-07-02 18:26:234302void WebContentsImpl::MoveRangeSelectionExtent(const gfx::Point& extent) {
Alexander Timin5fdeff22020-09-08 09:20:374303 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MoveRangeSelectionExtent");
Dave Tapuska58a099e2020-06-08 21:48:404304 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514305 if (!input_handler)
mohsen7ab1ec16ec2015-07-02 18:26:234306 return;
4307
Dave Tapuskae782bea2019-07-09 16:21:514308 input_handler->MoveRangeSelectionExtent(extent);
mohsen7ab1ec16ec2015-07-02 18:26:234309}
4310
4311void WebContentsImpl::SelectRange(const gfx::Point& base,
4312 const gfx::Point& extent) {
Alexander Timin5fdeff22020-09-08 09:20:374313 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SelectRange");
Dave Tapuska58a099e2020-06-08 21:48:404314 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514315 if (!input_handler)
mohsen7ab1ec16ec2015-07-02 18:26:234316 return;
4317
Dave Tapuskae782bea2019-07-09 16:21:514318 input_handler->SelectRange(base, extent);
mohsen7ab1ec16ec2015-07-02 18:26:234319}
4320
Dave Tapuskab336b922017-07-06 19:24:054321void WebContentsImpl::MoveCaret(const gfx::Point& extent) {
Alexander Timin5fdeff22020-09-08 09:20:374322 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
4323 "WebContentsImpl::MoveCaret");
Dave Tapuska58a099e2020-06-08 21:48:404324 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514325 if (!input_handler)
Dave Tapuskab336b922017-07-06 19:24:054326 return;
4327
Dave Tapuskae782bea2019-07-09 16:21:514328 input_handler->MoveCaret(extent);
Dave Tapuskab336b922017-07-06 19:24:054329}
4330
Shimi Zhang37deeb22017-09-28 00:59:014331void WebContentsImpl::AdjustSelectionByCharacterOffset(
4332 int start_adjust,
4333 int end_adjust,
4334 bool show_selection_menu) {
Alexander Timin5fdeff22020-09-08 09:20:374335 OPTIONAL_TRACE_EVENT0("content",
4336 "WebContentsImpl::AdjustSelectionByCharacterOffset");
Dave Tapuska58a099e2020-06-08 21:48:404337 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514338 if (!input_handler)
aurimasab0319022015-07-10 21:57:384339 return;
4340
Shimi Zhang37deeb22017-09-28 00:59:014341 using blink::mojom::SelectionMenuBehavior;
Dave Tapuskae782bea2019-07-09 16:21:514342 input_handler->AdjustSelectionByCharacterOffset(
Shimi Zhang37deeb22017-09-28 00:59:014343 start_adjust, end_adjust,
4344 show_selection_menu ? SelectionMenuBehavior::kShow
4345 : SelectionMenuBehavior::kHide);
aurimasab0319022015-07-10 21:57:384346}
4347
[email protected]b172aee2012-04-10 17:05:264348void WebContentsImpl::UpdatePreferredSize(const gfx::Size& pref_size) {
Alexander Timin5fdeff22020-09-08 09:20:374349 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::UpdatePreferredSize");
[email protected]222f5822014-02-05 23:40:494350 const gfx::Size old_size = GetPreferredSize();
[email protected]bcd2815602012-01-14 18:17:234351 preferred_size_ = pref_size;
[email protected]222f5822014-02-05 23:40:494352 OnPreferredSizeChanged(old_size);
[email protected]0548c5352011-09-07 00:33:334353}
4354
avic3aa8422015-11-09 20:57:224355void WebContentsImpl::ResizeDueToAutoResize(
4356 RenderWidgetHostImpl* render_widget_host,
Fady Samuel97947112018-05-05 16:24:544357 const gfx::Size& new_size) {
Alexander Timin5fdeff22020-09-08 09:20:374358 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ResizeDueToAutoResize",
4359 "render_widget_host", render_widget_host);
avic3aa8422015-11-09 20:57:224360 if (render_widget_host != GetRenderViewHost()->GetWidget())
4361 return;
4362
[email protected]61e2b3cc2012-03-02 16:13:344363 if (delegate_)
4364 delegate_->ResizeDueToAutoResize(this, new_size);
4365}
4366
[email protected]b172aee2012-04-10 17:05:264367WebContents* WebContentsImpl::OpenURL(const OpenURLParams& params) {
Alexander Timin5fdeff22020-09-08 09:20:374368 TRACE_EVENT1("content", "WebContentsImpl::OpenURL", "url",
4369 base::trace_event::ValueToString(params.url));
Aaron Colwell9dab1652019-12-09 18:29:494370#if DCHECK_IS_ON()
4371 DCHECK(params.Valid());
4372#endif
4373
Bo Liu300c6052018-06-12 04:46:074374 if (!delegate_) {
4375 // Embedder can delay setting a delegate on new WebContents with
4376 // WebContentsDelegate::ShouldResumeRequestsForCreatedWindow. In the mean
4377 // time, navigations, including the initial one, that goes through OpenURL
4378 // should be delayed until embedder is ready to resume loading.
4379 delayed_open_url_params_ = std::make_unique<OpenURLParams>(params);
Nasko Oskov83a8cf92018-10-19 14:58:564380
4381 // If there was a navigation deferred when creating the window through
4382 // CreateNewWindow, drop it in favor of this navigation.
4383 delayed_load_url_params_.reset();
4384
Ivan Kotenkov2c0d2bb32017-11-01 15:41:284385 return nullptr;
Bo Liu300c6052018-06-12 04:46:074386 }
[email protected]00c37fc2011-08-02 00:22:504387
[email protected]e5d549d2011-12-28 01:29:204388 WebContents* new_contents = delegate_->OpenURLFromTab(this, params);
pnoland488944652017-02-22 18:58:544389
4390 RenderFrameHost* source_render_frame_host = RenderFrameHost::FromID(
4391 params.source_render_process_id, params.source_render_frame_id);
4392
4393 if (source_render_frame_host && params.source_site_instance) {
4394 CHECK_EQ(source_render_frame_host->GetSiteInstance(),
4395 params.source_site_instance.get());
4396 }
4397
4398 if (new_contents && source_render_frame_host && new_contents != this) {
Alexander Timin90c20c32020-08-12 15:28:324399 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4400 observer->DidOpenRequestedURL(
Lukasz Anforowicz48c9f872018-08-01 00:58:414401 new_contents, source_render_frame_host, params.url, params.referrer,
4402 params.disposition, params.transition,
4403 params.started_from_context_menu, params.is_renderer_initiated);
Alexander Timin90c20c32020-08-12 15:28:324404 });
pnoland488944652017-02-22 18:58:544405 }
4406
[email protected]e5d549d2011-12-28 01:29:204407 return new_contents;
[email protected]d5f942ba2008-09-26 19:30:344408}
4409
avi2b177592014-12-10 02:08:024410void WebContentsImpl::SetHistoryOffsetAndLength(int history_offset,
4411 int history_length) {
Alexander Timin5fdeff22020-09-08 09:20:374412 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetHistoryOffsetAndLength",
4413 "history_offset", history_offset, "history_length",
4414 history_length);
alexmos136fd6e62016-08-15 20:58:414415 SendPageMessage(new PageMsg_SetHistoryOffsetAndLength(
4416 MSG_ROUTING_NONE, history_offset, history_length));
avi2b177592014-12-10 02:08:024417}
4418
4419void WebContentsImpl::SetHistoryOffsetAndLengthForView(
4420 RenderViewHost* render_view_host,
4421 int history_offset,
4422 int history_length) {
Alexander Timin5fdeff22020-09-08 09:20:374423 OPTIONAL_TRACE_EVENT2(
4424 "content", "WebContentsImpl::SetHistoryOffsetAndLengthForView",
4425 "history_offset", history_offset, "history_length", history_length);
alexmos136fd6e62016-08-15 20:58:414426 render_view_host->Send(new PageMsg_SetHistoryOffsetAndLength(
avi2b177592014-12-10 02:08:024427 render_view_host->GetRoutingID(), history_offset, history_length));
[email protected]796931a92011-08-10 01:32:144428}
4429
arthursonzogni818c2642019-09-27 12:18:104430void WebContentsImpl::ReloadFocusedFrame() {
Alexander Timin5fdeff22020-09-08 09:20:374431 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ReloadFocusedFrame");
[email protected]1f3fc1d2014-04-03 14:50:174432 RenderFrameHost* focused_frame = GetFocusedFrame();
4433 if (!focused_frame)
4434 return;
4435
yilkal921048bd2019-10-09 23:51:044436 focused_frame->Reload();
[email protected]959be4c2014-04-08 15:01:334437}
4438
4439void WebContentsImpl::Undo() {
Alexander Timin5fdeff22020-09-08 09:20:374440 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Undo");
Dave Tapuska58a099e2020-06-08 21:48:404441 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514442 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334443 return;
4444
Dave Tapuskae782bea2019-07-09 16:21:514445 input_handler->Undo();
[email protected]959be4c2014-04-08 15:01:334446 RecordAction(base::UserMetricsAction("Undo"));
4447}
4448
4449void WebContentsImpl::Redo() {
Alexander Timin5fdeff22020-09-08 09:20:374450 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Redo");
Dave Tapuska58a099e2020-06-08 21:48:404451 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514452 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334453 return;
Dave Tapuskae782bea2019-07-09 16:21:514454
4455 input_handler->Redo();
[email protected]959be4c2014-04-08 15:01:334456 RecordAction(base::UserMetricsAction("Redo"));
4457}
4458
4459void WebContentsImpl::Cut() {
Alexander Timin5fdeff22020-09-08 09:20:374460 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Cut");
Dave Tapuska58a099e2020-06-08 21:48:404461 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514462 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334463 return;
4464
Dave Tapuskae782bea2019-07-09 16:21:514465 input_handler->Cut();
[email protected]959be4c2014-04-08 15:01:334466 RecordAction(base::UserMetricsAction("Cut"));
4467}
4468
4469void WebContentsImpl::Copy() {
Alexander Timin5fdeff22020-09-08 09:20:374470 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Copy");
Dave Tapuska58a099e2020-06-08 21:48:404471 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514472 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334473 return;
4474
Dave Tapuskae782bea2019-07-09 16:21:514475 input_handler->Copy();
[email protected]959be4c2014-04-08 15:01:334476 RecordAction(base::UserMetricsAction("Copy"));
4477}
4478
4479void WebContentsImpl::CopyToFindPboard() {
Alexander Timin5fdeff22020-09-08 09:20:374480 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::CopyToFindPboard");
Avi Drissman7c57be72020-07-29 20:09:464481#if defined(OS_MAC)
Dave Tapuska58a099e2020-06-08 21:48:404482 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514483 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334484 return;
4485
4486 // Windows/Linux don't have the concept of a find pasteboard.
Dave Tapuskae782bea2019-07-09 16:21:514487 input_handler->CopyToFindPboard();
[email protected]959be4c2014-04-08 15:01:334488 RecordAction(base::UserMetricsAction("CopyToFindPboard"));
4489#endif
4490}
4491
4492void WebContentsImpl::Paste() {
Alexander Timin5fdeff22020-09-08 09:20:374493 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Paste");
Dave Tapuska58a099e2020-06-08 21:48:404494 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514495 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334496 return;
4497
Dave Tapuskae782bea2019-07-09 16:21:514498 input_handler->Paste();
Alexander Timin90c20c32020-08-12 15:28:324499 observers_.ForEachObserver(
4500 [&](WebContentsObserver* observer) { observer->OnPaste(); });
[email protected]959be4c2014-04-08 15:01:334501 RecordAction(base::UserMetricsAction("Paste"));
4502}
4503
4504void WebContentsImpl::PasteAndMatchStyle() {
Alexander Timin5fdeff22020-09-08 09:20:374505 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::PasteAndMatchStyle");
Dave Tapuska58a099e2020-06-08 21:48:404506 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514507 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334508 return;
4509
Dave Tapuskae782bea2019-07-09 16:21:514510 input_handler->PasteAndMatchStyle();
Alexander Timin90c20c32020-08-12 15:28:324511 observers_.ForEachObserver(
4512 [&](WebContentsObserver* observer) { observer->OnPaste(); });
[email protected]959be4c2014-04-08 15:01:334513 RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
4514}
4515
4516void WebContentsImpl::Delete() {
Alexander Timin5fdeff22020-09-08 09:20:374517 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Delete");
Dave Tapuska58a099e2020-06-08 21:48:404518 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514519 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334520 return;
4521
Dave Tapuskae782bea2019-07-09 16:21:514522 input_handler->Delete();
[email protected]959be4c2014-04-08 15:01:334523 RecordAction(base::UserMetricsAction("DeleteSelection"));
4524}
4525
4526void WebContentsImpl::SelectAll() {
Alexander Timin5fdeff22020-09-08 09:20:374527 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SelectAll");
Dave Tapuska58a099e2020-06-08 21:48:404528 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514529 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334530 return;
4531
Dave Tapuskae782bea2019-07-09 16:21:514532 input_handler->SelectAll();
[email protected]959be4c2014-04-08 15:01:334533 RecordAction(base::UserMetricsAction("SelectAll"));
4534}
4535
yabinh351e7ec2017-03-10 02:43:244536void WebContentsImpl::CollapseSelection() {
Alexander Timin5fdeff22020-09-08 09:20:374537 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::CollapseSelection");
Dave Tapuska58a099e2020-06-08 21:48:404538 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514539 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334540 return;
4541
Dave Tapuskae782bea2019-07-09 16:21:514542 input_handler->CollapseSelection();
[email protected]1f3fc1d2014-04-03 14:50:174543}
4544
4545void WebContentsImpl::Replace(const base::string16& word) {
Alexander Timin5fdeff22020-09-08 09:20:374546 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Replace");
Dave Tapuska58a099e2020-06-08 21:48:404547 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514548 if (!input_handler)
[email protected]1f3fc1d2014-04-03 14:50:174549 return;
4550
Dave Tapuskae782bea2019-07-09 16:21:514551 input_handler->Replace(word);
[email protected]1f3fc1d2014-04-03 14:50:174552}
4553
4554void WebContentsImpl::ReplaceMisspelling(const base::string16& word) {
Alexander Timin5fdeff22020-09-08 09:20:374555 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ReplaceMisspelling");
Dave Tapuska58a099e2020-06-08 21:48:404556 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514557 if (!input_handler)
[email protected]1f3fc1d2014-04-03 14:50:174558 return;
4559
Dave Tapuskae782bea2019-07-09 16:21:514560 input_handler->ReplaceMisspelling(word);
[email protected]959be4c2014-04-08 15:01:334561}
4562
4563void WebContentsImpl::NotifyContextMenuClosed(
4564 const CustomContextMenuContext& context) {
Alexander Timin5fdeff22020-09-08 09:20:374565 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::NotifyContextMenuClosed");
[email protected]959be4c2014-04-08 15:01:334566 RenderFrameHost* focused_frame = GetFocusedFrame();
4567 if (!focused_frame)
4568 return;
4569
4570 focused_frame->Send(new FrameMsg_ContextMenuClosed(
4571 focused_frame->GetRoutingID(), context));
4572}
4573
4574void WebContentsImpl::ExecuteCustomContextMenuCommand(
4575 int action, const CustomContextMenuContext& context) {
Alexander Timin5fdeff22020-09-08 09:20:374576 OPTIONAL_TRACE_EVENT1("content",
4577 "WebContentsImpl::ExecuteCustomContextMenuCommand",
4578 "action", action);
[email protected]959be4c2014-04-08 15:01:334579 RenderFrameHost* focused_frame = GetFocusedFrame();
4580 if (!focused_frame)
4581 return;
4582
4583 focused_frame->Send(new FrameMsg_CustomContextMenuAction(
4584 focused_frame->GetRoutingID(), context, action));
[email protected]4fed3702014-04-01 09:08:004585}
4586
[email protected]fc2b46b2014-05-03 16:33:454587gfx::NativeView WebContentsImpl::GetNativeView() {
4588 return view_->GetNativeView();
4589}
4590
4591gfx::NativeView WebContentsImpl::GetContentNativeView() {
4592 return view_->GetContentNativeView();
4593}
4594
4595gfx::NativeWindow WebContentsImpl::GetTopLevelNativeWindow() {
4596 return view_->GetTopLevelNativeWindow();
4597}
4598
4599gfx::Rect WebContentsImpl::GetViewBounds() {
4600 return view_->GetViewBounds();
4601}
4602
4603gfx::Rect WebContentsImpl::GetContainerBounds() {
Jeremy Roman352239c2020-05-21 16:31:324604 return view_->GetContainerBounds();
[email protected]fc2b46b2014-05-03 16:33:454605}
4606
4607DropData* WebContentsImpl::GetDropData() {
4608 return view_->GetDropData();
4609}
4610
4611void WebContentsImpl::Focus() {
Alexander Timin5fdeff22020-09-08 09:20:374612 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Focus");
miu9e14e492014-10-25 02:39:044613 view_->Focus();
[email protected]fc2b46b2014-05-03 16:33:454614}
4615
4616void WebContentsImpl::SetInitialFocus() {
Alexander Timin5fdeff22020-09-08 09:20:374617 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetInitialFocus");
miu9e14e492014-10-25 02:39:044618 view_->SetInitialFocus();
[email protected]fc2b46b2014-05-03 16:33:454619}
4620
4621void WebContentsImpl::StoreFocus() {
Alexander Timin5fdeff22020-09-08 09:20:374622 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::StoreFocus");
miu9e14e492014-10-25 02:39:044623 view_->StoreFocus();
[email protected]fc2b46b2014-05-03 16:33:454624}
4625
4626void WebContentsImpl::RestoreFocus() {
Alexander Timin5fdeff22020-09-08 09:20:374627 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::RestoreFocus");
miu9e14e492014-10-25 02:39:044628 view_->RestoreFocus();
[email protected]fc2b46b2014-05-03 16:33:454629}
4630
[email protected]b172aee2012-04-10 17:05:264631void WebContentsImpl::FocusThroughTabTraversal(bool reverse) {
Alexander Timin5fdeff22020-09-08 09:20:374632 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::FocusThroughTabTraversal",
4633 "reverse", reverse);
Maxim Podgorodskiya926c4ff2017-11-20 02:06:394634 view_->FocusThroughTabTraversal(reverse);
[email protected]96d185d2009-04-24 03:28:544635}
4636
[email protected]b172aee2012-04-10 17:05:264637bool WebContentsImpl::IsSavable() {
[email protected]a53209b2012-01-20 16:48:164638 // WebKit creates Document object when MIME type is application/xhtml+xml,
4639 // so we also support this MIME type.
Yuzu Saijoc23e9b72020-06-25 07:21:274640 std::string mime_type = GetContentsMimeType();
4641 return mime_type == "text/html" || mime_type == "text/xml" ||
4642 mime_type == "application/xhtml+xml" || mime_type == "text/plain" ||
4643 mime_type == "text/css" ||
4644 blink::IsSupportedJavascriptMimeType(mime_type);
[email protected]a53209b2012-01-20 16:48:164645}
4646
[email protected]b172aee2012-04-10 17:05:264647void WebContentsImpl::OnSavePage() {
Alexander Timin5fdeff22020-09-08 09:20:374648 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnSavePage");
[email protected]c7dd2f62011-07-18 15:57:594649 // If we can not save the page, try to download it.
[email protected]a53209b2012-01-20 16:48:164650 if (!IsSavable()) {
Min Qinda0ed2062018-02-23 22:00:534651 download::RecordSavePackageEvent(
4652 download::SAVE_PACKAGE_DOWNLOAD_ON_NON_HTML);
nasko89ad7742015-03-05 22:14:194653 SaveFrame(GetLastCommittedURL(), Referrer());
[email protected]27678b2a2012-02-04 22:09:144654 return;
[email protected]c7dd2f62011-07-18 15:57:594655 }
4656
4657 Stop();
4658
4659 // Create the save package and possibly prompt the user for the name to save
4660 // the page as. The user prompt is an asynchronous operation that runs on
4661 // another thread.
4662 save_package_ = new SavePackage(this);
4663 save_package_->GetSaveInfo();
4664}
4665
4666// Used in automated testing to bypass prompting the user for file names.
4667// Instead, the names and paths are hard coded rather than running them through
4668// file name sanitation and extension / mime checking.
[email protected]2dec8ec2013-02-07 19:20:344669bool WebContentsImpl::SavePage(const base::FilePath& main_file,
4670 const base::FilePath& dir_path,
[email protected]8ff00d72012-10-23 19:12:214671 SavePageType save_type) {
Alexander Timin5fdeff22020-09-08 09:20:374672 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SavePage", "main_file",
4673 base::trace_event::ValueToString(main_file), "dir_path",
4674 base::trace_event::ValueToString(dir_path));
[email protected]c7dd2f62011-07-18 15:57:594675 // Stop the page from navigating.
4676 Stop();
4677
4678 save_package_ = new SavePackage(this, save_type, main_file, dir_path);
[email protected]8ff00d72012-10-23 19:12:214679 return save_package_->Init(SavePackageDownloadCreatedCallback());
[email protected]c7dd2f62011-07-18 15:57:594680}
4681
Alexander Timin5fdeff22020-09-08 09:20:374682void WebContentsImpl::SaveFrame(const GURL& url, const Referrer& referrer) {
4683 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SaveFrame");
Xing Liu10329bf2018-03-20 19:22:144684 SaveFrameWithHeaders(url, referrer, std::string(), base::string16());
kundaji6c7f9692015-03-09 18:00:374685}
4686
Xing Liu10329bf2018-03-20 19:22:144687void WebContentsImpl::SaveFrameWithHeaders(
4688 const GURL& url,
4689 const Referrer& referrer,
4690 const std::string& headers,
4691 const base::string16& suggested_filename) {
Alexander Timin5fdeff22020-09-08 09:20:374692 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SaveFrameWithHeaders",
4693 "url", base::trace_event::ValueToString(url), "headers",
4694 headers);
Lei Zhang13a42e42019-02-19 23:28:114695 // Check and see if the guest can handle this.
4696 if (delegate_) {
4697 WebContents* guest_web_contents = nullptr;
4698 if (browser_plugin_embedder_) {
4699 BrowserPluginGuest* guest = browser_plugin_embedder_->GetFullPageGuest();
4700 if (guest)
4701 guest_web_contents = guest->GetWebContents();
4702 } else if (browser_plugin_guest_) {
4703 guest_web_contents = this;
4704 }
4705
4706 if (guest_web_contents && delegate_->GuestSaveFrame(guest_web_contents))
4707 return;
4708 }
4709
nasko89ad7742015-03-05 22:14:194710 if (!GetLastCommittedURL().is_valid())
[email protected]3c71576ce2013-07-23 02:00:014711 return;
sammc92af61552014-11-19 23:27:404712 if (delegate_ && delegate_->SaveFrame(url, referrer))
4713 return;
4714
nasko89ad7742015-03-05 22:14:194715 // TODO(nasko): This check for main frame is incorrect and should be fixed
brettw760f7442016-05-23 21:19:224716 // by explicitly passing in which frame this method should target. This would
4717 // indicate whether it's the main frame, and also tell us the frame pointer
4718 // to use for routing.
nasko89ad7742015-03-05 22:14:194719 bool is_main_frame = (url == GetLastCommittedURL());
brettw760f7442016-05-23 21:19:224720 RenderFrameHost* frame_host = GetMainFrame();
[email protected]3c71576ce2013-07-23 02:00:014721
avib7348942015-12-25 20:57:104722 int64_t post_id = -1;
[email protected]3c71576ce2013-07-23 02:00:014723 if (is_main_frame) {
Lucas Furukawa Gadani5553a152019-01-08 18:55:574724 NavigationEntry* entry = controller_.GetLastCommittedEntry();
[email protected]3c71576ce2013-07-23 02:00:014725 if (entry)
4726 post_id = entry->GetPostID();
4727 }
Ramin Halavati24e21012017-07-10 12:56:064728 net::NetworkTrafficAnnotationTag traffic_annotation =
4729 net::DefineNetworkTrafficAnnotation("download_web_contents_frame", R"(
4730 semantics {
4731 sender: "Save Page Action"
4732 description:
4733 "Saves the given frame's URL to the local file system."
4734 trigger:
4735 "The user has triggered a save operation on the frame through a "
4736 "context menu or other mechanism."
4737 data: "None."
4738 destination: WEBSITE
4739 }
4740 policy {
Ramin Halavati3b979782017-07-21 11:40:264741 cookies_allowed: YES
Ramin Halavati24e21012017-07-10 12:56:064742 cookies_store: "user"
4743 setting:
4744 "This feature cannot be disabled by settings, but it's is only "
4745 "triggered by user request."
4746 policy_exception_justification: "Not implemented."
4747 })");
Min Qina904f3302018-02-13 23:33:344748 auto params = std::make_unique<download::DownloadUrlParameters>(
brettw760f7442016-05-23 21:19:224749 url, frame_host->GetProcess()->GetID(),
4750 frame_host->GetRenderViewHost()->GetRoutingID(),
Matt Menke0dcaebc32020-03-06 17:00:104751 frame_host->GetRoutingID(), traffic_annotation);
Min Qina904f3302018-02-13 23:33:344752 params->set_referrer(referrer.url);
4753 params->set_referrer_policy(
4754 Referrer::ReferrerPolicyForUrlRequest(referrer.policy));
[email protected]3c71576ce2013-07-23 02:00:014755 params->set_post_id(post_id);
[email protected]3c71576ce2013-07-23 02:00:014756 if (post_id >= 0)
4757 params->set_method("POST");
4758 params->set_prompt(true);
kundaji6c7f9692015-03-09 18:00:374759
4760 if (headers.empty()) {
4761 params->set_prefer_cache(true);
4762 } else {
Min Qina904f3302018-02-13 23:33:344763 for (download::DownloadUrlParameters::RequestHeadersNameValuePair
4764 key_value : ParseDownloadHeaders(headers)) {
Megan Jablonski2f6a4c52017-07-10 23:01:254765 params->add_request_header(key_value.first, key_value.second);
kundaji6c7f9692015-03-09 18:00:374766 }
4767 }
Xing Liu10329bf2018-03-20 19:22:144768 params->set_suggested_name(suggested_filename);
Min Qin0ca8e1ee2018-01-31 00:49:354769 params->set_download_source(download::DownloadSource::WEB_CONTENTS_API);
thestig859c78892017-05-15 21:17:064770 BrowserContext::GetDownloadManager(GetBrowserContext())
Ramin Halavati03efa732017-06-12 09:28:204771 ->DownloadUrl(std::move(params));
[email protected]3c71576ce2013-07-23 02:00:014772}
4773
[email protected]b172aee2012-04-10 17:05:264774void WebContentsImpl::GenerateMHTML(
dewittj6dc5747a2016-05-17 01:48:474775 const MHTMLGenerationParams& params,
Avi Drissman149b7832018-03-23 14:31:494776 base::OnceCallback<void(int64_t)> callback) {
Alexander Timin5fdeff22020-09-08 09:20:374777 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GenerateMHTML");
Angel Alvarez902496682019-08-27 22:58:424778 base::OnceCallback<void(const MHTMLGenerationResult&)> wrapper_callback =
4779 base::BindOnce(
4780 [](base::OnceCallback<void(int64_t)> size_callback,
4781 const MHTMLGenerationResult& result) {
4782 std::move(size_callback).Run(result.file_size);
4783 },
4784 std::move(callback));
4785 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, params,
4786 std::move(wrapper_callback));
4787}
4788
4789void WebContentsImpl::GenerateMHTMLWithResult(
4790 const MHTMLGenerationParams& params,
4791 MHTMLGenerationResult::GenerateMHTMLCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:374792 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GenerateMHTMLWithResult");
Avi Drissman149b7832018-03-23 14:31:494793 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, params,
4794 std::move(callback));
[email protected]aa4f3972012-03-01 18:12:124795}
4796
Tsuyoshi Horob0d8d902020-03-12 00:09:394797void WebContentsImpl::GenerateWebBundle(
4798 const base::FilePath& file_path,
4799 base::OnceCallback<void(uint64_t /* file_size */,
4800 data_decoder::mojom::WebBundlerError)> callback) {
Alexander Timin5fdeff22020-09-08 09:20:374801 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::GenerateWebBundle",
4802 "file_path",
4803 base::trace_event::ValueToString(file_path));
Tsuyoshi Horob0d8d902020-03-12 00:09:394804 SaveAsWebBundleJob::Start(this, file_path, std::move(callback));
4805}
4806
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414807const std::string& WebContentsImpl::GetContentsMimeType() {
Yuzu Saijoc23e9b72020-06-25 07:21:274808 return GetRenderViewHost()->contents_mime_type();
[email protected]0bfbf882011-12-22 18:19:274809}
4810
Leon Hanc819dc62019-01-28 04:30:194811blink::mojom::RendererPreferences* WebContentsImpl::GetMutableRendererPrefs() {
[email protected]0bfbf882011-12-22 18:19:274812 return &renderer_preferences_;
4813}
4814
[email protected]e35ccd52012-05-23 16:22:474815void WebContentsImpl::Close() {
Alexander Timin5fdeff22020-09-08 09:20:374816 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Close");
[email protected]e35ccd52012-05-23 16:22:474817 Close(GetRenderViewHost());
4818}
4819
Ella Ge80a52dce2017-11-15 18:01:524820void WebContentsImpl::DragSourceEndedAt(float client_x,
4821 float client_y,
4822 float screen_x,
4823 float screen_y,
Paul Meyer0c58c3712016-11-17 22:59:514824 blink::WebDragOperation operation,
4825 RenderWidgetHost* source_rwh) {
Alexander Timin5fdeff22020-09-08 09:20:374826 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
4827 "WebContentsImpl::DragSourceEndedAt");
Lei Zhang6410ec1a2019-01-31 21:38:584828 if (browser_plugin_embedder_) {
W. James MacLean9437b5bf2019-12-06 17:33:444829 browser_plugin_embedder_->DragSourceEndedAt(client_x, client_y, screen_x,
4830 screen_y, operation);
Lei Zhang6410ec1a2019-01-31 21:38:584831 }
Paul Meyer0c58c3712016-11-17 22:59:514832 if (source_rwh) {
Ella Ge80a52dce2017-11-15 18:01:524833 source_rwh->DragSourceEndedAt(gfx::PointF(client_x, client_y),
4834 gfx::PointF(screen_x, screen_y), operation);
Paul Meyer0c58c3712016-11-17 22:59:514835 }
[email protected]cf200a562013-05-03 16:24:294836}
4837
jam73f892642016-09-11 06:04:064838void WebContentsImpl::LoadStateChanged(
Charles Harrison911fa062018-03-06 21:01:464839 const std::string& host,
jam73f892642016-09-11 06:04:064840 const net::LoadStateWithParam& load_state,
4841 uint64_t upload_position,
4842 uint64_t upload_size) {
Alexander Timin5fdeff22020-09-08 09:20:374843 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::LoadStateChanged", "host",
4844 host, "load_state", static_cast<int>(load_state.state));
Charles Harrison911fa062018-03-06 21:01:464845 base::string16 host16 = url_formatter::IDNToUnicode(host);
Elly Fong-Jonescad9c3d12018-01-31 17:26:104846 // Drop no-op updates.
4847 if (load_state_.state == load_state.state &&
4848 load_state_.param == load_state.param &&
4849 upload_position_ == upload_position && upload_size_ == upload_size &&
Charles Harrison911fa062018-03-06 21:01:464850 load_state_host_ == host16) {
Elly Fong-Jonescad9c3d12018-01-31 17:26:104851 return;
4852 }
jam73f892642016-09-11 06:04:064853 load_state_ = load_state;
4854 upload_position_ = upload_position;
4855 upload_size_ = upload_size;
Charles Harrison911fa062018-03-06 21:01:464856 load_state_host_ = host16;
jam73f892642016-09-11 06:04:064857 if (load_state_.state == net::LOAD_STATE_READING_RESPONSE)
4858 SetNotWaitingForResponse();
jam73f892642016-09-11 06:04:064859}
4860
Collin Baker989e0882019-11-01 01:27:174861void WebContentsImpl::SetVisibilityAndNotifyObservers(Visibility visibility) {
Alexander Timin5fdeff22020-09-08 09:20:374862 OPTIONAL_TRACE_EVENT1("content",
4863 "WebContentsImpl::SetVisibilityAndNotifyObservers",
4864 "visibility", static_cast<int>(visibility));
Francois Doraye6161152018-03-27 22:05:374865 const Visibility previous_visibility = visibility_;
4866 visibility_ = visibility;
4867
Francois Dorayfe4a1772018-02-17 04:17:094868 // Notify observers if the visibility changed or if WasShown() is being called
4869 // for the first time.
Francois Dorayfe4a1772018-02-17 04:17:094870 if (visibility != previous_visibility ||
4871 (visibility == Visibility::VISIBLE && !did_first_set_visible_)) {
Alexander Timin90c20c32020-08-12 15:28:324872 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4873 observer->OnVisibilityChanged(visibility);
4874 });
Francois Dorayfe4a1772018-02-17 04:17:094875 }
4876}
4877
Michael Thiessen896405db2017-07-20 17:52:324878void WebContentsImpl::NotifyWebContentsFocused(
4879 RenderWidgetHost* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:374880 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::NotifyWebContentsFocused",
4881 "render_widget_host", render_widget_host);
Alexander Timin90c20c32020-08-12 15:28:324882 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4883 observer->OnWebContentsFocused(render_widget_host);
4884 });
calamity7fe55ce2015-04-10 03:59:374885}
4886
Michael Thiessen896405db2017-07-20 17:52:324887void WebContentsImpl::NotifyWebContentsLostFocus(
4888 RenderWidgetHost* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:374889 OPTIONAL_TRACE_EVENT1("content",
4890 "WebContentsImpl::NotifyWebContentsLostFocus",
4891 "render_widget_host", render_widget_host);
Alexander Timin90c20c32020-08-12 15:28:324892 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4893 observer->OnWebContentsLostFocus(render_widget_host);
4894 });
zijiehe3bee08e22017-05-17 04:14:464895}
4896
Paul Meyer0c58c3712016-11-17 22:59:514897void WebContentsImpl::SystemDragEnded(RenderWidgetHost* source_rwh) {
Alexander Timin5fdeff22020-09-08 09:20:374898 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SystemDragEnded",
4899 "render_widget_host", source_rwh);
Paul Meyer0c58c3712016-11-17 22:59:514900 if (source_rwh)
4901 source_rwh->DragSourceSystemDragEnded();
Lei Zhang6410ec1a2019-01-31 21:38:584902 if (browser_plugin_embedder_)
[email protected]cf200a562013-05-03 16:24:294903 browser_plugin_embedder_->SystemDragEnded();
[email protected]7813bd72011-02-05 02:19:344904}
4905
[email protected]b172aee2012-04-10 17:05:264906void WebContentsImpl::SetClosedByUserGesture(bool value) {
Alexander Timin5fdeff22020-09-08 09:20:374907 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetClosedByUserGesture",
4908 "value", value);
[email protected]0bfbf882011-12-22 18:19:274909 closed_by_user_gesture_ = value;
4910}
4911
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414912bool WebContentsImpl::GetClosedByUserGesture() {
[email protected]0bfbf882011-12-22 18:19:274913 return closed_by_user_gesture_;
4914}
4915
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414916int WebContentsImpl::GetMinimumZoomPercent() {
[email protected]0bfbf882011-12-22 18:19:274917 return minimum_zoom_percent_;
4918}
4919
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414920int WebContentsImpl::GetMaximumZoomPercent() {
[email protected]0bfbf882011-12-22 18:19:274921 return maximum_zoom_percent_;
4922}
4923
Dave Tapuska8f7c3872020-02-07 01:16:384924void WebContentsImpl::SetPageScale(float scale_factor) {
Alexander Timin5fdeff22020-09-08 09:20:374925 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetPageScale",
4926 "scale_factor", scale_factor);
Dave Tapuska8f7c3872020-02-07 01:16:384927 GetMainFrame()->GetAssociatedLocalMainFrame()->SetScaleFactor(scale_factor);
ccameronb7c1d6c2015-03-09 17:08:244928}
4929
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414930gfx::Size WebContentsImpl::GetPreferredSize() {
Francois Doray24fc62c2017-12-11 17:27:334931 return IsBeingCaptured() ? preferred_size_for_capture_ : preferred_size_;
[email protected]bcd2815602012-01-14 18:17:234932}
4933
James Hollyerd5c9de462020-03-10 19:02:454934bool WebContentsImpl::GotResponseToLockMouseRequest(
4935 blink::mojom::PointerLockResult result) {
Alexander Timin5fdeff22020-09-08 09:20:374936 OPTIONAL_TRACE_EVENT0("content",
4937 "WebContentsImpl::GotResponseToLockMouseRequest");
lfgf0cd46e2017-01-04 00:05:234938 if (mouse_lock_widget_) {
4939 if (mouse_lock_widget_->delegate()->GetAsWebContents() != this) {
4940 return mouse_lock_widget_->delegate()
4941 ->GetAsWebContents()
James Hollyerd5c9de462020-03-10 19:02:454942 ->GotResponseToLockMouseRequest(result);
lfgf0cd46e2017-01-04 00:05:234943 }
lfgad8244352016-07-13 16:55:514944
James Hollyerd5c9de462020-03-10 19:02:454945 if (mouse_lock_widget_->GotResponseToLockMouseRequest(result))
lfgf0cd46e2017-01-04 00:05:234946 return true;
4947 }
4948
4949 for (WebContentsImpl* current = this; current;
4950 current = current->GetOuterWebContents()) {
4951 current->mouse_lock_widget_ = nullptr;
4952 }
4953
lfgbee1e0a2016-06-08 21:24:214954 return false;
[email protected]0bfbf882011-12-22 18:19:274955}
4956
James Hollyerd5c9de462020-03-10 19:02:454957void WebContentsImpl::GotLockMousePermissionResponse(bool allowed) {
4958 GotResponseToLockMouseRequest(
4959 allowed ? blink::mojom::PointerLockResult::kSuccess
4960 : blink::mojom::PointerLockResult::kPermissionDenied);
4961}
4962
Joe Downing13dd76b2018-04-09 18:32:154963bool WebContentsImpl::GotResponseToKeyboardLockRequest(bool allowed) {
Alexander Timin5fdeff22020-09-08 09:20:374964 OPTIONAL_TRACE_EVENT1("content",
4965 "WebContentsImpl::GotResponseToKeyboardLockRequest",
4966 "allowed", allowed);
4967
Joe Downing13dd76b2018-04-09 18:32:154968 if (!keyboard_lock_widget_)
4969 return false;
4970
4971 if (keyboard_lock_widget_->delegate()->GetAsWebContents() != this) {
4972 NOTREACHED();
4973 return false;
4974 }
4975
4976 // KeyboardLock is only supported when called by the top-level browsing
4977 // context and is not supported in embedded content scenarios.
4978 if (GetOuterWebContents())
4979 return false;
4980
4981 keyboard_lock_widget_->GotResponseToKeyboardLockRequest(allowed);
4982 return true;
4983}
4984
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414985bool WebContentsImpl::HasOpener() {
Ivan Kotenkov2c0d2bb32017-11-01 15:41:284986 return GetOpener() != nullptr;
[email protected]a0358d72012-03-09 14:06:504987}
4988
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414989RenderFrameHostImpl* WebContentsImpl::GetOpener() {
alexmose201c7cd2015-06-10 17:14:214990 FrameTreeNode* opener_ftn = frame_tree_.root()->opener();
lukasza6f8ac622017-06-06 03:10:204991 return opener_ftn ? opener_ftn->current_frame_host() : nullptr;
jochen55ff3502014-12-18 20:52:574992}
4993
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414994bool WebContentsImpl::HasOriginalOpener() {
Ivan Kotenkov2c0d2bb32017-11-01 15:41:284995 return GetOriginalOpener() != nullptr;
jochen6004a362017-02-04 00:11:404996}
4997
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414998RenderFrameHostImpl* WebContentsImpl::GetOriginalOpener() {
jochen6004a362017-02-04 00:11:404999 FrameTreeNode* opener_ftn = frame_tree_.root()->original_opener();
lukasza6f8ac622017-06-06 03:10:205000 return opener_ftn ? opener_ftn->current_frame_host() : nullptr;
jochen6004a362017-02-04 00:11:405001}
5002
[email protected]cb805452013-05-22 15:16:215003void WebContentsImpl::DidChooseColorInColorChooser(SkColor color) {
Alexander Timin5fdeff22020-09-08 09:20:375004 OPTIONAL_TRACE_EVENT1("content",
5005 "WebContentsImpl::DidChooseColorInColorChooser",
5006 "color", color);
Joel Hockey85b379d2017-12-11 10:42:135007 color_chooser_->DidChooseColorInColorChooser(color);
[email protected]da8543762012-03-20 08:52:205008}
5009
[email protected]cb805452013-05-22 15:16:215010void WebContentsImpl::DidEndColorChooser() {
Alexander Timin5fdeff22020-09-08 09:20:375011 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidEndColorChooser");
Joel Hockey85b379d2017-12-11 10:42:135012 color_chooser_.reset();
[email protected]da8543762012-03-20 08:52:205013}
5014
halton.huoca2eabd2015-07-06 08:17:405015int WebContentsImpl::DownloadImage(
5016 const GURL& url,
5017 bool is_favicon,
Fredrik Söderquistb2b39eb92019-11-18 16:16:505018 uint32_t preferred_size,
halton.huoca2eabd2015-07-06 08:17:405019 uint32_t max_bitmap_size,
5020 bool bypass_cache,
Avi Drissmana5a52dd2018-03-27 03:39:025021 WebContents::ImageDownloadCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:375022 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DownloadImage", "url",
5023 base::trace_event::ValueToString(url));
Danyao Wanga78f3dd22020-03-05 05:31:275024 return DownloadImageInFrame(GlobalFrameRoutingId(), url, is_favicon,
5025 preferred_size, max_bitmap_size, bypass_cache,
5026 std::move(callback));
5027}
5028
5029int WebContentsImpl::DownloadImageInFrame(
5030 const GlobalFrameRoutingId& initiator_frame_routing_id,
5031 const GURL& url,
5032 bool is_favicon,
5033 uint32_t preferred_size,
5034 uint32_t max_bitmap_size,
5035 bool bypass_cache,
5036 WebContents::ImageDownloadCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:375037 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DownloadImageInFrame");
amistry9f01b772015-07-29 01:54:555038 DCHECK_CURRENTLY_ON(BrowserThread::UI);
halton.huoca2eabd2015-07-06 08:17:405039 static int next_image_download_id = 0;
Danyao Wanga78f3dd22020-03-05 05:31:275040
5041 RenderFrameHostImpl* initiator_frame =
5042 initiator_frame_routing_id.child_id
5043 ? RenderFrameHostImpl::FromID(initiator_frame_routing_id)
5044 : GetMainFrame();
Julie Jeongeun Kimb1473572019-08-15 05:59:135045 const mojo::Remote<blink::mojom::ImageDownloader>& mojo_image_downloader =
Danyao Wanga78f3dd22020-03-05 05:31:275046 initiator_frame->GetMojoImageDownloader();
amistry9f01b772015-07-29 01:54:555047 const int download_id = ++next_image_download_id;
5048 if (!mojo_image_downloader) {
5049 // If the renderer process is dead (i.e. crash, or memory pressure on
5050 // Android), the downloader service will be invalid. Pre-Mojo, this would
Avi Drissmana5a52dd2018-03-27 03:39:025051 // hang the callback indefinitely since the IPC would be dropped. Now,
amistry9f01b772015-07-29 01:54:555052 // respond with a 400 HTTP error code to indicate that something went wrong.
Gabriel Charettee7cdc5cd2020-05-27 23:35:055053 GetUIThreadTaskRunner({})->PostTask(
5054 FROM_HERE,
tzike2aca992017-09-05 08:50:545055 base::BindOnce(&WebContentsImpl::OnDidDownloadImage,
Avi Drissmana5a52dd2018-03-27 03:39:025056 weak_factory_.GetWeakPtr(), std::move(callback),
5057 download_id, url, 400, std::vector<SkBitmap>(),
5058 std::vector<gfx::Size>()));
amistry9f01b772015-07-29 01:54:555059 return download_id;
5060 }
5061
halton.huoca2eabd2015-07-06 08:17:405062 mojo_image_downloader->DownloadImage(
Fredrik Söderquistb2b39eb92019-11-18 16:16:505063 url, is_favicon, preferred_size, max_bitmap_size, bypass_cache,
tzike2aca992017-09-05 08:50:545064 base::BindOnce(&WebContentsImpl::OnDidDownloadImage,
Avi Drissmana5a52dd2018-03-27 03:39:025065 weak_factory_.GetWeakPtr(), std::move(callback),
5066 download_id, url));
amistry9f01b772015-07-29 01:54:555067 return download_id;
[email protected]795c28972012-12-06 06:13:395068}
5069
[email protected]36ec24f2014-01-09 00:32:085070void WebContentsImpl::Find(int request_id,
5071 const base::string16& search_text,
Rakina Zata Amni3f77dff2018-09-08 16:19:435072 blink::mojom::FindOptionsPtr options) {
Alexander Timin5fdeff22020-09-08 09:20:375073 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Find");
thestig6057a6b22015-11-12 23:01:335074 // Cowardly refuse to search for no text.
5075 if (search_text.empty()) {
5076 NOTREACHED();
5077 return;
5078 }
5079
Rakina Zata Amni3f77dff2018-09-08 16:19:435080 GetOrCreateFindRequestManager()->Find(request_id, search_text,
5081 std::move(options));
[email protected]36ec24f2014-01-09 00:32:085082}
5083
5084void WebContentsImpl::StopFinding(StopFindAction action) {
Alexander Timin5fdeff22020-09-08 09:20:375085 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::StopFinding");
paulmeyerfeafc2d2017-04-25 21:46:405086 if (FindRequestManager* manager = GetFindRequestManager())
5087 manager->StopFinding(action);
[email protected]36ec24f2014-01-09 00:32:085088}
5089
Tommy Steimel18360512017-11-01 00:38:195090bool WebContentsImpl::WasEverAudible() {
5091 return was_ever_audible_;
5092}
5093
Avi Drissmana5a52dd2018-03-27 03:39:025094void WebContentsImpl::GetManifest(GetManifestCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:375095 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GetManifest");
Yuzu Saijofce18322020-05-14 05:02:095096 // TODO(yuzus, 1061899): Move this function to RenderFrameHostImpl.
5097 ManifestManagerHost* manifest_manager_host =
5098 ManifestManagerHost::GetOrCreateForCurrentDocument(GetMainFrame());
5099 manifest_manager_host->GetManifest(std::move(callback));
mlamouriefdca9d2014-09-16 16:55:405100}
5101
bokanece34a82016-01-28 19:49:465102void WebContentsImpl::ExitFullscreen(bool will_cause_resize) {
Alexander Timin5fdeff22020-09-08 09:20:375103 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ExitFullscreen");
mlamouri7a78d6fd2015-01-17 13:23:535104 // Clean up related state and initiate the fullscreen exit.
James Hollyerd5c9de462020-03-10 19:02:455105 GetRenderViewHost()->GetWidget()->RejectMouseLockOrUnlockIfNecessary(
5106 blink::mojom::PointerLockResult::kUserRejected);
bokanece34a82016-01-28 19:49:465107 ExitFullscreenMode(will_cause_resize);
mlamouri7a78d6fd2015-01-17 13:23:535108}
5109
Mike Wassermanb6bc0152020-08-25 22:46:205110base::ScopedClosureRunner WebContentsImpl::ForSecurityDropFullscreen(
5111 int64_t display_id) {
Alexander Timin5fdeff22020-09-08 09:20:375112 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ForSecurityDropFullscreen",
5113 "display_id", display_id);
Avi Drissman33972942020-06-19 14:16:015114 // Kick WebContentses that are "related" to this WebContents out of
5115 // fullscreen. This needs to be done with two passes, because it is simple to
5116 // walk _up_ the chain of openers and outer contents, but it not simple to
5117 // walk _down_ the chain.
5118
5119 // First, determine if any WebContents that is in fullscreen has this
5120 // WebContents as an upstream contents. Drop that WebContents out of
5121 // fullscreen if it does. This is theoretically quadratic-ish (fullscreen
5122 // contentses x each one's opener length) but neither of those is expected to
5123 // ever be a large number.
5124
Mike Wassermanb6bc0152020-08-25 22:46:205125 auto* screen = display::Screen::GetScreen();
5126
Avi Drissman33972942020-06-19 14:16:015127 auto fullscreen_set_copy = *FullscreenContentsSet(GetBrowserContext());
5128 for (auto* fullscreen_contents : fullscreen_set_copy) {
Avi Drissman97aef042020-06-30 21:04:485129 // Checking IsFullscreen() for tabs in the fullscreen set may seem
5130 // redundant, but teeeeechnically fullscreen is run by the delegate, and
5131 // it's possible that the delegate's notion of fullscreen may have changed
5132 // outside of WebContents's notice.
Mike Wassermanb6bc0152020-08-25 22:46:205133 if (fullscreen_contents->IsFullscreen() &&
5134 (display_id == display::kInvalidDisplayId || !screen ||
5135 display_id ==
5136 screen->GetDisplayNearestView(fullscreen_contents->GetNativeView())
5137 .id())) {
Avi Drissman33972942020-06-19 14:16:015138 auto opener_contentses = GetAllOpeningWebContents(fullscreen_contents);
5139 if (opener_contentses.count(this))
5140 fullscreen_contents->ExitFullscreen(true);
5141 }
5142 }
5143
5144 // Second, walk upstream from this WebContents, and drop the fullscreen of
5145 // all WebContentses that are in fullscreen. Block all the WebContentses in
5146 // the chain from entering fullscreen while the returned closure runner is
5147 // alive. It's OK that this set doesn't contain downstream WebContentses, as
5148 // any request to enter fullscreen will have the upstream of the WebContents
5149 // checked. (See CanEnterFullscreenMode().)
Avi Drissmanced52b62019-08-14 21:25:465150
Avi Drissman1a55a9d62020-03-10 18:56:455151 std::vector<base::WeakPtr<WebContentsImpl>> blocked_contentses;
5152
Avi Drissman33972942020-06-19 14:16:015153 for (auto* opener : GetAllOpeningWebContents(this)) {
Avi Drissman1a55a9d62020-03-10 18:56:455154 // Drop fullscreen if the WebContents is in it, and...
Mike Wassermanb6bc0152020-08-25 22:46:205155 if (opener->IsFullscreen() &&
5156 (display_id == display::kInvalidDisplayId || !screen ||
5157 display_id ==
5158 screen->GetDisplayNearestView(opener->GetNativeView()).id()))
Avi Drissman33972942020-06-19 14:16:015159 opener->ExitFullscreen(true);
Avi Drissmanced52b62019-08-14 21:25:465160
Avi Drissman1a55a9d62020-03-10 18:56:455161 // ...block the WebContents from entering fullscreen until further notice.
Avi Drissman33972942020-06-19 14:16:015162 ++opener->fullscreen_blocker_count_;
5163 blocked_contentses.push_back(opener->weak_factory_.GetWeakPtr());
Avi Drissmanced52b62019-08-14 21:25:465164 }
Avi Drissman1a55a9d62020-03-10 18:56:455165
5166 return base::ScopedClosureRunner(base::BindOnce(
5167 [](std::vector<base::WeakPtr<WebContentsImpl>> blocked_contentses) {
5168 for (base::WeakPtr<WebContentsImpl>& web_contents :
5169 blocked_contentses) {
5170 if (web_contents) {
5171 DCHECK_GT(web_contents->fullscreen_blocker_count_, 0);
5172 --web_contents->fullscreen_blocker_count_;
5173 }
5174 }
5175 },
5176 std::move(blocked_contentses)));
Avi Drissmanced52b62019-08-14 21:25:465177}
5178
mariakhomenko44bdc4732015-04-29 01:55:385179void WebContentsImpl::ResumeLoadingCreatedWebContents() {
Alexander Timin5fdeff22020-09-08 09:20:375180 OPTIONAL_TRACE_EVENT0("content",
5181 "WebContentsImpl::ResumeLoadingCreatedWebContents");
Nasko Oskov83a8cf92018-10-19 14:58:565182 if (delayed_load_url_params_.get()) {
5183 DCHECK(!delayed_open_url_params_);
5184 controller_.LoadURLWithParams(*delayed_load_url_params_.get());
5185 delayed_load_url_params_.reset(nullptr);
5186 return;
5187 }
5188
mariakhomenkoa4971c12015-07-21 19:04:375189 if (delayed_open_url_params_.get()) {
5190 OpenURL(*delayed_open_url_params_.get());
5191 delayed_open_url_params_.reset(nullptr);
5192 return;
5193 }
5194
mariakhomenko44bdc4732015-04-29 01:55:385195 // Resume blocked requests for both the RenderViewHost and RenderFrameHost.
5196 // TODO(brettw): It seems bogus to reach into here and initialize the host.
dfalcantarae6b7b46752015-07-10 18:14:165197 if (is_resume_pending_) {
5198 is_resume_pending_ = false;
avi0f1bbc9712015-11-17 02:58:135199 GetRenderViewHost()->GetWidget()->Init();
dfalcantarae6b7b46752015-07-10 18:14:165200 GetMainFrame()->Init();
5201 }
mariakhomenko44bdc4732015-04-29 01:55:385202}
5203
[email protected]b172aee2012-04-10 17:05:265204bool WebContentsImpl::FocusLocationBarByDefault() {
Alexander Timin5fdeff22020-09-08 09:20:375205 OPTIONAL_TRACE_EVENT0("content",
5206 "WebContentsImpl::FocusLocationBarByDefault");
Xiyuan Xia2a66b112018-12-06 15:52:165207 if (should_focus_location_bar_by_default_)
[email protected]0c9406632013-02-08 01:13:335208 return true;
Xiyuan Xia2a66b112018-12-06 15:52:165209
[email protected]0c9406632013-02-08 01:13:335210 return delegate_ && delegate_->ShouldFocusLocationBarByDefault(this);
[email protected]0bfbf882011-12-22 18:19:275211}
5212
Tommy C. Li8bb5bf42019-01-18 18:45:515213void WebContentsImpl::SetFocusToLocationBar() {
Alexander Timin5fdeff22020-09-08 09:20:375214 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetFocusToLocationBar");
[email protected]0bfbf882011-12-22 18:19:275215 if (delegate_)
Tommy C. Li8bb5bf42019-01-18 18:45:515216 delegate_->SetFocusToLocationBar();
[email protected]c40d6232011-03-25 00:16:215217}
5218
clamy0e119882015-07-31 16:12:335219void WebContentsImpl::DidStartNavigation(NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:485220 TRACE_EVENT1("navigation", "WebContentsImpl::DidStartNavigation",
5221 "navigation_handle", navigation_handle);
Alan Cutterab48fc02020-02-24 12:26:425222 if (navigation_handle->IsInMainFrame())
5223 favicon_urls_.clear();
Mounir Lamouri7b4a1f232019-12-23 16:32:105224
Alexander Timin90c20c32020-08-12 15:28:325225 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5226 observer->DidStartNavigation(navigation_handle);
5227 });
Xiyuan Xia2a66b112018-12-06 15:52:165228 if (navigation_handle->IsInMainFrame()) {
5229 // When the browser is started with about:blank as the startup URL, focus
5230 // the location bar (which will also select its contents) so people can
5231 // simply begin typing to navigate elsewhere.
5232 //
5233 // We need to be careful not to trigger this for anything other than the
5234 // startup navigation. In particular, if we allow an attacker to open a
5235 // popup to about:blank, then navigate, focusing the Omnibox will cause the
5236 // end of the new URL to be scrolled into view instead of the start,
5237 // allowing the attacker to spoof other URLs. The conditions checked here
5238 // are all aimed at ensuring no such attacker-controlled navigation can
5239 // trigger this.
5240 should_focus_location_bar_by_default_ =
5241 controller_.IsInitialNavigation() &&
5242 !navigation_handle->IsRendererInitiated() &&
5243 navigation_handle->GetURL() == url::kAboutBlankURL;
5244 }
clamy0e119882015-07-31 16:12:335245}
5246
5247void WebContentsImpl::DidRedirectNavigation(
5248 NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:485249 TRACE_EVENT1("navigation", "WebContentsImpl::DidRedirectNavigation",
5250 "navigation_handle", navigation_handle);
Alexander Timin90c20c32020-08-12 15:28:325251 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5252 observer->DidRedirectNavigation(navigation_handle);
5253 });
jam5f358e52017-02-13 16:37:035254 // Notify accessibility if this is a reload. This has to called on the
5255 // BrowserAccessibilityManager associated with the old RFHI.
5256 if (navigation_handle->GetReloadType() != ReloadType::NONE) {
Mohamed Abdelhalim95794962019-09-20 11:16:495257 NavigationRequest* request = NavigationRequest::From(navigation_handle);
jam5f358e52017-02-13 16:37:035258 BrowserAccessibilityManager* manager =
Mohamed Abdelhalim95794962019-09-20 11:16:495259 request->frame_tree_node()
jam5f358e52017-02-13 16:37:035260 ->current_frame_host()
5261 ->browser_accessibility_manager();
5262 if (manager)
5263 manager->UserIsReloading();
5264 }
clamy0e119882015-07-31 16:12:335265}
5266
clamyefca29e2015-09-17 00:22:115267void WebContentsImpl::ReadyToCommitNavigation(
5268 NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:485269 TRACE_EVENT1("navigation", "WebContentsImpl::ReadyToCommitNavigation",
5270 "navigation_handle", navigation_handle);
Alexander Timin90c20c32020-08-12 15:28:325271 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5272 observer->ReadyToCommitNavigation(navigation_handle);
5273 });
Kenneth Russell954ed9ce2018-04-12 23:07:015274 // If any domains are blocked from accessing 3D APIs because they may
5275 // have caused the GPU to reset recently, unblock them here if the user
5276 // initiated this navigation. This implies that the user was involved in
5277 // the decision to navigate, so there's no concern about
5278 // denial-of-service issues. Want to do this as early as
5279 // possible to avoid race conditions with pages attempting to access
5280 // WebGL early on.
5281 //
5282 // TODO(crbug.com/617904): currently navigations initiated by the browser
5283 // (reload button, reload menu option, pressing return in the Omnibox)
5284 // return false from HasUserGesture(). If or when that is addressed,
5285 // remove the check for IsRendererInitiated() below.
5286 //
5287 // TODO(crbug.com/832180): HasUserGesture comes from the renderer
5288 // process and isn't validated. Until it is, don't trust it.
5289 if (!navigation_handle->IsRendererInitiated()) {
5290 GpuDataManagerImpl::GetInstance()->UnblockDomainFrom3DAPIs(
5291 navigation_handle->GetURL());
5292 }
5293
John Abd-El-Malekfde08e6da2017-12-05 04:06:245294 if (navigation_handle->IsSameDocument())
5295 return;
5296
Livvie Lin139bf442018-08-10 00:18:545297 // SSLInfo is not needed on subframe navigations since the main-frame
5298 // certificate is the only one that can be inspected (using the info
5299 // bubble) without refreshing the page with DevTools open.
Carlos ILaed1e7b2019-03-12 19:27:215300 // We don't call DidStartResourceResponse on net errors, since that results on
5301 // existing cert exceptions being revoked, which leads to weird behavior with
5302 // committed interstitials or while offline. We only need the error check for
5303 // the main frame case because unlike this method, SubresourceResponseStarted
5304 // does not get called on network errors.
5305 if (navigation_handle->IsInMainFrame() &&
5306 navigation_handle->GetNetErrorCode() == net::OK) {
Livvie Lin139bf442018-08-10 00:18:545307 controller_.ssl_manager()->DidStartResourceResponse(
Lukasz Anforowiczd334bba2020-02-10 23:32:555308 navigation_handle->GetURL(),
Camille Lamy62b826012019-02-26 09:15:475309 navigation_handle->GetSSLInfo().has_value()
5310 ? net::IsCertStatusError(
5311 navigation_handle->GetSSLInfo()->cert_status)
5312 : false);
5313 }
John Abd-El-Malekfde08e6da2017-12-05 04:06:245314
Bruce Dawsone1c5c842020-09-15 02:09:145315 // LoadingStateChanged must be called last in case it triggers deletion of
5316 // |this| due to recursive message pumps.
John Abd-El-Malekfde08e6da2017-12-05 04:06:245317 SetNotWaitingForResponse();
clamyefca29e2015-09-17 00:22:115318}
5319
clamy0e119882015-07-31 16:12:335320void WebContentsImpl::DidFinishNavigation(NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:485321 TRACE_EVENT1("navigation", "WebContentsImpl::DidFinishNavigation",
5322 "navigation_handle", navigation_handle);
Steven Holte38041342018-06-22 22:00:575323
Alexander Timin90c20c32020-08-12 15:28:325324 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5325 observer->DidFinishNavigation(navigation_handle);
5326 });
Becca Hughesd11d6502018-07-31 17:01:285327 if (display_cutout_host_impl_)
5328 display_cutout_host_impl_->DidFinishNavigation(navigation_handle);
5329
jam5f358e52017-02-13 16:37:035330 if (navigation_handle->HasCommitted()) {
Ian Prestcdd843d2020-01-28 18:59:585331 // TODO(domfarolino, dmazzoni): Do this using WebContentsObserver. See
5332 // https://crbug.com/981271.
5333 BrowserAccessibilityManager* manager =
5334 static_cast<RenderFrameHostImpl*>(
5335 navigation_handle->GetRenderFrameHost())
5336 ->browser_accessibility_manager();
5337 if (manager) {
5338 if (navigation_handle->IsErrorPage()) {
5339 manager->NavigationFailed();
5340 } else {
5341 manager->NavigationSucceeded();
5342 }
5343 }
5344
Yue Ru Sun979c4b162019-11-06 16:11:045345 if (navigation_handle->IsInMainFrame()) {
5346 last_committed_source_id_including_same_document_ =
Steven Holte38041342018-06-22 22:00:575347 ukm::ConvertToSourceId(navigation_handle->GetNavigationId(),
5348 ukm::SourceIdType::NAVIGATION_ID);
Yue Ru Sun979c4b162019-11-06 16:11:045349
5350 if (!navigation_handle->IsSameDocument()) {
5351 was_ever_audible_ = false;
Yue Ru Sun979c4b162019-11-06 16:11:045352 }
Tommy Steimel18360512017-11-01 00:38:195353 }
Lan Weif81c6e7c2020-02-12 16:46:095354
5355 if (!navigation_handle->IsSameDocument())
5356 last_screen_orientation_change_time_ = base::TimeTicks();
dmazzonibf8cec42015-02-08 08:28:085357 }
Xiyuan Xia2a66b112018-12-06 15:52:165358
5359 // If we didn't end up on about:blank after setting this in DidStartNavigation
5360 // then don't focus the location bar.
5361 if (should_focus_location_bar_by_default_ &&
5362 navigation_handle->GetURL() != url::kAboutBlankURL) {
5363 should_focus_location_bar_by_default_ = false;
5364 }
yilkal796e89e2019-10-02 23:58:285365
yilkal172da772019-11-06 22:49:075366 if (navigation_handle->IsInMainFrame() && first_navigation_completed_)
5367 RecordMaxFrameCountUMA(max_loaded_frame_count_);
yilkal796e89e2019-10-02 23:58:285368
yilkal172da772019-11-06 22:49:075369 // If navigation has successfully finished in the main frame, set
5370 // |first_navigation_completed_| to true so that we will record
5371 // |max_loaded_frame_count_| above when future main frame navigations finish.
5372 if (navigation_handle->IsInMainFrame() && !navigation_handle->IsErrorPage()) {
5373 first_navigation_completed_ = true;
5374
5375 // Navigation has completed in main frame. Reset |max_loaded_frame_count_|.
5376 // |max_loaded_frame_count_| is not necessarily 1 if the navigation was
5377 // served from BackForwardCache.
5378 max_loaded_frame_count_ =
5379 GetMainFrame()->frame_tree_node()->GetFrameTreeSize();
yilkal796e89e2019-10-02 23:58:285380 }
Rakina Zata Amni347b70902020-07-22 10:49:045381
5382 if (web_preferences_) {
5383 // Update the WebPreferences for this WebContents that depends on changes
5384 // that might occur during navigation. This will only update the preferences
5385 // that needs to be updated (and won't cause an update/overwrite preferences
5386 // that needs to stay the same after navigations).
5387 bool value_changed_due_to_override =
5388 GetContentClient()->browser()->OverrideWebPreferencesAfterNavigation(
5389 this, web_preferences_.get());
5390 // We need to update the WebPreferences value on the renderer if the value
5391 // is changed due to the override above, or if the navigation is served from
5392 // the back-forward cache, because the WebPreferences value stored in the
5393 // renderer might be stale (because we don't send WebPreferences updates to
5394 // bfcached renderers).
5395 // TODO(rakina): Maybe handle the back-forward cache case in
5396 // ReadyToCommitNavigation instead?
5397 if (value_changed_due_to_override ||
5398 NavigationRequest::From(navigation_handle)
5399 ->IsServedFromBackForwardCache()) {
5400 SetWebPreferences(*web_preferences_.get());
5401 }
5402 }
[email protected]400992b2012-06-14 00:03:545403}
5404
[email protected]b80624c2014-02-09 02:46:555405void WebContentsImpl::DidFailLoadWithError(
5406 RenderFrameHostImpl* render_frame_host,
[email protected]b80624c2014-02-09 02:46:555407 const GURL& url,
Dave Tapuska924ef3c2020-01-22 18:20:595408 int error_code) {
Alexander Timin5fdeff22020-09-08 09:20:375409 TRACE_EVENT2("content,navigation", "WebContentsImpl::DidFailLoadWithError",
5410 "render_frame_host",
5411 base::trace_event::ToTracedValue(render_frame_host), "url",
5412 base::trace_event::ValueToString(url));
Alexander Timin90c20c32020-08-12 15:28:325413 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5414 observer->DidFailLoad(render_frame_host, url, error_code);
5415 });
[email protected]b80624c2014-02-09 02:46:555416}
5417
[email protected]52913802013-12-10 05:52:185418void WebContentsImpl::NotifyChangedNavigationState(
5419 InvalidateTypes changed_flags) {
5420 NotifyNavigationStateChanged(changed_flags);
5421}
5422
lukasza1d025732016-09-28 21:36:085423bool WebContentsImpl::ShouldTransferNavigation(bool is_main_frame_navigation) {
Alexander Timin5fdeff22020-09-08 09:20:375424 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ShouldTransferNavigation",
5425 "is_main_frame_navigation", is_main_frame_navigation);
creis29460272015-12-16 04:38:225426 if (!delegate_)
5427 return true;
lukasza1d025732016-09-28 21:36:085428 return delegate_->ShouldTransferNavigation(is_main_frame_navigation);
creis29460272015-12-16 04:38:225429}
5430
[email protected]aa62afd2014-04-22 19:22:465431bool WebContentsImpl::ShouldPreserveAbortedURLs() {
Alexander Timin5fdeff22020-09-08 09:20:375432 OPTIONAL_TRACE_EVENT0("content",
5433 "WebContentsImpl::ShouldPreserveAbortedURLs");
[email protected]aa62afd2014-04-22 19:22:465434 if (!delegate_)
5435 return false;
5436 return delegate_->ShouldPreserveAbortedURLs(this);
5437}
5438
[email protected]0d0f4c492014-04-02 06:42:575439void WebContentsImpl::DidNavigateMainFramePreCommit(
[email protected]5cfbddc2014-06-23 23:52:235440 bool navigation_is_within_page) {
Alexander Timin5fdeff22020-09-08 09:20:375441 TRACE_EVENT1("content,navigation",
5442 "WebContentsImpl::DidNavigateMainFramePreCommit",
5443 "navigation_is_within_page", navigation_is_within_page);
[email protected]0d0f4c492014-04-02 06:42:575444 // Ensure fullscreen mode is exited before committing the navigation to a
5445 // different page. The next page will not start out assuming it is in
5446 // fullscreen mode.
[email protected]5cfbddc2014-06-23 23:52:235447 if (navigation_is_within_page) {
[email protected]dfc39cb2014-04-09 22:58:195448 // No page change? Then, the renderer and browser can remain in fullscreen.
[email protected]0d0f4c492014-04-02 06:42:575449 return;
5450 }
Avi Drissman97aef042020-06-30 21:04:485451 if (IsFullscreen())
bokanece34a82016-01-28 19:49:465452 ExitFullscreen(false);
Avi Drissman97aef042020-06-30 21:04:485453 DCHECK(!IsFullscreen());
Joe Downingc1a57efe2018-05-09 18:23:545454
5455 // Clean up keyboard lock state when navigating.
5456 CancelKeyboardLock(keyboard_lock_widget_);
[email protected]0d0f4c492014-04-02 06:42:575457}
5458
[email protected]37567b432014-02-12 01:12:225459void WebContentsImpl::DidNavigateMainFramePostCommit(
sky8b00392d2015-01-10 00:30:285460 RenderFrameHostImpl* render_frame_host,
[email protected]37567b432014-02-12 01:12:225461 const LoadCommittedDetails& details,
5462 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
Alexander Timin5fdeff22020-09-08 09:20:375463 OPTIONAL_TRACE_EVENT1(
5464 "content,navigation", "WebContentsImpl::DidNavigateMainFramePostCommit",
5465 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host));
[email protected]37567b432014-02-12 01:12:225466 if (details.is_navigation_to_different_page()) {
5467 // Clear the status bubble. This is a workaround for a bug where WebKit
5468 // doesn't let us know that the cursor left an element during a
5469 // transition (this is also why the mouse cursor remains as a hand after
5470 // clicking on a link); see bugs 1184641 and 980803. We don't want to
5471 // clear the bubble when a user navigates to a named anchor in the same
5472 // page.
Lukasz Anforowiczfd707142018-02-07 19:46:135473 ClearTargetURL();
lanwei9d343ad22015-02-11 01:46:005474
5475 RenderWidgetHostViewBase* rwhvb =
5476 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
5477 if (rwhvb)
5478 rwhvb->OnDidNavigateMainFrameToNewPage();
[email protected]37567b432014-02-12 01:12:225479 }
5480
[email protected]e85165c642014-06-10 14:34:315481 if (delegate_)
[email protected]37567b432014-02-12 01:12:225482 delegate_->DidNavigateMainFramePostCommit(this);
[email protected]e85165c642014-06-10 14:34:315483 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
Shivani Sharma985474f2019-05-23 21:36:475484
Alan Cutterd73a15d92020-08-21 07:12:455485 // The following events will not fire again if the page is restored from the
5486 // BackForwardCache. So fire them ourselves if needed.
Carlos Caballero91fffb22019-10-29 15:24:305487 if (details.is_navigation_to_different_page() &&
5488 GetRenderViewHost()->did_first_visually_non_empty_paint()) {
Carlos Caballero91fffb22019-10-29 15:24:305489 DidFirstVisuallyNonEmptyPaint(GetRenderViewHost());
5490 }
Alan Cutterd73a15d92020-08-21 07:12:455491 if (GetRenderViewHost()->theme_color() != last_sent_theme_color_)
Carlos Caballero1215f882019-10-29 15:58:435492 OnThemeColorChanged(GetRenderViewHost());
Alan Cutterd73a15d92020-08-21 07:12:455493 if (GetRenderViewHost()->background_color() != last_sent_background_color_)
5494 OnBackgroundColorChanged(GetRenderViewHost());
[email protected]37567b432014-02-12 01:12:225495}
5496
5497void WebContentsImpl::DidNavigateAnyFramePostCommit(
5498 RenderFrameHostImpl* render_frame_host,
5499 const LoadCommittedDetails& details,
5500 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
Alexander Timin5fdeff22020-09-08 09:20:375501 OPTIONAL_TRACE_EVENT1(
5502 "content,navigation", "WebContentsImpl::DidNavigateAnyFramePostCommit",
5503 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host));
[email protected]b4c84012014-04-28 19:51:105504 // Now that something has committed, we don't need to track whether the
5505 // initial page has been accessed.
5506 has_accessed_initial_document_ = false;
5507
[email protected]37567b432014-02-12 01:12:225508 // If we navigate off the page, close all JavaScript dialogs.
eugenebutee08663a2017-04-27 17:43:125509 if (!details.is_same_document)
creis89a0f782015-05-27 16:13:175510 CancelActiveAndPendingDialogs();
[email protected]37567b432014-02-12 01:12:225511
avid53461d2016-02-25 17:15:045512 // If this is a user-initiated navigation, start allowing JavaScript dialogs
5513 // again.
avi5d3b8692016-10-12 22:00:465514 if (params.gesture == NavigationGestureUser && dialog_manager_) {
avi6879fcf2017-01-21 05:27:535515 dialog_manager_->CancelDialogs(this, /*reset_state=*/true);
avi5d3b8692016-10-12 22:00:465516 }
[email protected]37567b432014-02-12 01:12:225517}
5518
[email protected]277857a2014-06-03 10:38:015519bool WebContentsImpl::CanOverscrollContent() const {
Alexander Timin5fdeff22020-09-08 09:20:375520 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::CanOverscrollContent");
[email protected]e85165c642014-06-10 14:34:315521 // Disable overscroll when touch emulation is on. See crbug.com/369938.
[email protected]34ff1cfc2014-08-20 06:16:055522 if (force_disable_overscroll_content_)
[email protected]e85165c642014-06-10 14:34:315523 return false;
5524
[email protected]37567b432014-02-12 01:12:225525 if (delegate_)
5526 return delegate_->CanOverscrollContent();
5527
5528 return false;
5529}
5530
Carlos Caballero1215f882019-10-29 15:58:435531void WebContentsImpl::OnThemeColorChanged(RenderViewHostImpl* source) {
Alexander Timin5fdeff22020-09-08 09:20:375532 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnThemeColorChanged",
5533 "render_view_host", source);
Carlos Caballero1215f882019-10-29 15:58:435534 if (source->did_first_visually_non_empty_paint() &&
5535 last_sent_theme_color_ != source->theme_color()) {
Alexander Timin90c20c32020-08-12 15:28:325536 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5537 observer->DidChangeThemeColor();
5538 });
Matt Jones36fc2882020-08-25 14:25:125539 last_sent_theme_color_ = source->theme_color();
peter90afaba2015-06-01 12:05:295540 }
[email protected]e7104762014-06-20 19:17:255541}
5542
Alan Cutterd73a15d92020-08-21 07:12:455543void WebContentsImpl::OnBackgroundColorChanged(RenderViewHostImpl* source) {
5544 if (source->did_first_visually_non_empty_paint() &&
5545 last_sent_background_color_ != source->background_color()) {
5546 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5547 observer->OnBackgroundColorChanged();
5548 });
5549 last_sent_background_color_ = source->background_color();
5550 }
5551}
5552
Gyuyoung Kim1905f7c2020-05-02 00:00:245553void WebContentsImpl::DidLoadResourceFromMemoryCache(
nicka0ac8382016-12-15 23:59:235554 RenderFrameHostImpl* source,
[email protected]724159a2010-12-30 01:11:185555 const GURL& url,
[email protected]70435962011-08-02 20:13:285556 const std::string& http_method,
[email protected]6d6cfb3a2012-05-23 22:53:185557 const std::string& mime_type,
Kinuko Yasuda433f710a2020-02-14 02:11:585558 network::mojom::RequestDestination request_destination) {
Alexander Timin5fdeff22020-09-08 09:20:375559 OPTIONAL_TRACE_EVENT2(
5560 "content", "WebContentsImpl::DidLoadResourceFromMemoryCache",
5561 "render_frame_host", base::trace_event::ToTracedValue(source), "url",
5562 base::trace_event::ValueToString(url));
Alexander Timin90c20c32020-08-12 15:28:325563 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5564 observer->DidLoadResourceFromMemoryCache(url, mime_type,
5565 request_destination);
5566 });
[email protected]b0f724c2013-09-05 04:21:135567
Steven Bingler674fb0822018-12-12 18:04:525568 if (url.is_valid() && url.SchemeIsHTTPOrHTTPS()) {
nicka0ac8382016-12-15 23:59:235569 StoragePartition* partition = source->GetProcess()->GetStoragePartition();
John Abd-El-Malekf4fe9d82019-07-31 04:05:595570 partition->GetNetworkContext()->NotifyExternalCacheHit(
Matt Menke2a33dee2019-12-02 17:01:545571 url, http_method, source->GetNetworkIsolationKey());
[email protected]8bfc8272013-09-09 20:10:535572 }
[email protected]724159a2010-12-30 01:11:185573}
5574
carloskd9d97942017-02-16 08:58:095575void WebContentsImpl::DidDisplayInsecureContent() {
Alexander Timin5fdeff22020-09-08 09:20:375576 OPTIONAL_TRACE_EVENT0("content",
5577 "WebContentsImpl::DidDisplayInsecureContent");
estarkc2273502016-10-12 22:03:025578 controller_.ssl_manager()->DidDisplayMixedContent();
[email protected]724159a2010-12-30 01:11:185579}
5580
Dave Tapuskaa657d872019-10-21 20:23:215581void WebContentsImpl::DidContainInsecureFormAction() {
Alexander Timin5fdeff22020-09-08 09:20:375582 OPTIONAL_TRACE_EVENT0("content",
5583 "WebContentsImpl::DidContainInsecureFormAction");
elawrenceb2ac2a232017-03-27 21:46:255584 controller_.ssl_manager()->DidContainInsecureFormAction();
5585}
5586
Julie Jeongeun Kim0b103492020-01-29 05:30:515587void WebContentsImpl::DocumentAvailableInMainFrame() {
Alexander Timin5fdeff22020-09-08 09:20:375588 OPTIONAL_TRACE_EVENT0("content",
5589 "WebContentsImpl::DocumentAvailableInMainFrame");
Alexander Timin90c20c32020-08-12 15:28:325590 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5591 observer->DocumentAvailableInMainFrame();
5592 });
Julie Jeongeun Kim0b103492020-01-29 05:30:515593}
5594
nicka0ac8382016-12-15 23:59:235595void WebContentsImpl::OnDidRunInsecureContent(RenderFrameHostImpl* source,
5596 const GURL& security_origin,
estark910b4572015-12-09 20:55:415597 const GURL& target_url) {
Alexander Timin5fdeff22020-09-08 09:20:375598 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnDidRunInsecureContent",
5599 "render_frame_host",
5600 base::trace_event::ToTracedValue(source));
nicka0ac8382016-12-15 23:59:235601 // TODO(nick, estark): Should we call FilterURL using |source|'s process on
5602 // these parameters? |target_url| seems unused, except for a log message. And
5603 // |security_origin| might be replaceable with the origin of the main frame.
carloskd9d97942017-02-16 08:58:095604 DidRunInsecureContent(security_origin, target_url);
5605}
5606
5607void WebContentsImpl::DidRunInsecureContent(const GURL& security_origin,
5608 const GURL& target_url) {
Alexander Timin5fdeff22020-09-08 09:20:375609 OPTIONAL_TRACE_EVENT2(
5610 "content", "WebContentsImpl::DidRunInsecureContent", "security_origin",
5611 base::trace_event::ValueToString(security_origin), "target_url",
5612 base::trace_event::ValueToString(target_url));
[email protected]9450c462013-11-23 01:22:585613 LOG(WARNING) << security_origin << " ran insecure content from "
5614 << target_url.possibly_invalid_spec();
[email protected]e6e30ac2014-01-13 21:24:395615 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
estark910b4572015-12-09 20:55:415616 if (base::EndsWith(security_origin.spec(), kDotGoogleDotCom,
brettwa7ff1b292015-07-16 17:49:295617 base::CompareCase::INSENSITIVE_ASCII))
[email protected]e6e30ac2014-01-13 21:24:395618 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
estarkc2273502016-10-12 22:03:025619 controller_.ssl_manager()->DidRunMixedContent(security_origin);
[email protected]724159a2010-12-30 01:11:185620}
5621
carloskd9d97942017-02-16 08:58:095622void WebContentsImpl::PassiveInsecureContentFound(const GURL& resource_url) {
Alexander Timin5fdeff22020-09-08 09:20:375623 OPTIONAL_TRACE_EVENT1(
5624 "content", "WebContentsImpl::PassiveInsecureContentFound", "resource_url",
5625 base::trace_event::ValueToString(resource_url));
Sergey Kuznetsov3ebc01b2018-02-01 04:57:365626 if (delegate_) {
5627 delegate_->PassiveInsecureContentFound(resource_url);
5628 }
carloskd9d97942017-02-16 08:58:095629}
5630
5631bool WebContentsImpl::ShouldAllowRunningInsecureContent(
carloskd9d97942017-02-16 08:58:095632 bool allowed_per_prefs,
5633 const url::Origin& origin,
5634 const GURL& resource_url) {
Alexander Timin5fdeff22020-09-08 09:20:375635 OPTIONAL_TRACE_EVENT0("content",
5636 "WebContentsImpl::ShouldAllowRunningInsecureContent");
Sergey Kuznetsov3ebc01b2018-02-01 04:57:365637 if (delegate_) {
Carlos IL29294a62020-05-15 00:21:165638 return delegate_->ShouldAllowRunningInsecureContent(this, allowed_per_prefs,
5639 origin, resource_url);
Sergey Kuznetsov3ebc01b2018-02-01 04:57:365640 }
5641
5642 return allowed_per_prefs;
carloskd9d97942017-02-16 08:58:095643}
5644
Lukasz Anforowicze1b954d92017-10-30 21:28:065645void WebContentsImpl::ViewSource(RenderFrameHostImpl* frame) {
Alexander Timin5fdeff22020-09-08 09:20:375646 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ViewSource",
5647 "render_frame_host",
5648 base::trace_event::ToTracedValue(frame));
Lukasz Anforowicze1b954d92017-10-30 21:28:065649 DCHECK_EQ(this, WebContents::FromRenderFrameHost(frame));
5650
5651 // Don't do anything if there is no |delegate_| that could accept and show the
5652 // new WebContents containing the view-source.
5653 if (!delegate_)
5654 return;
5655
5656 // Use the last committed entry, since the pending entry hasn't loaded yet and
5657 // won't be copied into the cloned tab.
5658 NavigationEntryImpl* last_committed_entry =
Fergal Daly09d6c762020-05-29 02:05:185659 GetController().GetLastCommittedEntry();
Lukasz Anforowicze1b954d92017-10-30 21:28:065660 if (!last_committed_entry)
5661 return;
5662
5663 FrameNavigationEntry* frame_entry =
5664 last_committed_entry->GetFrameEntry(frame->frame_tree_node());
5665 if (!frame_entry)
5666 return;
5667
5668 // Any new WebContents opened while this WebContents is in fullscreen can be
5669 // used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:455670 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
5671 // The new view source contents will be independent of this contents, so
5672 // release the fullscreen block.
5673 fullscreen_block.RunAndReset();
Lukasz Anforowicze1b954d92017-10-30 21:28:065674
5675 // We intentionally don't share the SiteInstance with the original frame so
5676 // that view source has a consistent process model and always ends up in a new
5677 // process (https://crbug.com/699493).
5678 scoped_refptr<SiteInstanceImpl> site_instance_for_view_source = nullptr;
Lukasz Anforowicz435bcb582019-07-12 20:50:065679 // Referrer and initiator are not important, because view-source should not
5680 // hit the network, but should be served from the cache instead.
Lukasz Anforowicze1b954d92017-10-30 21:28:065681 Referrer referrer_for_view_source;
Lukasz Anforowicz435bcb582019-07-12 20:50:065682 base::Optional<url::Origin> initiator_for_view_source = base::nullopt;
Lukasz Anforowicze1b954d92017-10-30 21:28:065683 // Do not restore title, derive it from the url.
5684 base::string16 title_for_view_source;
5685 auto navigation_entry = std::make_unique<NavigationEntryImpl>(
5686 site_instance_for_view_source, frame_entry->url(),
Lukasz Anforowicz435bcb582019-07-12 20:50:065687 referrer_for_view_source, initiator_for_view_source,
5688 title_for_view_source, ui::PAGE_TRANSITION_LINK,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:095689 /* is_renderer_initiated = */ false,
5690 /* blob_url_loader_factory = */ nullptr);
Joel Hockey891e88062020-04-30 05:38:445691 const GURL url(content::kViewSourceScheme + std::string(":") +
5692 frame_entry->url().spec());
5693 navigation_entry->SetVirtualURL(url);
Matt Menkea56c5992020-04-10 20:53:565694 navigation_entry->set_isolation_info(
5695 frame->GetIsolationInfoForSubresources());
Yao Xiaof68f57d2019-10-03 04:20:055696
Lukasz Anforowicze1b954d92017-10-30 21:28:065697 // Do not restore scroller position.
5698 // TODO(creis, lukasza, arthursonzogni): Do not reuse the original PageState,
5699 // but start from a new one and only copy the needed data.
5700 const PageState& new_page_state =
5701 frame_entry->page_state().RemoveScrollOffset();
5702
5703 scoped_refptr<FrameNavigationEntry> new_frame_entry =
5704 navigation_entry->root_node()->frame_entry;
5705 new_frame_entry->set_method(frame_entry->method());
5706 new_frame_entry->SetPageState(new_page_state);
5707
5708 // Create a new WebContents, which is used to display the source code.
erikchenbee5c9622018-04-27 19:30:255709 std::unique_ptr<WebContents> view_source_contents =
Erik Chenbb8e738e2018-04-28 14:10:435710 Create(CreateParams(GetBrowserContext()));
Lukasz Anforowicze1b954d92017-10-30 21:28:065711
5712 // Restore the previously created NavigationEntry.
5713 std::vector<std::unique_ptr<NavigationEntry>> navigation_entries;
5714 navigation_entries.push_back(std::move(navigation_entry));
5715 view_source_contents->GetController().Restore(0, RestoreType::CURRENT_SESSION,
5716 &navigation_entries);
5717
5718 // Add |view_source_contents| as a new tab.
5719 gfx::Rect initial_rect;
5720 constexpr bool kUserGesture = true;
5721 bool ignored_was_blocked;
Joel Hockey891e88062020-04-30 05:38:445722 delegate_->AddNewContents(this, std::move(view_source_contents), url,
Lukasz Anforowicze1b954d92017-10-30 21:28:065723 WindowOpenDisposition::NEW_FOREGROUND_TAB,
5724 initial_rect, kUserGesture, &ignored_was_blocked);
5725 // Note that the |delegate_| could have deleted |view_source_contents| during
5726 // AddNewContents method call.
5727}
5728
Lukasz Anforowiczd334bba2020-02-10 23:32:555729void WebContentsImpl::SubresourceResponseStarted(const GURL& url,
5730 net::CertStatus cert_status) {
Alexander Timin5fdeff22020-09-08 09:20:375731 OPTIONAL_TRACE_EVENT1("content",
5732 "WebContentsImpl::SubresourceResponseStarted", "url",
5733 base::trace_event::ValueToString(url));
Lukasz Anforowiczd334bba2020-02-10 23:32:555734 controller_.ssl_manager()->DidStartResourceResponse(url, cert_status);
Jay Civellid5904f02018-03-23 19:43:575735 SetNotWaitingForResponse();
5736}
5737
Jay Civelli116683f2018-03-27 19:56:235738void WebContentsImpl::ResourceLoadComplete(
Jay Civelli52a63302018-04-30 22:39:555739 RenderFrameHost* render_frame_host,
Clark DuVall36164bd2018-08-09 22:49:085740 const GlobalRequestID& request_id,
Minggang Wangee5af392020-02-05 02:55:285741 blink::mojom::ResourceLoadInfoPtr resource_load_info) {
Alexander Timin5fdeff22020-09-08 09:20:375742 OPTIONAL_TRACE_EVENT2(
5743 "content", "WebContentsImpl::ResourceLoadComplete", "render_frame_host",
5744 base::trace_event::ToTracedValue(render_frame_host), "request_id",
5745 base::trace_event::TracedValue::Build(
5746 {{"child_id", request_id.child_id},
5747 {"request_id", request_id.request_id}}));
Alexander Timin90c20c32020-08-12 15:28:325748 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5749 observer->ResourceLoadComplete(render_frame_host, request_id,
5750 *resource_load_info);
5751 });
John Abd-El-Malekd4882642017-12-04 21:45:195752}
5753
Gyuyoung Kim1ac4ca782020-09-11 03:32:515754const blink::web_pref::WebPreferences&
5755WebContentsImpl::GetOrCreateWebPreferences() {
Alexander Timin5fdeff22020-09-08 09:20:375756 OPTIONAL_TRACE_EVENT0("content",
5757 "WebContentsImpl::GetOrCreateWebPreferences");
Rakina Zata Amni347b70902020-07-22 10:49:045758 // Compute WebPreferences based on the current state if it's null.
5759 if (!web_preferences_)
Rakina Zata Amni4029b6d2020-07-28 02:36:205760 OnWebPreferencesChanged();
Rakina Zata Amni347b70902020-07-22 10:49:045761 return *web_preferences_.get();
5762}
5763
5764bool WebContentsImpl::IsWebPreferencesSet() const {
5765 return web_preferences_.get();
5766}
5767
Gyuyoung Kim1ac4ca782020-09-11 03:32:515768void WebContentsImpl::SetWebPreferences(
5769 const blink::web_pref::WebPreferences& prefs) {
Alexander Timin5fdeff22020-09-08 09:20:375770 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetWebPreferences");
Gyuyoung Kim1ac4ca782020-09-11 03:32:515771 web_preferences_ = std::make_unique<blink::web_pref::WebPreferences>(prefs);
Rakina Zata Amni347b70902020-07-22 10:49:045772 // Get all the RenderViewHosts (except the ones for currently back-forward
5773 // cached pages), and make them send the current WebPreferences
5774 // to the renderer. WebPreferences updates for back-forward cached pages will
5775 // be sent when we restore those pages from the back-forward cache.
5776 for (auto& rvh : frame_tree_.render_view_hosts()) {
5777 rvh.second->SendWebPreferencesToRenderer();
5778 }
5779}
5780
5781void WebContentsImpl::RecomputeWebPreferencesSlow() {
Alexander Timin5fdeff22020-09-08 09:20:375782 OPTIONAL_TRACE_EVENT0("content",
5783 "WebContentsImpl::RecomputeWebPreferencesSlow");
Rakina Zata Amni4029b6d2020-07-28 02:36:205784 // OnWebPreferencesChanged is a no-op when this is true.
5785 if (updating_web_preferences_)
5786 return;
Rakina Zata Amni347b70902020-07-22 10:49:045787 // Resets |web_preferences_| so that we won't have any cached value for slow
5788 // attributes (which won't get recomputed if we have pre-existing values for
5789 // them).
5790 web_preferences_.reset();
Rakina Zata Amni4029b6d2020-07-28 02:36:205791 OnWebPreferencesChanged();
Rakina Zata Amni347b70902020-07-22 10:49:045792}
5793
Wei Li5bb659742018-02-14 03:07:585794void WebContentsImpl::PrintCrossProcessSubframe(
5795 const gfx::Rect& rect,
5796 int document_cookie,
5797 RenderFrameHost* subframe_host) {
Alexander Timin5fdeff22020-09-08 09:20:375798 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::PrintCrossProcessSubframe",
5799 "subframe",
5800 base::trace_event::ToTracedValue(subframe_host));
Wei Li5c0b4d12018-03-22 15:05:225801 auto* outer_contents = GetOuterWebContents();
5802 if (outer_contents) {
5803 // When an extension or app page is printed, the content should be
5804 // composited with outer content, so the outer contents should handle the
5805 // print request.
5806 outer_contents->PrintCrossProcessSubframe(rect, document_cookie,
5807 subframe_host);
5808 return;
5809 }
5810
Wei Li5bb659742018-02-14 03:07:585811 // If there is no delegate such as in tests or during deletion, do nothing.
5812 if (!delegate_)
5813 return;
5814
5815 delegate_->PrintCrossProcessSubframe(this, rect, document_cookie,
5816 subframe_host);
5817}
5818
ckitagawa8695799b2020-02-05 16:08:495819void WebContentsImpl::CapturePaintPreviewOfCrossProcessSubframe(
5820 const gfx::Rect& rect,
5821 const base::UnguessableToken& guid,
5822 RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:375823 OPTIONAL_TRACE_EVENT1(
5824 "content", "WebContentsImpl::CapturePaintPreviewOfCrossProcessSubframe",
5825 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host));
ckitagawa8695799b2020-02-05 16:08:495826 if (!delegate_)
5827 return;
ckitagawac43ac982020-07-07 17:41:175828 delegate_->CapturePaintPreviewOfSubframe(this, rect, guid, render_frame_host);
ckitagawa8695799b2020-02-05 16:08:495829}
5830
rob.buis300b0872017-03-10 20:43:585831#if defined(OS_ANDROID)
5832base::android::ScopedJavaLocalRef<jobject>
5833WebContentsImpl::GetJavaRenderFrameHostDelegate() {
5834 return GetJavaWebContents();
5835}
5836#endif
5837
Hiroki Nakagawa39d1bbe2020-07-14 16:15:525838void WebContentsImpl::OnDidDisplayContentWithCertificateErrors() {
Alexander Timin5fdeff22020-09-08 09:20:375839 OPTIONAL_TRACE_EVENT0(
5840 "content", "WebContentsImpl::OnDidDisplayContentWithCertificateErrors");
estarkc2273502016-10-12 22:03:025841 controller_.ssl_manager()->DidDisplayContentWithCertErrors();
estark910b4572015-12-09 20:55:415842}
5843
5844void WebContentsImpl::OnDidRunContentWithCertificateErrors(
Zhuoyu Qian4353f7f2018-01-08 05:33:005845 RenderFrameHostImpl* source) {
Alexander Timin5fdeff22020-09-08 09:20:375846 OPTIONAL_TRACE_EVENT1(
5847 "content", "WebContentsImpl::OnDidRunContentWithCertificateErrors",
5848 "render_frame_host", base::trace_event::ToTracedValue(source));
Emily Starkabbdd662020-06-05 02:40:135849 // For RenderFrameHosts that are inactive and going to be discarded, we can
5850 // disregard this message; there's no need to update the UI if the UI will
5851 // never be shown again.
5852 //
5853 // We still process this message for speculative RenderFrameHosts. This can
5854 // happen when a subframe's main resource has a certificate error. The
5855 // currently committed navigation entry will get marked as having run insecure
5856 // content and that will carry over to the navigation entry for the
5857 // speculative RFH when it commits.
5858 if (source->lifecycle_state() !=
5859 RenderFrameHostImpl::LifecycleState::kSpeculative &&
5860 source->IsInactiveAndDisallowReactivation()) {
estarkaeda1422016-05-10 02:31:125861 return;
Emily Starkabbdd662020-06-05 02:40:135862 }
estarkcd2e30c2016-08-12 06:51:155863 controller_.ssl_manager()->DidRunContentWithCertErrors(
Emily Starkabbdd662020-06-05 02:40:135864 source->GetMainFrame()->GetLastCommittedOrigin().GetURL());
estark910b4572015-12-09 20:55:415865}
5866
Kouhei Ueno97e0990d2019-09-25 02:57:275867void WebContentsImpl::DOMContentLoaded(RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:375868 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DOMContentLoaded",
5869 "render_frame_host",
5870 base::trace_event::ToTracedValue(render_frame_host));
Alexander Timin90c20c32020-08-12 15:28:325871 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5872 observer->DOMContentLoaded(render_frame_host);
5873 });
[email protected]724159a2010-12-30 01:11:185874}
5875
Gyuyoung Kim525e0c5d2020-03-09 15:04:195876void WebContentsImpl::OnDidFinishLoad(RenderFrameHost* render_frame_host,
nicka0ac8382016-12-15 23:59:235877 const GURL& url) {
Alexander Timin5fdeff22020-09-08 09:20:375878 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnDidFinishLoad",
5879 "render_frame_host",
5880 base::trace_event::ToTracedValue(render_frame_host),
5881 "url", base::trace_event::ValueToString(url));
[email protected]8b3af1e2014-01-24 13:29:125882 GURL validated_url(url);
Gyuyoung Kim525e0c5d2020-03-09 15:04:195883 render_frame_host->GetProcess()->FilterURL(false, &validated_url);
[email protected]028053d42014-03-05 22:20:375884
Alexander Timin90c20c32020-08-12 15:28:325885 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5886 observer->DidFinishLoad(render_frame_host, validated_url);
5887 });
yilkal172da772019-11-06 22:49:075888 size_t tree_size = frame_tree_.root()->GetFrameTreeSize();
5889 if (max_loaded_frame_count_ < tree_size)
5890 max_loaded_frame_count_ = tree_size;
5891
Gyuyoung Kim525e0c5d2020-03-09 15:04:195892 if (!render_frame_host->GetParent())
yilkal172da772019-11-06 22:49:075893 UMA_HISTOGRAM_COUNTS_1000("Navigation.MainFrame.FrameCount", tree_size);
[email protected]1a55c5be2011-11-29 11:36:315894}
5895
Dave Tapuska549baab2019-03-19 15:52:405896void WebContentsImpl::OnGoToEntryAtOffset(RenderFrameHostImpl* source,
Julie Jeongeun Kim144f8192020-01-18 06:59:035897 int32_t offset,
Dave Tapuska043b94a2019-09-10 14:14:355898 bool has_user_gesture) {
Alexander Timin5fdeff22020-09-08 09:20:375899 OPTIONAL_TRACE_EVENT2(
5900 "content", "WebContentsImpl::OnGoToEntryAtOffset", "render_frame_host",
5901 base::trace_event::ToTracedValue(source), "offset", offset);
Arthur Sonzognia7d715a2018-09-20 16:11:135902 // Non-user initiated navigations coming from the renderer should be ignored
5903 // if there is an ongoing browser-initiated navigation.
5904 // See https://crbug.com/879965.
5905 // TODO(arthursonzogni): See if this should check for ongoing navigations in
5906 // the frame(s) affected by the session history navigation, rather than just
5907 // the main frame.
Kevin McNee96851e12020-07-16 03:43:225908 if (Navigator::ShouldIgnoreIncomingRendererRequest(
5909 frame_tree_.root()->navigation_request(), has_user_gesture))
5910 return;
Arthur Sonzognia7d715a2018-09-20 16:11:135911
nicka0ac8382016-12-15 23:59:235912 // All frames are allowed to navigate the global history.
Dave Tapuska8bfd84c2019-03-26 20:47:165913 if (!delegate_ || delegate_->OnGoToEntryOffset(offset)) {
arthursonzognib93a4472020-04-10 07:38:005914 if (source->IsSandboxed(network::mojom::WebSandboxFlags::kTopNavigation)) {
Dave Tapuska8bfd84c2019-03-26 20:47:165915 // Keep track of whether this is a session history from a sandboxed iframe
5916 // with top level navigation disallowed.
5917 controller_.GoToOffsetInSandboxedFrame(offset,
5918 source->GetFrameTreeNodeId());
5919 } else {
5920 controller_.GoToOffset(offset);
5921 }
5922 }
[email protected]216813952011-05-19 22:21:265923}
5924
Dave Tapuska4c02911b2020-02-14 22:52:075925void WebContentsImpl::OnPageScaleFactorChanged(RenderFrameHostImpl* source,
nicka0ac8382016-12-15 23:59:235926 float page_scale_factor) {
Alexander Timin5fdeff22020-09-08 09:20:375927 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnPageScaleFactorChanged",
5928 "render_frame_host",
5929 base::trace_event::ToTracedValue(source),
5930 "page_scale_factor", page_scale_factor);
mcnee336ea2c2017-05-23 22:50:595931#if !defined(OS_ANDROID)
5932 // While page scale factor is used on mobile, this PageScaleFactorIsOne logic
5933 // is only needed on desktop.
mcnee432e47d2015-11-09 19:37:465934 bool is_one = page_scale_factor == 1.f;
5935 if (is_one != page_scale_factor_is_one_) {
5936 page_scale_factor_is_one_ = is_one;
5937
5938 HostZoomMapImpl* host_zoom_map =
5939 static_cast<HostZoomMapImpl*>(HostZoomMap::GetForWebContents(this));
5940
nicka0ac8382016-12-15 23:59:235941 if (host_zoom_map) {
mcnee432e47d2015-11-09 19:37:465942 host_zoom_map->SetPageScaleFactorIsOneForView(
Dave Tapuska4c02911b2020-02-14 22:52:075943 source->GetProcess()->GetID(),
5944 source->GetRenderViewHost()->GetRoutingID(),
mcnee432e47d2015-11-09 19:37:465945 page_scale_factor_is_one_);
5946 }
5947 }
mcnee336ea2c2017-05-23 22:50:595948#endif // !defined(OS_ANDROID)
mcnee432e47d2015-11-09 19:37:465949
Alexander Timin90c20c32020-08-12 15:28:325950 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5951 observer->OnPageScaleFactorChanged(page_scale_factor);
5952 });
mcnee432e47d2015-11-09 19:37:465953}
5954
W. James MacLean62198672019-06-04 16:46:105955void WebContentsImpl::OnTextAutosizerPageInfoChanged(
Henrique Ferreiroba535472020-04-21 11:38:365956 RenderFrameHostImpl* source,
5957 blink::mojom::TextAutosizerPageInfoPtr page_info) {
Alexander Timin5fdeff22020-09-08 09:20:375958 OPTIONAL_TRACE_EVENT1(
5959 "content", "WebContentsImpl::OnTextAutosizerPageInfoChanged",
5960 "render_frame_host", base::trace_event::ToTracedValue(source));
W. James MacLean62198672019-06-04 16:46:105961 // Keep a copy of |page_info| in case we create a new RenderView before
5962 // the next update.
Henrique Ferreiroba535472020-04-21 11:38:365963 text_autosizer_page_info_.main_frame_width = page_info->main_frame_width;
5964 text_autosizer_page_info_.main_frame_layout_width =
5965 page_info->main_frame_layout_width;
5966 text_autosizer_page_info_.device_scale_adjustment =
5967 page_info->device_scale_adjustment;
Antonio Gomesda7e03d2020-08-05 15:03:085968
5969 auto remote_frames_broadcast_callback = base::BindRepeating(
5970 [](const blink::mojom::TextAutosizerPageInfo& page_info,
5971 RenderFrameProxyHost* proxy_host) {
5972 DCHECK(proxy_host);
5973 proxy_host->GetAssociatedRemoteMainFrame()->UpdateTextAutosizerPageInfo(
5974 page_info.Clone());
5975 },
5976 text_autosizer_page_info_);
5977
5978 frame_tree_.root()->render_manager()->ExecuteRemoteFramesBroadcastMethod(
5979 std::move(remote_frames_broadcast_callback), source->GetSiteInstance());
W. James MacLean62198672019-06-04 16:46:105980}
5981
Kent Tamura8c9e0562018-11-06 07:02:195982void WebContentsImpl::EnumerateDirectory(
5983 RenderFrameHost* render_frame_host,
Kent Tamura3abb32d2020-07-02 00:23:015984 scoped_refptr<FileChooserImpl::FileSelectListenerImpl> listener,
Kent Tamura8c9e0562018-11-06 07:02:195985 const base::FilePath& directory_path) {
Alexander Timin5fdeff22020-09-08 09:20:375986 OPTIONAL_TRACE_EVENT2(
5987 "content", "WebContentsImpl::EnumerateDirectory", "render_frame_host",
5988 base::trace_event::ToTracedValue(render_frame_host), "directory_path",
5989 base::trace_event::ValueToString(directory_path));
Avi Drissman1a55a9d62020-03-10 18:56:455990 // Any explicit focusing of another window while this WebContents is in
5991 // fullscreen can be used to confuse the user, so drop fullscreen.
5992 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
5993 listener->SetFullscreenBlock(std::move(fullscreen_block));
5994
Kent Tamura8c9e0562018-11-06 07:02:195995 if (delegate_)
5996 delegate_->EnumerateDirectory(this, std::move(listener), directory_path);
5997 else
5998 listener->FileSelectionCanceled();
[email protected]3a29a6e2011-08-24 18:26:215999}
6000
Dave Tapuskaf9fc3122019-10-18 19:42:556001void WebContentsImpl::RegisterProtocolHandler(RenderFrameHostImpl* source,
6002 const std::string& protocol,
6003 const GURL& url,
6004 const base::string16& title,
6005 bool user_gesture) {
Alexander Timin5fdeff22020-09-08 09:20:376006 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RegisterProtocolHandler",
6007 "render_frame_host",
6008 base::trace_event::ToTracedValue(source), "protocol",
6009 protocol);
nicka0ac8382016-12-15 23:59:236010 // TODO(nick): Do we need to apply FilterURL to |url|?
[email protected]e5f2de02012-07-20 22:15:436011 if (!delegate_)
6012 return;
6013
Raymes Khoury58373df2019-08-06 06:29:206014 if (!AreValidRegisterProtocolHandlerArguments(
6015 protocol, url, source->GetLastCommittedOrigin())) {
6016 ReceivedBadMessage(source->GetProcess(),
6017 bad_message::REGISTER_PROTOCOL_HANDLER_INVALID_URL);
[email protected]b9535422012-02-09 01:47:596018 return;
Raymes Khoury58373df2019-08-06 06:29:206019 }
[email protected]8f810632013-06-06 22:33:326020
Carlos Caballero8a6c6b72020-07-20 16:56:226021 delegate_->RegisterProtocolHandler(source, protocol, url, user_gesture);
[email protected]7d189022011-08-25 22:54:206022}
6023
Dave Tapuskaf9fc3122019-10-18 19:42:556024void WebContentsImpl::UnregisterProtocolHandler(RenderFrameHostImpl* source,
6025 const std::string& protocol,
6026 const GURL& url,
6027 bool user_gesture) {
Alexander Timin5fdeff22020-09-08 09:20:376028 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::UnregisterProtocolHandler",
6029 "render_frame_host",
6030 base::trace_event::ToTracedValue(source), "protocol",
6031 protocol);
nicka0ac8382016-12-15 23:59:236032 // TODO(nick): Do we need to apply FilterURL to |url|?
[email protected]f5273e52014-07-14 16:30:206033 if (!delegate_)
6034 return;
6035
Raymes Khoury58373df2019-08-06 06:29:206036 if (!AreValidRegisterProtocolHandlerArguments(
6037 protocol, url, source->GetLastCommittedOrigin())) {
6038 ReceivedBadMessage(source->GetProcess(),
6039 bad_message::REGISTER_PROTOCOL_HANDLER_INVALID_URL);
[email protected]f5273e52014-07-14 16:30:206040 return;
Raymes Khoury58373df2019-08-06 06:29:206041 }
[email protected]f5273e52014-07-14 16:30:206042
Carlos Caballero8a6c6b72020-07-20 16:56:226043 delegate_->UnregisterProtocolHandler(source, protocol, url, user_gesture);
[email protected]f5273e52014-07-14 16:30:206044}
6045
Marijn Kruisselbrink7f519672019-02-05 19:12:506046void WebContentsImpl::OnAppCacheAccessed(const GURL& manifest_url,
[email protected]b172aee2012-04-10 17:05:266047 bool blocked_by_policy) {
Alexander Timin5fdeff22020-09-08 09:20:376048 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnAppCacheAccessed");
nicka0ac8382016-12-15 23:59:236049 // TODO(nick): Should we consider |source| here? Should we call FilterURL on
6050 // |manifest_url|?
6051
[email protected]7fc4bbb2011-09-08 21:23:106052 // Notify observers about navigation.
Alexander Timin90c20c32020-08-12 15:28:326053 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6054 observer->AppCacheAccessed(manifest_url, blocked_by_policy);
6055 });
[email protected]7fc4bbb2011-09-08 21:23:106056}
6057
Gyuyoung Kimc5f4ac12020-05-08 10:59:396058void WebContentsImpl::DomOperationResponse(const std::string& json_string) {
Alexander Timin5fdeff22020-09-08 09:20:376059 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DomOperationResponse",
6060 "json_string", json_string);
6061
Gyuyoung Kimc5f4ac12020-05-08 10:59:396062 // TODO(lukasza): The notification below should probably indicate which
6063 // RenderFrameHostImpl the message is coming from. This can enable tests to
6064 // talk to 2 frames at the same time, without being confused which frame a
6065 // given response comes from. See also a corresponding TODO in the
6066 // ExecuteScriptHelper in //content/public/test/browser_test_utils.cc
6067 NotificationService::current()->Notify(
6068 NOTIFICATION_DOM_OPERATION_RESPONSE, Source<WebContents>(this),
6069 Details<const std::string>(&json_string));
6070}
6071
Gyuyoung Kim4c50517842020-06-04 17:50:446072void WebContentsImpl::SavableResourceLinksResponse(
6073 RenderFrameHostImpl* source,
6074 const std::vector<GURL>& resources_list,
6075 blink::mojom::ReferrerPtr referrer,
6076 const std::vector<blink::mojom::SavableSubframePtr>& subframes) {
Alexander Timin5fdeff22020-09-08 09:20:376077 OPTIONAL_TRACE_EVENT1(
6078 "content", "WebContentsImpl::SavableResourceLinksResponse",
6079 "render_frame_host", base::trace_event::ToTracedValue(source));
Gyuyoung Kim4c50517842020-06-04 17:50:446080 save_package_->SavableResourceLinksResponse(source, resources_list,
6081 std::move(referrer), subframes);
6082}
6083
6084void WebContentsImpl::SavableResourceLinksError(RenderFrameHostImpl* source) {
Alexander Timin5fdeff22020-09-08 09:20:376085 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SavableResourceLinksError",
6086 "render_frame_host",
6087 base::trace_event::ToTracedValue(source));
Gyuyoung Kim4c50517842020-06-04 17:50:446088 save_package_->SavableResourceLinksError(source);
6089}
6090
Alexander Timin17edc742020-04-23 18:22:186091void WebContentsImpl::OnServiceWorkerAccessed(
6092 RenderFrameHost* render_frame_host,
6093 const GURL& scope,
6094 AllowServiceWorkerResult allowed) {
Alexander Timin5fdeff22020-09-08 09:20:376095 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnServiceWorkerAccessed",
6096 "render_frame_host",
6097 base::trace_event::ToTracedValue(render_frame_host),
6098 "scope", base::trace_event::ValueToString(scope));
Alexander Timin90c20c32020-08-12 15:28:326099 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6100 observer->OnServiceWorkerAccessed(render_frame_host, scope, allowed);
6101 });
Alexander Timin17edc742020-04-23 18:22:186102}
6103
6104void WebContentsImpl::OnServiceWorkerAccessed(
6105 NavigationHandle* navigation,
6106 const GURL& scope,
6107 AllowServiceWorkerResult allowed) {
Alexander Timin5fdeff22020-09-08 09:20:376108 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnServiceWorkerAccessed",
6109 "navigation_handle", navigation, "scope",
6110 base::trace_event::ValueToString(scope));
Alexander Timin90c20c32020-08-12 15:28:326111 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6112 observer->OnServiceWorkerAccessed(navigation, scope, allowed);
6113 });
Alexander Timin17edc742020-04-23 18:22:186114}
6115
Miyoung Shincb6475a2019-11-09 10:49:456116void WebContentsImpl::OnColorChooserFactoryReceiver(
Julie Jeongeun Kim8e2879e2019-08-06 23:55:206117 mojo::PendingReceiver<blink::mojom::ColorChooserFactory> receiver) {
Alexander Timin5fdeff22020-09-08 09:20:376118 OPTIONAL_TRACE_EVENT0("content",
6119 "WebContentsImpl::OnColorChooserFactoryReceiver");
Julie Jeongeun Kim8e2879e2019-08-06 23:55:206120 color_chooser_factory_receivers_.Add(this, std::move(receiver));
Joel Hockey85b379d2017-12-11 10:42:136121}
6122
6123void WebContentsImpl::OpenColorChooser(
Julie Jeongeun Kim8e2879e2019-08-06 23:55:206124 mojo::PendingReceiver<blink::mojom::ColorChooser> chooser_receiver,
6125 mojo::PendingRemote<blink::mojom::ColorChooserClient> client,
[email protected]8ed16472014-04-11 19:02:486126 SkColor color,
Joel Hockey163835a2017-12-20 11:51:576127 std::vector<blink::mojom::ColorSuggestionPtr> suggestions) {
Alexander Timin5fdeff22020-09-08 09:20:376128 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OpenColorChooser");
Joel Hockey85b379d2017-12-11 10:42:136129 content::ColorChooser* new_color_chooser =
Ivan Kotenkov2c0d2bb32017-11-01 15:41:286130 delegate_ ? delegate_->OpenColorChooser(this, color, suggestions)
6131 : nullptr;
[email protected]820957a2014-01-14 14:56:306132 if (!new_color_chooser)
[email protected]cb805452013-05-22 15:16:216133 return;
[email protected]8ed16472014-04-11 19:02:486134
Joel Hockey85b379d2017-12-11 10:42:136135 color_chooser_.reset();
6136 color_chooser_ = std::make_unique<ColorChooser>(
Julie Jeongeun Kim8e2879e2019-08-06 23:55:206137 new_color_chooser, std::move(chooser_receiver), std::move(client));
[email protected]da8543762012-03-20 08:52:206138}
6139
brettw4b461082016-11-19 18:55:166140#if BUILDFLAG(ENABLE_PLUGINS)
nicka0ac8382016-12-15 23:59:236141void WebContentsImpl::OnPepperInstanceCreated(RenderFrameHostImpl* source,
6142 int32_t pp_instance) {
Alexander Timin5fdeff22020-09-08 09:20:376143 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPepperInstanceCreated",
6144 "render_frame_host",
6145 base::trace_event::ToTracedValue(source));
Alexander Timin90c20c32020-08-12 15:28:326146 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6147 observer->PepperInstanceCreated();
6148 });
nicka0ac8382016-12-15 23:59:236149 pepper_playback_observer_->PepperInstanceCreated(source, pp_instance);
emaxxe70f5e12015-05-29 11:26:006150}
6151
nicka0ac8382016-12-15 23:59:236152void WebContentsImpl::OnPepperInstanceDeleted(RenderFrameHostImpl* source,
6153 int32_t pp_instance) {
Alexander Timin5fdeff22020-09-08 09:20:376154 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPepperInstanceDeleted",
6155 "render_frame_host",
6156 base::trace_event::ToTracedValue(source));
Alexander Timin90c20c32020-08-12 15:28:326157 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6158 observer->PepperInstanceDeleted();
6159 });
nicka0ac8382016-12-15 23:59:236160 pepper_playback_observer_->PepperInstanceDeleted(source, pp_instance);
emaxxe70f5e12015-05-29 11:26:006161}
6162
nicka0ac8382016-12-15 23:59:236163void WebContentsImpl::OnPepperPluginHung(RenderFrameHostImpl* source,
6164 int plugin_child_id,
tommyclie6633ca72014-10-31 00:40:426165 const base::FilePath& path,
6166 bool is_hung) {
Alexander Timin5fdeff22020-09-08 09:20:376167 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPepperPluginHung",
6168 "render_frame_host",
6169 base::trace_event::ToTracedValue(source));
Steven Holte95922222018-09-14 20:06:236170 UMA_HISTOGRAM_COUNTS_1M("Pepper.PluginHung", 1);
tommyclie6633ca72014-10-31 00:40:426171
Alexander Timin90c20c32020-08-12 15:28:326172 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6173 observer->PluginHungStatusChanged(plugin_child_id, path, is_hung);
6174 });
tommyclie6633ca72014-10-31 00:40:426175}
6176
nicka0ac8382016-12-15 23:59:236177void WebContentsImpl::OnPepperStartsPlayback(RenderFrameHostImpl* source,
6178 int32_t pp_instance) {
Alexander Timin5fdeff22020-09-08 09:20:376179 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPepperStartsPlayback",
6180 "render_frame_host",
6181 base::trace_event::ToTracedValue(source));
nicka0ac8382016-12-15 23:59:236182 pepper_playback_observer_->PepperStartsPlayback(source, pp_instance);
zqzhang181047e62016-07-01 13:37:176183}
6184
nicka0ac8382016-12-15 23:59:236185void WebContentsImpl::OnPepperStopsPlayback(RenderFrameHostImpl* source,
6186 int32_t pp_instance) {
Alexander Timin5fdeff22020-09-08 09:20:376187 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPepperStopsPlayback",
6188 "render_frame_host",
6189 base::trace_event::ToTracedValue(source));
nicka0ac8382016-12-15 23:59:236190 pepper_playback_observer_->PepperStopsPlayback(source, pp_instance);
zqzhang181047e62016-07-01 13:37:176191}
6192
nicka0ac8382016-12-15 23:59:236193void WebContentsImpl::OnPluginCrashed(RenderFrameHostImpl* source,
6194 const base::FilePath& plugin_path,
tommyclie6633ca72014-10-31 00:40:426195 base::ProcessId plugin_pid) {
Alexander Timin5fdeff22020-09-08 09:20:376196 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPluginCrashed",
6197 "render_frame_host",
6198 base::trace_event::ToTracedValue(source));
nicka0ac8382016-12-15 23:59:236199 // TODO(nick): Eliminate the |plugin_pid| parameter, which can't be trusted,
Gyuyoung Kim26c7bc92020-04-29 00:53:006200 // and is only used by WebTestControlHost.
Alexander Timin90c20c32020-08-12 15:28:326201 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6202 observer->PluginCrashed(plugin_path, plugin_pid);
6203 });
tommyclie6633ca72014-10-31 00:40:426204}
6205
[email protected]d8415ad92012-08-23 14:40:506206void WebContentsImpl::OnRequestPpapiBrokerPermission(
nicka0ac8382016-12-15 23:59:236207 RenderViewHostImpl* source,
6208 int ppb_broker_route_id,
[email protected]d8415ad92012-08-23 14:40:506209 const GURL& url,
[email protected]2dec8ec2013-02-07 19:20:346210 const base::FilePath& plugin_path) {
Alexander Timin5fdeff22020-09-08 09:20:376211 OPTIONAL_TRACE_EVENT1("content",
6212 "WebContentsImpl::OnRequestPpapiBrokerPermission",
6213 "render_view_host", source);
Avi Drissman0a2a967d2019-04-01 19:33:526214 base::OnceCallback<void(bool)> permission_result_callback = base::BindOnce(
nicka0ac8382016-12-15 23:59:236215 &WebContentsImpl::SendPpapiBrokerPermissionResult, base::Unretained(this),
6216 source->GetProcess()->GetID(), ppb_broker_route_id);
[email protected]8c8fc292012-11-23 18:57:166217 if (!delegate_) {
Tommy Nyquist4b749d02018-03-20 21:46:296218 std::move(permission_result_callback).Run(false);
[email protected]8c8fc292012-11-23 18:57:166219 return;
[email protected]d8415ad92012-08-23 14:40:506220 }
6221
Avi Drissman0a2a967d2019-04-01 19:33:526222 delegate_->RequestPpapiBrokerPermission(
6223 this, url, plugin_path, std::move(permission_result_callback));
[email protected]d8415ad92012-08-23 14:40:506224}
6225
nicka0ac8382016-12-15 23:59:236226void WebContentsImpl::SendPpapiBrokerPermissionResult(int process_id,
6227 int ppb_broker_route_id,
6228 bool result) {
Alexander Timin5fdeff22020-09-08 09:20:376229 OPTIONAL_TRACE_EVENT2(
6230 "content", "WebContentsImpl::SendPpapiBrokerPermissionResult",
6231 "process_id", process_id, "ppb_broker_route_id", ppb_broker_route_id);
nicka0ac8382016-12-15 23:59:236232 RenderProcessHost* rph = RenderProcessHost::FromID(process_id);
6233 if (rph) {
6234 // TODO(nick): Convert this from ViewMsg_ to a Ppapi msg, since it
6235 // is not routed to a RenderView.
6236 rph->Send(
6237 new ViewMsg_PpapiBrokerPermissionResult(ppb_broker_route_id, result));
6238 }
[email protected]d8415ad92012-08-23 14:40:506239}
brettw4b461082016-11-19 18:55:166240#endif // BUILDFLAG(ENABLE_PLUGINS)
[email protected]19be7a62012-10-01 23:03:376241
Miyoung Shin5709ab02020-02-19 06:50:416242void WebContentsImpl::UpdateFaviconURL(
6243 RenderFrameHost* source,
6244 std::vector<blink::mojom::FaviconURLPtr> candidates) {
Alexander Timin5fdeff22020-09-08 09:20:376245 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::UpdateFaviconURL",
6246 "render_frame_host",
6247 base::trace_event::ToTracedValue(source));
lukasza178ff092017-06-07 23:39:506248 // Ignore favicons for non-main frame.
6249 if (source->GetParent()) {
6250 NOTREACHED();
6251 return;
6252 }
6253
pkotwiczf9bc20592015-04-21 18:57:066254 // We get updated favicon URLs after the page stops loading. If a cross-site
6255 // navigation occurs while a page is still loading, the initial page
6256 // may stop loading and send us updated favicon URLs after the navigation
6257 // for the new page has committed.
lukasza178ff092017-06-07 23:39:506258 if (!source->IsCurrent())
pkotwiczf9bc20592015-04-21 18:57:066259 return;
6260
Miyoung Shin5709ab02020-02-19 06:50:416261 favicon_urls_ = std::move(candidates);
Mounir Lamouri7b4a1f232019-12-23 16:32:106262
Alexander Timin90c20c32020-08-12 15:28:326263 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6264 observer->DidUpdateFaviconURL(source, favicon_urls_);
6265 });
[email protected]795c28972012-12-06 06:13:396266}
6267
qinmin72e8bd02016-10-21 19:35:376268void WebContentsImpl::SetIsOverlayContent(bool is_overlay_content) {
Alexander Timin5fdeff22020-09-08 09:20:376269 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetIsOverlayContent",
6270 "is_overlay_content", is_overlay_content);
qinmin72e8bd02016-10-21 19:35:376271 is_overlay_content_ = is_overlay_content;
6272}
6273
Albert J. Wongfb64e142018-10-16 01:10:456274void WebContentsImpl::DidFirstVisuallyNonEmptyPaint(
6275 RenderViewHostImpl* source) {
Alexander Timin5fdeff22020-09-08 09:20:376276 OPTIONAL_TRACE_EVENT1("content",
6277 "WebContentsImpl::DidFirstVisuallyNonEmptyPaint",
6278 "render_view_host", source);
nicka0ac8382016-12-15 23:59:236279 // TODO(nick): When this is ported to FrameHostMsg_, we should only listen if
6280 // |source| is the main frame.
Alexander Timin90c20c32020-08-12 15:28:326281 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6282 observer->DidFirstVisuallyNonEmptyPaint();
6283 });
Carlos Caballero1215f882019-10-29 15:58:436284 if (source->theme_color() != last_sent_theme_color_) {
yusufod41c5f92015-03-06 00:14:286285 // Theme color should have updated by now if there was one.
Alexander Timin90c20c32020-08-12 15:28:326286 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6287 observer->DidChangeThemeColor();
6288 });
Carlos Caballero1215f882019-10-29 15:58:436289 last_sent_theme_color_ = source->theme_color();
yusufod41c5f92015-03-06 00:14:286290 }
Alan Cutterd73a15d92020-08-21 07:12:456291
6292 if (source->background_color() != last_sent_background_color_) {
6293 // Background color should have updated by now if there was one.
6294 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6295 observer->OnBackgroundColorChanged();
6296 });
6297 last_sent_background_color_ = source->background_color();
6298 }
[email protected]9f268072013-11-07 00:02:156299}
[email protected]d9030b82013-07-19 08:26:066300
Kevin McNee068c3eb2020-04-03 18:24:196301bool WebContentsImpl::IsPortal() {
Adithya Srinivasan46b8a792019-02-01 14:47:236302 return portal();
6303}
6304
Kevin McNee94ea52f52020-06-23 17:42:066305WebContentsImpl* WebContentsImpl::GetPortalHostWebContents() {
6306 return portal() ? portal()->GetPortalHostContents() : nullptr;
6307}
6308
[email protected]17e286e2013-03-01 23:29:396309void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
Alexander Timin5fdeff22020-09-08 09:20:376310 OPTIONAL_TRACE_EVENT0("content",
6311 "WebContentsImpl::NotifyBeforeFormRepostWarningShow");
Alexander Timin90c20c32020-08-12 15:28:326312 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6313 observer->BeforeFormRepostWarningShow();
6314 });
[email protected]17e286e2013-03-01 23:29:396315}
6316
[email protected]ec6c05f2013-10-23 18:41:576317void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
Alexander Timin5fdeff22020-09-08 09:20:376318 OPTIONAL_TRACE_EVENT0(
6319 "content", "WebContentsImpl::ActivateAndShowRepostFormWarningDialog");
[email protected]ec6c05f2013-10-23 18:41:576320 Activate();
6321 if (delegate_)
6322 delegate_->ShowRepostFormWarningDialog(this);
6323}
6324
[email protected]b4c84012014-04-28 19:51:106325bool WebContentsImpl::HasAccessedInitialDocument() {
6326 return has_accessed_initial_document_;
6327}
6328
afakhry6f0c1ec22016-07-14 13:55:136329void WebContentsImpl::UpdateTitleForEntry(NavigationEntry* entry,
[email protected]fcf75d42013-12-03 20:11:266330 const base::string16& title) {
Alexander Timin5fdeff22020-09-08 09:20:376331 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::UpdateTitleForEntry",
6332 "title", base::trace_event::ValueToString(title));
[email protected]fcf75d42013-12-03 20:11:266333 base::string16 final_title;
Avi Drissman93002212017-09-27 03:20:526334 base::TrimWhitespace(title, base::TRIM_ALL, &final_title);
[email protected]420ae012009-04-24 05:16:326335
[email protected]987fc3a2011-05-26 14:18:096336 // If a page is created via window.open and never navigated,
6337 // there will be no navigation entry. In this situation,
[email protected]73eb2602012-02-09 19:50:556338 // |page_title_when_no_navigation_entry_| will be used for page title.
[email protected]987fc3a2011-05-26 14:18:096339 if (entry) {
[email protected]36fc0392011-12-25 03:59:516340 if (final_title == entry->GetTitle())
afakhry6f0c1ec22016-07-14 13:55:136341 return; // Nothing changed, don't bother.
[email protected]420ae012009-04-24 05:16:326342
[email protected]36fc0392011-12-25 03:59:516343 entry->SetTitle(final_title);
Avi Drissman93002212017-09-27 03:20:526344
6345 // The title for display may differ from the title just set; grab it.
6346 final_title = entry->GetTitleForDisplay();
[email protected]987fc3a2011-05-26 14:18:096347 } else {
6348 if (page_title_when_no_navigation_entry_ == final_title)
afakhry6f0c1ec22016-07-14 13:55:136349 return; // Nothing changed, don't bother.
[email protected]987fc3a2011-05-26 14:18:096350
6351 page_title_when_no_navigation_entry_ = final_title;
6352 }
[email protected]420ae012009-04-24 05:16:326353
[email protected]420ae012009-04-24 05:16:326354 // Lastly, set the title for the view.
[email protected]790e2fd2011-09-21 20:28:236355 view_->SetPageTitle(final_title);
[email protected]420ae012009-04-24 05:16:326356
Alexander Timin90c20c32020-08-12 15:28:326357 observers_.ForEachObserver(
6358 [&](WebContentsObserver* observer) { observer->TitleWasSet(entry); });
afakhry6f0c1ec22016-07-14 13:55:136359 // Broadcast notifications when the UI should be updated.
6360 if (entry == controller_.GetEntryAtOffset(0))
6361 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE);
[email protected]420ae012009-04-24 05:16:326362}
6363
fdegansa696e5112015-04-17 01:57:596364void WebContentsImpl::SendChangeLoadProgress() {
Alexander Timin5fdeff22020-09-08 09:20:376365 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SendChangeLoadProgress",
6366 "load_progress", frame_tree_.load_progress());
[email protected]960b0372014-05-19 18:01:006367 loading_last_progress_update_ = base::TimeTicks::Now();
Alexander Timin90c20c32020-08-12 15:28:326368 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6369 observer->LoadProgressChanged(frame_tree_.load_progress());
6370 });
[email protected]960b0372014-05-19 18:01:006371}
6372
6373void WebContentsImpl::ResetLoadProgressState() {
Alexander Timin5fdeff22020-09-08 09:20:376374 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ResetLoadProgressState");
fdegans1d16355162015-03-26 11:58:346375 frame_tree_.ResetLoadProgress();
[email protected]960b0372014-05-19 18:01:006376 loading_weak_factory_.InvalidateWeakPtrs();
6377 loading_last_progress_update_ = base::TimeTicks();
6378}
6379
clamy44e84ce2016-02-22 15:38:256380// Notifies the RenderWidgetHost instance about the fact that the page is
6381// loading, or done loading.
6382void WebContentsImpl::LoadingStateChanged(bool to_different_document,
clamy44e84ce2016-02-22 15:38:256383 LoadNotificationDetails* details) {
Nate Chapin22ea6592019-03-05 22:29:026384 if (is_being_destroyed_)
6385 return;
clamy44e84ce2016-02-22 15:38:256386
6387 bool is_loading = IsLoading();
6388
Alexander Timin5fdeff22020-09-08 09:20:376389 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::LoadingStateChanged",
6390 "is_loading", is_loading);
6391
clamy44e84ce2016-02-22 15:38:256392 if (!is_loading) {
6393 load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
6394 base::string16());
6395 load_state_host_.clear();
6396 upload_size_ = 0;
6397 upload_position_ = 0;
6398 }
6399
6400 GetRenderManager()->SetIsLoading(is_loading);
6401
6402 waiting_for_response_ = is_loading;
6403 is_load_to_different_document_ = to_different_document;
6404
6405 if (delegate_)
6406 delegate_->LoadingStateChanged(this, to_different_document);
6407 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD);
6408
6409 std::string url = (details ? details->url.possibly_invalid_spec() : "NULL");
6410 if (is_loading) {
6411 TRACE_EVENT_ASYNC_BEGIN2("browser,navigation", "WebContentsImpl Loading",
6412 this, "URL", url, "Main FrameTreeNode id",
6413 GetFrameTree()->root()->frame_tree_node_id());
Alexander Timin90c20c32020-08-12 15:28:326414 observers_.ForEachObserver(
6415 [&](WebContentsObserver* observer) { observer->DidStartLoading(); });
clamy44e84ce2016-02-22 15:38:256416 } else {
6417 TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
6418 this, "URL", url);
Alexander Timin90c20c32020-08-12 15:28:326419 observers_.ForEachObserver(
6420 [&](WebContentsObserver* observer) { observer->DidStopLoading(); });
clamy44e84ce2016-02-22 15:38:256421 }
6422
6423 // TODO(avi): Remove. http://crbug.com/170921
6424 int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP;
6425 NotificationDetails det = NotificationService::NoDetails();
6426 if (details)
6427 det = Details<LoadNotificationDetails>(details);
6428 NotificationService::current()->Notify(
6429 type, Source<NavigationController>(&controller_), det);
6430}
6431
danakja0bce4c952020-05-12 20:40:286432void WebContentsImpl::NotifyViewSwapped(RenderViewHost* old_view,
6433 RenderViewHost* new_view) {
Alexander Timin5fdeff22020-09-08 09:20:376434 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::NotifyViewSwapped",
6435 "old_view", old_view, "new_view", new_view);
danakja0bce4c952020-05-12 20:40:286436 DCHECK_NE(old_view, new_view);
[email protected]420ae012009-04-24 05:16:326437 // After sending out a swap notification, we need to send a disconnect
6438 // notification so that clients that pick up a pointer to |this| can NULL the
6439 // pointer. See Bug 1230284.
6440 notify_disconnection_ = true;
Alexander Timin90c20c32020-08-12 15:28:326441 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6442 observer->RenderViewHostChanged(old_view, new_view);
6443 });
danakja0bce4c952020-05-12 20:40:286444 view_->RenderViewHostChanged(old_view, new_view);
Jinsuk Kimdc5284c22018-07-11 02:22:066445
Lucas Furukawa Gadanif9ea4fc2018-08-03 23:57:136446 // If this is an inner WebContents that has swapped views, we need to reattach
6447 // it to its outer WebContents.
6448 if (node_.outer_web_contents())
6449 ReattachToOuterWebContentsFrame();
6450
[email protected]7a846df2012-09-20 19:17:396451 // Ensure that the associated embedder gets cleared after a RenderViewHost
6452 // gets swapped, so we don't reuse the same embedder next time a
6453 // RenderViewHost is attached to this WebContents.
6454 RemoveBrowserPluginEmbedder();
[email protected]420ae012009-04-24 05:16:326455}
6456
danakja0bce4c952020-05-12 20:40:286457void WebContentsImpl::NotifyFrameSwapped(RenderFrameHost* old_frame,
6458 RenderFrameHost* new_frame,
Jinsuk Kim895b2c52018-07-03 06:49:166459 bool is_main_frame) {
Alexander Timin5fdeff22020-09-08 09:20:376460 TRACE_EVENT2("content", "WebContentsImpl::NotifyFrameSwapped", "old_frame",
6461 base::trace_event::ToTracedValue(old_frame), "new_frame",
6462 base::trace_event::ToTracedValue(new_frame));
Bo Liu168c8642017-08-28 18:26:026463#if defined(OS_ANDROID)
danakja0bce4c952020-05-12 20:40:286464 // Copy importance from |old_frame| if |new_frame| is a main frame.
6465 if (old_frame && !new_frame->GetParent()) {
6466 RenderWidgetHostImpl* old_widget =
6467 static_cast<RenderFrameHostImpl*>(old_frame)->GetRenderWidgetHost();
6468 RenderWidgetHostImpl* new_widget =
6469 static_cast<RenderFrameHostImpl*>(new_frame)->GetRenderWidgetHost();
6470 new_widget->SetImportance(old_widget->importance());
Bo Liu7c6779e92017-08-16 02:02:286471 }
Bo Liu168c8642017-08-28 18:26:026472#endif
Alexander Timin90c20c32020-08-12 15:28:326473 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6474 observer->RenderFrameHostChanged(old_frame, new_frame);
6475 });
[email protected]02d7b6e2014-06-24 21:01:506476}
6477
[email protected]da7a7182013-09-06 08:11:116478// TODO(avi): Remove this entire function because this notification is already
6479// covered by two observer functions. http://crbug.com/170921
[email protected]b172aee2012-04-10 17:05:266480void WebContentsImpl::NotifyDisconnected() {
Alexander Timin5fdeff22020-09-08 09:20:376481 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::NotifyDisconnected");
[email protected]420ae012009-04-24 05:16:326482 if (!notify_disconnection_)
6483 return;
6484
6485 notify_disconnection_ = false;
[email protected]8ff00d72012-10-23 19:12:216486 NotificationService::current()->Notify(
6487 NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
6488 Source<WebContents>(this),
6489 NotificationService::NoDetails());
[email protected]420ae012009-04-24 05:16:326490}
6491
[email protected]cbb1ef592013-06-05 19:49:466492void WebContentsImpl::NotifyNavigationEntryCommitted(
6493 const LoadCommittedDetails& load_details) {
Alexander Timin5fdeff22020-09-08 09:20:376494 OPTIONAL_TRACE_EVENT0("content",
6495 "WebContentsImpl::NotifyNavigationEntryCommitted");
Alexander Timin90c20c32020-08-12 15:28:326496 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6497 observer->NavigationEntryCommitted(load_details);
6498 });
[email protected]cbb1ef592013-06-05 19:49:466499}
6500
Sam McNally5c087a32017-08-25 01:46:146501void WebContentsImpl::NotifyNavigationEntryChanged(
6502 const EntryChangedDetails& change_details) {
Alexander Timin5fdeff22020-09-08 09:20:376503 OPTIONAL_TRACE_EVENT0("content",
6504 "WebContentsImpl::NotifyNavigationEntryChanged");
Alexander Timin90c20c32020-08-12 15:28:326505 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6506 observer->NavigationEntryChanged(change_details);
6507 });
Sam McNally5c087a32017-08-25 01:46:146508}
6509
6510void WebContentsImpl::NotifyNavigationListPruned(
6511 const PrunedDetails& pruned_details) {
Alexander Timin5fdeff22020-09-08 09:20:376512 OPTIONAL_TRACE_EVENT0("content",
6513 "WebContentsImpl::NotifyNavigationListPruned");
Alexander Timin90c20c32020-08-12 15:28:326514 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6515 observer->NavigationListPruned(pruned_details);
6516 });
Sam McNally5c087a32017-08-25 01:46:146517}
6518
Christian Dullweber1af31e62018-02-22 11:49:486519void WebContentsImpl::NotifyNavigationEntriesDeleted() {
Alexander Timin5fdeff22020-09-08 09:20:376520 OPTIONAL_TRACE_EVENT0("content",
6521 "WebContentsImpl::NotifyNavigationEntriesDeleted");
Alexander Timin90c20c32020-08-12 15:28:326522 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6523 observer->NavigationEntriesDeleted();
6524 });
Christian Dullweber1af31e62018-02-22 11:49:486525}
6526
rockotf62002a2016-09-15 00:08:596527void WebContentsImpl::OnAssociatedInterfaceRequest(
6528 RenderFrameHost* render_frame_host,
6529 const std::string& interface_name,
6530 mojo::ScopedInterfaceEndpointHandle handle) {
Alexander Timin5fdeff22020-09-08 09:20:376531 OPTIONAL_TRACE_EVENT2(
6532 "content", "WebContentsImpl::OnAssociatedInterfaceRequest",
6533 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host),
6534 "interface_name", interface_name);
Julie Jeongeun Kim7d0986172019-12-04 03:17:256535 auto it = receiver_sets_.find(interface_name);
6536 if (it != receiver_sets_.end())
6537 it->second->OnReceiverForFrame(render_frame_host, std::move(handle));
rockotf62002a2016-09-15 00:08:596538}
6539
Ben Goodger9e24929e2017-07-21 03:13:406540void WebContentsImpl::OnInterfaceRequest(
6541 RenderFrameHost* render_frame_host,
6542 const std::string& interface_name,
6543 mojo::ScopedMessagePipeHandle* interface_pipe) {
Alexander Timin5fdeff22020-09-08 09:20:376544 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnInterfaceRequest",
6545 "render_frame_host",
6546 base::trace_event::ToTracedValue(render_frame_host),
6547 "interface_name", interface_name);
Alexander Timin90c20c32020-08-12 15:28:326548 for (auto& observer : observers_.observer_list()) {
Ben Goodger9e24929e2017-07-21 03:13:406549 observer.OnInterfaceRequestFromFrame(render_frame_host, interface_name,
6550 interface_pipe);
6551 if (!interface_pipe->is_valid())
6552 break;
6553 }
6554}
6555
Varun Khaneja5da94302019-06-25 04:48:106556void WebContentsImpl::OnDidBlockNavigation(
6557 const GURL& blocked_url,
6558 const GURL& initiator_url,
Abhijeet Kandalkarde7348e2020-01-13 06:06:546559 blink::mojom::NavigationBlockedReason reason) {
Alexander Timin5fdeff22020-09-08 09:20:376560 OPTIONAL_TRACE_EVENT1(
6561 "content", "WebContentsImpl::OnDidBlockNavigation", "details",
6562 base::trace_event::TracedValue::Build(
6563 {{"blocked_url", base::trace_event::ValueToString(blocked_url)},
6564 {"initiator_url", base::trace_event::ValueToString(initiator_url)},
6565 {"reason", base::trace_event::ValueToString(reason)}}));
Nicolas Dossou-gbetebcab2472017-09-09 12:28:406566 if (delegate_)
Varun Khaneja5da94302019-06-25 04:48:106567 delegate_->OnDidBlockNavigation(this, blocked_url, initiator_url, reason);
Nicolas Dossou-gbetebcab2472017-09-09 12:28:406568}
6569
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416570const GURL& WebContentsImpl::GetMainFrameLastCommittedURL() {
[email protected]c31a84802014-04-03 15:55:496571 return GetLastCommittedURL();
6572}
6573
[email protected]b849847b2013-12-10 21:57:586574void WebContentsImpl::RenderFrameCreated(RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:376575 TRACE_EVENT1("content", "WebContentsImpl::RenderFrameCreated",
6576 "render_frame_host", render_frame_host);
Alexander Timin90c20c32020-08-12 15:28:326577 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6578 observer->RenderFrameCreated(render_frame_host);
6579 });
dmazzonif8a31042016-12-03 00:52:136580 UpdateAccessibilityModeOnFrame(render_frame_host);
clamy91b7abf2016-03-24 15:17:456581
Becca Hughesd11d6502018-07-31 17:01:286582 if (display_cutout_host_impl_)
6583 display_cutout_host_impl_->RenderFrameCreated(render_frame_host);
6584
clamy91b7abf2016-03-24 15:17:456585 if (!render_frame_host->IsRenderFrameLive() || render_frame_host->GetParent())
6586 return;
6587
6588 NavigationEntry* entry = controller_.GetPendingEntry();
6589 if (entry && entry->IsViewSourceMode()) {
6590 // Put the renderer in view source mode.
Dave Tapuska3c05e1c2019-11-27 18:34:186591 static_cast<RenderFrameHostImpl*>(render_frame_host)
6592 ->GetAssociatedLocalFrame()
6593 ->EnableViewSourceMode();
clamy91b7abf2016-03-24 15:17:456594 }
[email protected]b849847b2013-12-10 21:57:586595}
6596
6597void WebContentsImpl::RenderFrameDeleted(RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:376598 TRACE_EVENT1("content", "WebContentsImpl::RenderFrameDeleted",
6599 "render_frame_host",
6600 base::trace_event::ToTracedValue(render_frame_host));
yilkal172da772019-11-06 22:49:076601 if (IsBeingDestroyed() && !render_frame_host->GetParent() &&
6602 first_navigation_completed_ &&
Hajime Hoshibbc509c2020-04-06 08:55:086603 !render_frame_host->IsInBackForwardCache()) {
yilkal796e89e2019-10-02 23:58:286604 // Main frame has been deleted because WebContents is being destroyed.
Rakina Zata Amni74627df2019-10-15 02:03:176605 // Note that we aren't recording this here when the main frame is in the
6606 // back-forward cache because that means we've actually already navigated
6607 // away from it (and we got to this point because the WebContents is
yilkal172da772019-11-06 22:49:076608 // deleted), which means |max_loaded_frame_count_| is already overwritten.
6609 // The |max_loaded_frame_count_| value will instead be recorded from within
6610 // |WebContentsImpl::DidFinishNavigation()|.
6611 RecordMaxFrameCountUMA(max_loaded_frame_count_);
yilkal796e89e2019-10-02 23:58:286612 }
6613
Alexander Timin90c20c32020-08-12 15:28:326614 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6615 observer->RenderFrameDeleted(render_frame_host);
6616 });
zqzhang7b6f4f02016-12-07 22:10:226617#if BUILDFLAG(ENABLE_PLUGINS)
6618 pepper_playback_observer_->RenderFrameDeleted(render_frame_host);
6619#endif
Becca Hughesfd5d8f892018-06-14 18:23:366620
Becca Hughesd11d6502018-07-31 17:01:286621 if (display_cutout_host_impl_)
6622 display_cutout_host_impl_->RenderFrameDeleted(render_frame_host);
6623
Becca Hughesfd5d8f892018-06-14 18:23:366624 // Remove any fullscreen state that the frame has stored.
6625 FullscreenStateChanged(render_frame_host, false /* is_fullscreen */);
[email protected]b849847b2013-12-10 21:57:586626}
6627
[email protected]a09d53ce2014-01-31 00:46:426628void WebContentsImpl::ShowContextMenu(RenderFrameHost* render_frame_host,
6629 const ContextMenuParams& params) {
Alexander Timin5fdeff22020-09-08 09:20:376630 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ShowContextMenu",
6631 "render_frame_host",
6632 base::trace_event::ToTracedValue(render_frame_host));
avie9fd8722017-04-10 16:17:586633 // If a renderer fires off a second command to show a context menu before the
6634 // first context menu is closed, just ignore it. https://crbug.com/707534
ekaramadf6750aa2017-06-06 18:29:426635 if (showing_context_menu_)
avie9fd8722017-04-10 16:17:586636 return;
6637
[email protected]077e704b2014-05-23 19:24:106638 ContextMenuParams context_menu_params(params);
[email protected]a09d53ce2014-01-31 00:46:426639 // Allow WebContentsDelegates to handle the context menu operation first.
Joel Klinghed0ea22ea2019-02-20 22:04:226640 if (delegate_ &&
6641 delegate_->HandleContextMenu(render_frame_host, context_menu_params))
[email protected]a09d53ce2014-01-31 00:46:426642 return;
6643
[email protected]077e704b2014-05-23 19:24:106644 render_view_host_delegate_view_->ShowContextMenu(render_frame_host,
6645 context_menu_params);
[email protected]a09d53ce2014-01-31 00:46:426646}
6647
Avi Drissman4891b852018-09-25 18:12:586648namespace {
6649// Normalizes the line endings: \r\n -> \n, lone \r -> \n.
6650base::string16 NormalizeLineBreaks(const base::string16& source) {
6651 static const base::NoDestructor<base::string16> kReturnNewline(
6652 base::ASCIIToUTF16("\r\n"));
6653 static const base::NoDestructor<base::string16> kReturn(
6654 base::ASCIIToUTF16("\r"));
6655 static const base::NoDestructor<base::string16> kNewline(
6656 base::ASCIIToUTF16("\n"));
6657
6658 std::vector<base::StringPiece16> pieces;
6659
6660 for (const auto& rn_line : base::SplitStringPieceUsingSubstr(
6661 source, *kReturnNewline, base::KEEP_WHITESPACE,
6662 base::SPLIT_WANT_ALL)) {
6663 auto r_lines = base::SplitStringPieceUsingSubstr(
6664 rn_line, *kReturn, base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
6665 std::move(std::begin(r_lines), std::end(r_lines),
6666 std::back_inserter(pieces));
6667 }
6668
6669 return base::JoinString(pieces, *kNewline);
6670}
6671} // namespace
6672
Dave Tapuskacdf545cc2020-01-23 18:38:526673void WebContentsImpl::RunJavaScriptDialog(
6674 RenderFrameHost* render_frame_host,
6675 const base::string16& message,
6676 const base::string16& default_prompt,
6677 JavaScriptDialogType dialog_type,
6678 JavaScriptDialogCallback response_callback) {
Alexander Timin5fdeff22020-09-08 09:20:376679 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RunJavaScriptDialog",
6680 "render_frame_host",
6681 base::trace_event::ToTracedValue(render_frame_host));
Avi Drissman2ccbb402018-03-20 21:11:366682 // Ensure that if showing a dialog is the first thing that a page does, that
6683 // the contents of the previous page aren't shown behind it. This is required
6684 // because showing a dialog freezes the renderer, so no frames will be coming
6685 // from it. https://crbug.com/823353
6686 auto* render_widget_host_impl =
6687 static_cast<RenderFrameHostImpl*>(render_frame_host)
6688 ->GetRenderWidgetHost();
6689 if (render_widget_host_impl)
6690 render_widget_host_impl->ForceFirstFrameAfterNavigationTimeout();
6691
avi0720b02e2017-06-13 03:22:136692 // Running a dialog causes an exit to webpage-initiated fullscreen.
6693 // http://crbug.com/728276
Avi Drissman1a55a9d62020-03-10 18:56:456694 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
avi0720b02e2017-06-13 03:22:136695
Avi Drissman1a55a9d62020-03-10 18:56:456696 auto callback =
6697 base::BindOnce(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
6698 render_frame_host->GetProcess()->GetID(),
6699 render_frame_host->GetRoutingID(),
6700 std::move(response_callback), std::move(fullscreen_block));
Pavel Feldman3c1842b2017-08-02 05:00:166701
Pavel Feldman3c1842b2017-08-02 05:00:166702 std::vector<protocol::PageHandler*> page_handlers =
6703 protocol::PageHandler::EnabledForWebContents(this);
6704
Pavel Feldmanfab3cb62017-10-05 01:02:016705 if (delegate_)
6706 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
6707
Charlie Reis96077362019-07-04 00:34:046708 // While a JS message dialog is showing, defer commits in this WebContents.
6709 javascript_dialog_navigation_deferrer_ =
6710 std::make_unique<JavaScriptDialogNavigationDeferrer>();
6711
Carlos IL07f282f2020-05-15 22:58:296712 // Suppress JavaScript dialogs when requested.
6713 bool should_suppress = delegate_ && delegate_->ShouldSuppressDialogs(this);
Pavel Feldman1c587bc52018-04-04 21:16:056714 bool has_non_devtools_handlers = delegate_ && dialog_manager_;
6715 bool has_handlers = page_handlers.size() || has_non_devtools_handlers;
Pavel Feldmanfab3cb62017-10-05 01:02:016716 bool suppress_this_message = should_suppress || !has_handlers;
6717
6718 if (suppress_this_message) {
Avi Drissmane04d3992017-10-05 15:11:366719 std::move(callback).Run(true, false, base::string16());
Pavel Feldman3c1842b2017-08-02 05:00:166720 return;
6721 }
6722
6723 scoped_refptr<CloseDialogCallbackWrapper> wrapper =
Avi Drissmane04d3992017-10-05 15:11:366724 new CloseDialogCallbackWrapper(std::move(callback));
Pavel Feldman3c1842b2017-08-02 05:00:166725
6726 is_showing_javascript_dialog_ = true;
6727
Avi Drissman4891b852018-09-25 18:12:586728 base::string16 normalized_message = NormalizeLineBreaks(message);
6729
Pavel Feldman3c1842b2017-08-02 05:00:166730 for (auto* handler : page_handlers) {
Avi Drissmane04d3992017-10-05 15:11:366731 handler->DidRunJavaScriptDialog(
Avi Drissman4891b852018-09-25 18:12:586732 render_frame_host->GetLastCommittedURL(), normalized_message,
6733 default_prompt, dialog_type, has_non_devtools_handlers,
Avi Drissmane04d3992017-10-05 15:11:366734 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
Pavel Feldman3c1842b2017-08-02 05:00:166735 }
6736
6737 if (dialog_manager_) {
[email protected]87de04b02014-04-08 22:14:496738 dialog_manager_->RunJavaScriptDialog(
Avi Drissman4891b852018-09-25 18:12:586739 this, render_frame_host, dialog_type, normalized_message,
6740 default_prompt,
Avi Drissmane04d3992017-10-05 15:11:366741 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false),
6742 &suppress_this_message);
[email protected]87de04b02014-04-08 22:14:496743 }
6744
6745 if (suppress_this_message) {
6746 // If we are suppressing messages, just reply as if the user immediately
6747 // pressed "Cancel", passing true to |dialog_was_suppressed|.
Avi Drissmane04d3992017-10-05 15:11:366748 wrapper->Run(true, false, base::string16());
[email protected]87de04b02014-04-08 22:14:496749 }
[email protected]87de04b02014-04-08 22:14:496750}
6751
6752void WebContentsImpl::RunBeforeUnloadConfirm(
[email protected]39f2f9252014-05-03 00:54:016753 RenderFrameHost* render_frame_host,
[email protected]87de04b02014-04-08 22:14:496754 bool is_reload,
Dave Tapuskacdf545cc2020-01-23 18:38:526755 JavaScriptDialogCallback response_callback) {
Alexander Timin5fdeff22020-09-08 09:20:376756 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RunBeforeUnloadConfirm",
6757 "render_frame_host",
6758 base::trace_event::ToTracedValue(render_frame_host),
6759 "is_reload", is_reload);
Avi Drissman2ccbb402018-03-20 21:11:366760 // Ensure that if showing a dialog is the first thing that a page does, that
6761 // the contents of the previous page aren't shown behind it. This is required
6762 // because showing a dialog freezes the renderer, so no frames will be coming
6763 // from it. https://crbug.com/823353
6764 auto* render_widget_host_impl =
6765 static_cast<RenderFrameHostImpl*>(render_frame_host)
6766 ->GetRenderWidgetHost();
6767 if (render_widget_host_impl)
6768 render_widget_host_impl->ForceFirstFrameAfterNavigationTimeout();
6769
avi0720b02e2017-06-13 03:22:136770 // Running a dialog causes an exit to webpage-initiated fullscreen.
6771 // http://crbug.com/728276
Avi Drissman1a55a9d62020-03-10 18:56:456772 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
avi0720b02e2017-06-13 03:22:136773
[email protected]39f2f9252014-05-03 00:54:016774 RenderFrameHostImpl* rfhi =
6775 static_cast<RenderFrameHostImpl*>(render_frame_host);
[email protected]87de04b02014-04-08 22:14:496776 if (delegate_)
6777 delegate_->WillRunBeforeUnloadConfirm();
6778
Avi Drissman1a55a9d62020-03-10 18:56:456779 auto callback =
6780 base::BindOnce(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
6781 render_frame_host->GetProcess()->GetID(),
6782 render_frame_host->GetRoutingID(),
6783 std::move(response_callback), std::move(fullscreen_block));
Pavel Feldman3c1842b2017-08-02 05:00:166784
Pavel Feldman3c1842b2017-08-02 05:00:166785 std::vector<protocol::PageHandler*> page_handlers =
6786 protocol::PageHandler::EnabledForWebContents(this);
6787
Pavel Feldmanfab3cb62017-10-05 01:02:016788 if (delegate_)
6789 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
6790
Charlie Reis96077362019-07-04 00:34:046791 // While a JS beforeunload dialog is showing, defer commits in this
6792 // WebContents.
6793 javascript_dialog_navigation_deferrer_ =
6794 std::make_unique<JavaScriptDialogNavigationDeferrer>();
6795
Sreeja Kamishettyf352e302020-06-10 13:21:246796 bool should_suppress = !rfhi->IsCurrent() ||
Tarun Bansalc209b742019-12-24 06:53:256797 (delegate_ && delegate_->ShouldSuppressDialogs(this));
Pavel Feldman1c587bc52018-04-04 21:16:056798 bool has_non_devtools_handlers = delegate_ && dialog_manager_;
6799 bool has_handlers = page_handlers.size() || has_non_devtools_handlers;
Pavel Feldmanfab3cb62017-10-05 01:02:016800 if (should_suppress || !has_handlers) {
Avi Drissmane04d3992017-10-05 15:11:366801 std::move(callback).Run(false, true, base::string16());
[email protected]87de04b02014-04-08 22:14:496802 return;
6803 }
6804
6805 is_showing_before_unload_dialog_ = true;
Pavel Feldman3c1842b2017-08-02 05:00:166806
6807 scoped_refptr<CloseDialogCallbackWrapper> wrapper =
Avi Drissmane04d3992017-10-05 15:11:366808 new CloseDialogCallbackWrapper(std::move(callback));
Pavel Feldman3c1842b2017-08-02 05:00:166809
6810 GURL frame_url = rfhi->GetLastCommittedURL();
6811 for (auto* handler : page_handlers) {
Avi Drissmane04d3992017-10-05 15:11:366812 handler->DidRunBeforeUnloadConfirm(
Pavel Feldman1c587bc52018-04-04 21:16:056813 frame_url, has_non_devtools_handlers,
Avi Drissmane04d3992017-10-05 15:11:366814 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
Pavel Feldman3c1842b2017-08-02 05:00:166815 }
6816
6817 if (dialog_manager_) {
Avi Drissmane04d3992017-10-05 15:11:366818 dialog_manager_->RunBeforeUnloadDialog(
Avi Drissmanff9ed752017-11-28 21:18:126819 this, render_frame_host, is_reload,
Avi Drissmane04d3992017-10-05 15:11:366820 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
Pavel Feldman3c1842b2017-08-02 05:00:166821 }
[email protected]87de04b02014-04-08 22:14:496822}
6823
Kent Tamurac260c9a2018-09-14 09:10:566824void WebContentsImpl::RunFileChooser(
6825 RenderFrameHost* render_frame_host,
Kent Tamura3abb32d2020-07-02 00:23:016826 scoped_refptr<FileChooserImpl::FileSelectListenerImpl> listener,
Kent Tamurac260c9a2018-09-14 09:10:566827 const blink::mojom::FileChooserParams& params) {
Alexander Timin5fdeff22020-09-08 09:20:376828 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RunFileChooser",
6829 "render_frame_host",
6830 base::trace_event::ToTracedValue(render_frame_host));
Avi Drissman3d41e7712018-08-27 21:18:086831 // Any explicit focusing of another window while this WebContents is in
6832 // fullscreen can be used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:456833 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
6834 listener->SetFullscreenBlock(std::move(fullscreen_block));
Avi Drissman3d41e7712018-08-27 21:18:086835
naskoada75b22016-06-11 16:09:466836 if (delegate_)
Kent Tamura512a27e2018-10-04 00:49:326837 delegate_->RunFileChooser(render_frame_host, std::move(listener), params);
6838 else
6839 listener->FileSelectionCanceled();
naskoada75b22016-06-11 16:09:466840}
6841
[email protected]a86c0e962013-12-17 17:10:396842WebContents* WebContentsImpl::GetAsWebContents() {
6843 return this;
6844}
6845
mcnee336ea2c2017-05-23 22:50:596846#if !defined(OS_ANDROID)
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416847double WebContentsImpl::GetPendingPageZoomLevel() {
wjmaclean64951902016-04-29 20:59:126848 NavigationEntry* pending_entry = GetController().GetPendingEntry();
6849 if (!pending_entry)
6850 return HostZoomMap::GetZoomLevel(this);
6851
6852 GURL url = pending_entry->GetURL();
6853 return HostZoomMap::GetForWebContents(this)->GetZoomLevelForHostAndScheme(
6854 url.scheme(), net::GetHostOrSpecFromURL(url));
6855}
mcnee336ea2c2017-05-23 22:50:596856#endif // !defined(OS_ANDROID)
wjmaclean64951902016-04-29 20:59:126857
qinmin72e8bd02016-10-21 19:35:376858bool WebContentsImpl::HideDownloadUI() const {
6859 return is_overlay_content_;
6860}
6861
mlamouri5cd9ae82017-02-18 11:05:096862bool WebContentsImpl::HasPersistentVideo() const {
6863 return has_persistent_video_;
6864}
6865
Ian Vollick5d5c37f2019-06-19 22:50:576866bool WebContentsImpl::IsSpatialNavigationDisabled() const {
6867 return is_spatial_navigation_disabled_;
6868}
6869
Albert J. Wong65fe64d2019-09-20 02:48:146870RenderFrameHostImpl* WebContentsImpl::GetPendingMainFrame() {
clamy610c63b32017-12-22 15:05:186871 return GetRenderManager()->speculative_frame_host();
Alex Moshchuk27caae82017-09-11 23:11:186872}
6873
mlamourie52c1b542017-02-23 14:57:506874bool WebContentsImpl::HasActiveEffectivelyFullscreenVideo() const {
6875 return media_web_contents_observer_->HasActiveEffectivelyFullscreenVideo();
6876}
6877
François Beaufortad6c5232018-02-26 11:00:446878bool WebContentsImpl::IsPictureInPictureAllowedForFullscreenVideo() const {
6879 return media_web_contents_observer_
6880 ->IsPictureInPictureAllowedForFullscreenVideo();
6881}
6882
ekaramada110f642016-12-21 19:47:286883bool WebContentsImpl::IsFocusedElementEditable() {
6884 RenderFrameHostImpl* frame = GetFocusedFrame();
6885 return frame && frame->has_focused_editable_element();
6886}
6887
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416888bool WebContentsImpl::IsShowingContextMenu() {
ekaramadf6750aa2017-06-06 18:29:426889 return showing_context_menu_;
6890}
6891
6892void WebContentsImpl::SetShowingContextMenu(bool showing) {
Alexander Timin5fdeff22020-09-08 09:20:376893 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetShowingContextMenu",
6894 "showing", showing);
6895
ekaramadf6750aa2017-06-06 18:29:426896 DCHECK_NE(showing_context_menu_, showing);
6897 showing_context_menu_ = showing;
6898
6899 if (auto* view = GetRenderWidgetHostView()) {
6900 // Notify the main frame's RWHV to run the platform-specific code, if any.
6901 static_cast<RenderWidgetHostViewBase*>(view)->SetShowingContextMenu(
6902 showing);
6903 }
6904}
6905
ekaramada110f642016-12-21 19:47:286906void WebContentsImpl::ClearFocusedElement() {
Alexander Timin5fdeff22020-09-08 09:20:376907 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ClearFocusedElement");
ekaramada110f642016-12-21 19:47:286908 if (auto* frame = GetFocusedFrame())
6909 frame->ClearFocusedElement();
6910}
6911
danakj77eb7e82020-01-09 19:38:466912bool WebContentsImpl::IsNeverComposited() {
[email protected]7912e822014-04-16 02:37:036913 if (!delegate_)
6914 return false;
danakj77eb7e82020-01-09 19:38:466915 return delegate_->IsNeverComposited(this);
[email protected]7912e822014-04-16 02:37:036916}
6917
[email protected]5a3bdf52012-05-24 15:12:576918RenderViewHostDelegateView* WebContentsImpl::GetDelegateView() {
6919 return render_view_host_delegate_view_;
[email protected]420ae012009-04-24 05:16:326920}
6921
Peter Marshall2dc74e92020-07-29 20:02:306922blink::mojom::RendererPreferences WebContentsImpl::GetRendererPrefs() const {
[email protected]840b1512009-07-21 16:53:466923 return renderer_preferences_;
[email protected]80d96fa2009-06-10 22:34:516924}
6925
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166926RenderFrameHostImpl* WebContentsImpl::GetOuterWebContentsFrame() {
6927 if (GetOuterDelegateFrameTreeNodeId() ==
6928 FrameTreeNode::kFrameTreeNodeInvalidId) {
6929 return nullptr;
6930 }
6931
6932 FrameTreeNode* outer_node =
6933 FrameTreeNode::GloballyFindByID(GetOuterDelegateFrameTreeNodeId());
6934 // The outer node should be in the outer WebContents.
6935 DCHECK_EQ(outer_node->frame_tree(), GetOuterWebContents()->GetFrameTree());
Alexander Timin381e7e182020-04-28 19:04:036936 return outer_node->parent();
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166937}
6938
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416939WebContentsImpl* WebContentsImpl::GetOuterWebContents() {
Lucas Furukawa Gadani105de1e812018-05-31 19:38:396940 return node_.outer_web_contents();
avallee0206f782016-07-28 18:55:336941}
6942
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166943std::vector<WebContents*> WebContentsImpl::GetInnerWebContents() {
6944 std::vector<WebContents*> all_inner_contents;
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166945 const auto& inner_contents = node_.GetInnerWebContents();
6946 all_inner_contents.insert(all_inner_contents.end(), inner_contents.begin(),
6947 inner_contents.end());
6948 return all_inner_contents;
6949}
6950
Jeremy Roman7e70bf92020-01-07 23:23:586951WebContentsImpl* WebContentsImpl::GetResponsibleWebContents() {
6952 // Iteratively ask delegates which other contents is responsible until a fixed
6953 // point is found.
6954 WebContentsImpl* contents = this;
6955 while (WebContentsDelegate* delegate = contents->GetDelegate()) {
6956 auto* responsible_contents = static_cast<WebContentsImpl*>(
6957 delegate->GetResponsibleWebContents(contents));
6958 if (responsible_contents == contents)
6959 break;
6960 contents = responsible_contents;
6961 }
6962 return contents;
6963}
6964
avallee0206f782016-07-28 18:55:336965WebContentsImpl* WebContentsImpl::GetFocusedWebContents() {
lfg601233692017-03-06 22:45:446966 return GetOutermostWebContents()->node_.focused_web_contents();
avallee0206f782016-07-28 18:55:336967}
6968
avallee9993fca2016-11-17 06:16:506969bool WebContentsImpl::ContainsOrIsFocusedWebContents() {
6970 for (WebContentsImpl* focused_contents = GetFocusedWebContents();
6971 focused_contents;
6972 focused_contents = focused_contents->GetOuterWebContents()) {
6973 if (focused_contents == this)
6974 return true;
6975 }
6976
6977 return false;
6978}
6979
W. James MacLean9437b5bf2019-12-06 17:33:446980void WebContentsImpl::RemoveBrowserPluginEmbedder() {
Alexander Timin5fdeff22020-09-08 09:20:376981 OPTIONAL_TRACE_EVENT0("content",
6982 "WebContentsImpl::RemoveBrowserPluginEmbedder");
W. James MacLean9437b5bf2019-12-06 17:33:446983 browser_plugin_embedder_.reset();
6984}
6985
avallee0206f782016-07-28 18:55:336986WebContentsImpl* WebContentsImpl::GetOutermostWebContents() {
6987 WebContentsImpl* root = this;
6988 while (root->GetOuterWebContents())
6989 root = root->GetOuterWebContents();
6990 return root;
6991}
6992
avalleed68cdd12017-06-21 22:07:276993void WebContentsImpl::FocusOuterAttachmentFrameChain() {
Alexander Timin5fdeff22020-09-08 09:20:376994 OPTIONAL_TRACE_EVENT0("content",
6995 "WebContentsImpl::FocusOuterAttachmentFrameChain");
avalleed68cdd12017-06-21 22:07:276996 WebContentsImpl* outer_contents = GetOuterWebContents();
6997 if (!outer_contents)
6998 return;
6999
7000 FrameTreeNode* outer_node =
7001 FrameTreeNode::GloballyFindByID(GetOuterDelegateFrameTreeNodeId());
7002 outer_contents->frame_tree_.SetFocusedFrame(outer_node, nullptr);
7003
7004 // For a browser initiated focus change, let embedding renderer know of the
7005 // change. Otherwise, if the currently focused element is just across a
7006 // process boundary in focus order, it will not be possible to move across
7007 // that boundary. This is because the target element will already be focused
7008 // (that renderer was not notified) and drop the event.
7009 if (GetRenderManager()->GetProxyToOuterDelegate())
7010 GetRenderManager()->GetProxyToOuterDelegate()->SetFocusedFrame();
7011
7012 outer_contents->FocusOuterAttachmentFrameChain();
7013}
7014
Sean Toppingbbc4a2bd2019-01-30 02:16:147015void WebContentsImpl::InnerWebContentsCreated(WebContents* inner_web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:377016 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::InnerWebContentsCreated");
Alexander Timin90c20c32020-08-12 15:28:327017 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7018 observer->InnerWebContentsCreated(inner_web_contents);
7019 });
Sean Toppingbbc4a2bd2019-01-30 02:16:147020}
7021
Jeremy Roman03ce13ce2020-05-29 22:16:577022void WebContentsImpl::InnerWebContentsAttached(
7023 WebContents* inner_web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:377024 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::InnerWebContentsDetached");
Jeremy Roman03ce13ce2020-05-29 22:16:577025 if (inner_web_contents->IsCurrentlyAudible())
7026 OnAudioStateChanged();
7027}
7028
7029void WebContentsImpl::InnerWebContentsDetached(
7030 WebContents* inner_web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:377031 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::InnerWebContentsCreated");
Jeremy Roman03ce13ce2020-05-29 22:16:577032 if (!is_being_destroyed_)
7033 OnAudioStateChanged();
7034}
7035
[email protected]b172aee2012-04-10 17:05:267036void WebContentsImpl::RenderViewCreated(RenderViewHost* render_view_host) {
Alexander Timin5fdeff22020-09-08 09:20:377037 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderViewCreated",
7038 "render_view_host", render_view_host);
[email protected]86f98a22013-03-20 14:35:007039 if (delegate_)
[email protected]e85165c642014-06-10 14:34:317040 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
[email protected]a6b73c62013-02-11 23:05:087041
[email protected]8ff00d72012-10-23 19:12:217042 NotificationService::current()->Notify(
7043 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
7044 Source<WebContents>(this),
7045 Details<RenderViewHost>(render_view_host));
[email protected]420ae012009-04-24 05:16:327046
Alexander Timin90c20c32020-08-12 15:28:327047 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7048 observer->RenderViewCreated(render_view_host);
7049 });
Joel Einbinder848001c2017-09-19 21:39:317050 if (delegate_)
7051 RenderFrameDevToolsAgentHost::WebContentsCreated(this);
[email protected]420ae012009-04-24 05:16:327052}
7053
[email protected]b172aee2012-04-10 17:05:267054void WebContentsImpl::RenderViewReady(RenderViewHost* rvh) {
Alexander Timin5fdeff22020-09-08 09:20:377055 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderViewReady",
7056 "render_view_host", rvh);
[email protected]151a63d2011-12-20 22:32:527057 if (rvh != GetRenderViewHost()) {
[email protected]420ae012009-04-24 05:16:327058 // Don't notify the world, since this came from a renderer in the
7059 // background.
7060 return;
7061 }
7062
dmazzoni62111452017-04-28 23:46:557063 RenderWidgetHostViewBase* rwhv =
7064 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
7065 if (rwhv)
7066 rwhv->SetMainFrameAXTreeID(GetMainFrame()->GetAXTreeID());
7067
[email protected]da7a7182013-09-06 08:11:117068 notify_disconnection_ = true;
[email protected]da7a7182013-09-06 08:11:117069
[email protected]be1f56ab2011-12-22 06:55:317070 bool was_crashed = IsCrashed();
[email protected]443b80e2010-12-14 00:42:237071 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING, 0);
[email protected]9d8a4642009-07-29 17:25:307072
7073 // Restore the focus to the tab (otherwise the focus will be on the top
7074 // window).
[email protected]484ae5912010-09-29 19:16:147075 if (was_crashed && !FocusLocationBarByDefault() &&
7076 (!delegate_ || delegate_->ShouldFocusPageAfterCrash())) {
[email protected]f3615f02013-02-26 06:09:067077 view_->Focus();
[email protected]484ae5912010-09-29 19:16:147078 }
[email protected]32ded2212011-11-10 18:51:437079
Alexander Timin90c20c32020-08-12 15:28:327080 observers_.ForEachObserver(
7081 [&](WebContentsObserver* observer) { observer->RenderViewReady(); });
Jinsuk Kim895b2c52018-07-03 06:49:167082 view_->RenderViewReady();
[email protected]420ae012009-04-24 05:16:327083}
7084
[email protected]ec6a7eb2013-04-22 17:34:227085void WebContentsImpl::RenderViewTerminated(RenderViewHost* rvh,
7086 base::TerminationStatus status,
7087 int error_code) {
Alexander Timin5fdeff22020-09-08 09:20:377088 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RenderViewTerminated",
7089 "render_view_host", rvh, "status",
7090 static_cast<int>(status));
[email protected]151a63d2011-12-20 22:32:527091 if (rvh != GetRenderViewHost()) {
[email protected]420ae012009-04-24 05:16:327092 // The pending page's RenderViewHost is gone.
7093 return;
7094 }
[email protected]2fcdcc32014-03-05 02:14:077095 // Ensure fullscreen mode is exited in the |delegate_| since a crashed
7096 // renderer may not have made a clean exit.
Avi Drissman97aef042020-06-30 21:04:487097 if (IsFullscreen())
bokanece34a82016-01-28 19:49:467098 ExitFullscreenMode(false);
[email protected]2fcdcc32014-03-05 02:14:077099
Jennifer Apacibleb4b972a2018-06-07 04:41:027100 // Ensure any video in Picture-in-Picture is exited in the |delegate_| since
7101 // a crashed renderer may not have made a clean exit.
7102 if (HasPictureInPictureVideo())
7103 ExitPictureInPicture();
7104
[email protected]698191dc2014-02-25 01:06:137105 // Cancel any visible dialogs so they are not left dangling over the sad tab.
creis89a0f782015-05-27 16:13:177106 CancelActiveAndPendingDialogs();
[email protected]698191dc2014-02-25 01:06:137107
dalecurtis3d1e1302017-02-20 22:33:257108 audio_stream_monitor_.RenderProcessGone(rvh->GetProcess()->GetID());
7109
[email protected]960b0372014-05-19 18:01:007110 // Reset the loading progress. TODO(avi): What does it mean to have a
7111 // "renderer crash" when there is more than one renderer process serving a
7112 // webpage? Once this function is called at a more granular frame level, we
7113 // probably will need to more granularly reset the state here.
7114 ResetLoadProgressState();
clamy44e84ce2016-02-22 15:38:257115 NotifyDisconnected();
7116 SetIsCrashed(status, error_code);
[email protected]960b0372014-05-19 18:01:007117
Alexander Timin5fdeff22020-09-08 09:20:377118 TRACE_EVENT0("content",
7119 "Dispatching WebContentsObserver::RenderViewTerminated");
Alexander Timin90c20c32020-08-12 15:28:327120 // Some observers might destroy WebContents in RenderViewTerminated.
7121 base::WeakPtr<WebContentsImpl> weak_ptr = weak_factory_.GetWeakPtr();
7122 auto crashed_status = GetCrashedStatus();
7123 for (auto& observer : observers_.observer_list()) {
7124 observer.RenderProcessGone(crashed_status);
7125 if (!weak_ptr)
7126 return;
7127 }
7128
7129 // |this| might have been deleted. Do not add code here.
[email protected]420ae012009-04-24 05:16:327130}
7131
[email protected]b172aee2012-04-10 17:05:267132void WebContentsImpl::RenderViewDeleted(RenderViewHost* rvh) {
Alexander Timin5fdeff22020-09-08 09:20:377133 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderViewDeleted",
7134 "render_view_host", rvh);
Alexander Timin90c20c32020-08-12 15:28:327135 observers_.ForEachObserver(
7136 [&](WebContentsObserver* observer) { observer->RenderViewDeleted(rvh); });
[email protected]2e4633c2009-07-09 16:58:067137}
7138
Lukasz Anforowiczfd707142018-02-07 19:46:137139void WebContentsImpl::ClearTargetURL() {
Alexander Timin5fdeff22020-09-08 09:20:377140 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ClearTargetURL");
Mario Sanchez Pradadffbe66e2020-09-07 12:01:087141 frame_that_set_last_target_url_ = nullptr;
Lukasz Anforowiczfd707142018-02-07 19:46:137142 if (delegate_)
7143 delegate_->UpdateTargetURL(this, GURL());
7144}
7145
[email protected]b172aee2012-04-10 17:05:267146void WebContentsImpl::Close(RenderViewHost* rvh) {
Alexander Timin5fdeff22020-09-08 09:20:377147 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::Close", "render_view_host",
7148 rvh);
Avi Drissman7c57be72020-07-29 20:09:467149#if defined(OS_MAC)
[email protected]07707302009-11-06 00:50:297150 // The UI may be in an event-tracking loop, such as between the
7151 // mouse-down and mouse-up in text selection or a button click.
7152 // Defer the close until after tracking is complete, so that we
7153 // don't free objects out from under the UI.
[email protected]07707302009-11-06 00:50:297154 // TODO(shess): This could get more fine-grained. For instance,
7155 // closing a tab in another window while selecting text in the
7156 // current window's Omnibox should be just fine.
Christopher Cameron9ae31e0d2019-03-01 20:01:197157 if (view_->CloseTabAfterEventTrackingIfNeeded())
[email protected]07707302009-11-06 00:50:297158 return;
[email protected]60780f412013-02-25 16:34:107159#endif
[email protected]07707302009-11-06 00:50:297160
[email protected]420ae012009-04-24 05:16:327161 // Ignore this if it comes from a RenderViewHost that we aren't showing.
[email protected]151a63d2011-12-20 22:32:527162 if (delegate_ && rvh == GetRenderViewHost())
[email protected]6934a702011-12-20 00:04:517163 delegate_->CloseContents(this);
[email protected]420ae012009-04-24 05:16:327164}
7165
Avi Drissman014dec72018-06-07 02:34:017166void WebContentsImpl::RequestSetBounds(const gfx::Rect& new_bounds) {
Alexander Timin5fdeff22020-09-08 09:20:377167 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::RequestSetBounds");
Mike Wassermandabad612020-08-13 04:26:277168 if (!delegate_)
7169 return;
7170
7171 // Members of |new_bounds| may be 0 to indicate uninitialized values for newly
7172 // opened windows, even if the |GetContainerBounds()| inner rect is correct.
7173 // TODO(crbug.com/897300): Plumb values as specified; fallback on outer rect.
7174 auto bounds = new_bounds;
7175 if (bounds.IsEmpty())
7176 bounds.set_size(GetContainerBounds().size());
7177
7178 // Only requests from the main frame, not subframes, should reach this code.
Mike Wassermanb6bc0152020-08-25 22:46:207179 int64_t display_id = AdjustRequestedWindowBounds(&bounds, GetMainFrame());
7180
7181 // Drop fullscreen when placing a WebContents to prohibit deceptive behavior.
7182 // Only drop fullscreen on the specific destination display, which is known.
7183 // This supports sites using cross-screen window placement capabilities to
7184 // retain fullscreen and place a window on another screen.
7185 ForSecurityDropFullscreen(display_id).RunAndReset();
7186
Mike Wassermandabad612020-08-13 04:26:277187 delegate_->SetContentsBounds(this, bounds);
[email protected]420ae012009-04-24 05:16:327188}
7189
fdegansa696e5112015-04-17 01:57:597190void WebContentsImpl::DidStartLoading(FrameTreeNode* frame_tree_node,
[email protected]e3b10d12014-03-28 16:06:097191 bool to_different_document) {
Alexander Timin5fdeff22020-09-08 09:20:377192 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DidStartLoading",
7193 "frame_tree_node", frame_tree_node);
Evan Stadec3b26022017-07-14 19:50:247194 LoadingStateChanged(frame_tree_node->IsMainFrame() && to_different_document,
Carlos IL07f282f2020-05-15 22:58:297195 nullptr);
dmazzonibf8cec42015-02-08 08:28:087196
Xiyuan Xia2a66b112018-12-06 15:52:167197 // Reset the focus state from DidStartNavigation to false if a new load starts
7198 // afterward, in case loading logic triggers a FocusLocationBarByDefault call.
7199 should_focus_location_bar_by_default_ = false;
Ian Prestcdd843d2020-01-28 18:59:587200
7201 // Notify accessibility that the user is navigating away from the
7202 // current document.
7203 // TODO(domfarolino, dmazzoni): Do this using WebContentsObserver. See
7204 // https://crbug.com/981271.
7205 BrowserAccessibilityManager* manager =
7206 frame_tree_node->current_frame_host()->browser_accessibility_manager();
7207 if (manager)
7208 manager->UserIsNavigatingAway();
[email protected]420ae012009-04-24 05:16:327209}
7210
fdegansc73eec22015-03-19 14:47:547211void WebContentsImpl::DidStopLoading() {
Alexander Timin5fdeff22020-09-08 09:20:377212 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidStopLoading");
dcheng59716272016-04-09 05:19:087213 std::unique_ptr<LoadNotificationDetails> details;
[email protected]420ae012009-04-24 05:16:327214
[email protected]9595fd82013-04-19 21:28:497215 // Use the last committed entry rather than the active one, in case a
7216 // pending entry has been created.
7217 NavigationEntry* entry = controller_.GetLastCommittedEntry();
7218
[email protected]420ae012009-04-24 05:16:327219 // An entry may not exist for a stop when loading an initial blank page or
7220 // if an iframe injected by script into a blank page finishes loading.
7221 if (entry) {
Fergal Daly55b6d722020-09-11 07:56:337222 details = std::make_unique<LoadNotificationDetails>(
7223 entry->GetVirtualURL(), &controller_,
7224 controller_.GetCurrentEntryIndex());
[email protected]420ae012009-04-24 05:16:327225 }
7226
Carlos IL07f282f2020-05-15 22:58:297227 LoadingStateChanged(true, details.get());
[email protected]420ae012009-04-24 05:16:327228}
7229
fdegansa696e5112015-04-17 01:57:597230void WebContentsImpl::DidChangeLoadProgress() {
Alexander Timin5fdeff22020-09-08 09:20:377231 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidChangeLoadProgress");
Nate Chapin22ea6592019-03-05 22:29:027232 if (is_being_destroyed_)
7233 return;
fdegansa696e5112015-04-17 01:57:597234 double load_progress = frame_tree_.load_progress();
7235
7236 // The delegate is notified immediately for the first and last updates. Also,
7237 // since the message loop may be pretty busy when a page is loaded, it might
7238 // not execute a posted task in a timely manner so the progress report is sent
7239 // immediately if enough time has passed.
7240 base::TimeDelta min_delay =
7241 base::TimeDelta::FromMilliseconds(kMinimumDelayBetweenLoadingUpdatesMS);
7242 bool delay_elapsed = loading_last_progress_update_.is_null() ||
7243 base::TimeTicks::Now() - loading_last_progress_update_ > min_delay;
7244
7245 if (load_progress == 0.0 || load_progress == 1.0 || delay_elapsed) {
7246 // If there is a pending task to send progress, it is now obsolete.
7247 loading_weak_factory_.InvalidateWeakPtrs();
7248
7249 // Notify the load progress change.
7250 SendChangeLoadProgress();
7251
7252 // Clean-up the states if needed.
7253 if (load_progress == 1.0)
7254 ResetLoadProgressState();
7255 return;
7256 }
7257
7258 if (loading_weak_factory_.HasWeakPtrs())
7259 return;
7260
skyostil95082a62015-06-05 19:53:077261 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
tzike2aca992017-09-05 08:50:547262 FROM_HERE,
7263 base::BindOnce(&WebContentsImpl::SendChangeLoadProgress,
7264 loading_weak_factory_.GetWeakPtr()),
fdegansa696e5112015-04-17 01:57:597265 min_delay);
7266}
7267
avid6d88b912017-01-13 00:16:007268std::vector<std::unique_ptr<NavigationThrottle>>
7269WebContentsImpl::CreateThrottlesForNavigation(
clamycbf524d42016-09-27 12:48:357270 NavigationHandle* navigation_handle) {
Alexander Timin5fdeff22020-09-08 09:20:377271 OPTIONAL_TRACE_EVENT1("content",
7272 "WebContentsImpl::CreateThrottlesForNavigation",
7273 "navigation", navigation_handle);
Charlie Reis96077362019-07-04 00:34:047274 auto throttles = GetContentClient()->browser()->CreateThrottlesForNavigation(
clamycbf524d42016-09-27 12:48:357275 navigation_handle);
Charlie Reis96077362019-07-04 00:34:047276
7277 // This is not a normal place to be adding a throttle. However, in the case
7278 // javascript dialogs, related logic is present in the web_contents/ layer,
7279 // and the purpose of the throttle is to ensure that navigation commits are
7280 // deferred for the entire WebContents. Most throttles are either added by
7281 // the embederrer outside of content/, or are per-frame and added by
7282 // NavigationThrottleRunner.
7283 std::unique_ptr<content::NavigationThrottle> dialog_throttle =
7284 JavaScriptDialogNavigationThrottle::MaybeCreateThrottleFor(
7285 navigation_handle);
7286 if (dialog_throttle)
7287 throttles.push_back(std::move(dialog_throttle));
7288
7289 return throttles;
clamycbf524d42016-09-27 12:48:357290}
7291
clamy1e5574e2016-09-29 16:48:447292std::unique_ptr<NavigationUIData> WebContentsImpl::GetNavigationUIData(
7293 NavigationHandle* navigation_handle) {
Alexander Timin5fdeff22020-09-08 09:20:377294 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GetNavigationUIData");
clamy1e5574e2016-09-29 16:48:447295 return GetContentClient()->browser()->GetNavigationUIData(navigation_handle);
7296}
7297
W. James MacLean1c40862c2020-04-27 21:05:577298void WebContentsImpl::RegisterExistingOriginToPreventOptInIsolation(
W. James MacLeanb70fab82020-05-01 18:51:147299 const url::Origin& origin,
7300 NavigationRequest* navigation_request_to_exclude) {
Alexander Timin5fdeff22020-09-08 09:20:377301 OPTIONAL_TRACE_EVENT2(
7302 "content",
7303 "WebContentsImpl::RegisterExistingOriginToPreventOptInIsolation",
7304 "origin", base::trace_event::ValueToString(origin),
7305 "navigation_request_to_exclude", navigation_request_to_exclude);
W. James MacLean1c40862c2020-04-27 21:05:577306 // Note: This function can be made static if we ever need call it without
7307 // a WebContentsImpl instance, in which case we can use a wrapper to
7308 // implement the override from NavigatorDelegate.
7309 for (WebContentsImpl* web_contents : GetAllWebContents()) {
7310 web_contents->controller_.RegisterExistingOriginToPreventOptInIsolation(
7311 origin);
W. James MacLeanb70fab82020-05-01 18:51:147312 // Walk the frame tree to pick up any frames without FrameNavigationEntries.
7313 // * Some frames won't have FrameNavigationEntries (Issues 524208, 608402).
7314 // * Some pending navigations won't have NavigationEntries.
7315 web_contents->GetFrameTree()->RegisterExistingOriginToPreventOptInIsolation(
7316 origin, navigation_request_to_exclude);
W. James MacLean1c40862c2020-04-27 21:05:577317 }
7318}
7319
pdr15f5b5b2017-06-20 00:58:007320void WebContentsImpl::DidCancelLoading() {
Alexander Timin5fdeff22020-09-08 09:20:377321 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidCancelLoading");
pdr15f5b5b2017-06-20 00:58:007322 controller_.DiscardNonCommittedEntries();
7323
7324 // Update the URL display.
7325 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
7326}
7327
[email protected]59167c22013-06-03 18:07:327328void WebContentsImpl::DidAccessInitialDocument() {
Alexander Timin5fdeff22020-09-08 09:20:377329 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidAccessInitialDocument");
[email protected]b4c84012014-04-28 19:51:107330 has_accessed_initial_document_ = true;
7331
[email protected]d1371bf8e2014-04-19 03:26:247332 // We may have left a failed browser-initiated navigation in the address bar
7333 // to let the user edit it and try again. Clear it now that content might
7334 // show up underneath it.
7335 if (!IsLoading() && controller_.GetPendingEntry())
avi45a72532015-04-07 21:01:457336 controller_.DiscardPendingEntry(false);
[email protected]d1371bf8e2014-04-19 03:26:247337
[email protected]59167c22013-06-03 18:07:327338 // Update the URL display.
thestigc4cac8f2014-09-04 21:17:507339 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
[email protected]59167c22013-06-03 18:07:327340}
7341
alexmosbe2f4c32015-03-10 02:30:237342void WebContentsImpl::DidChangeName(RenderFrameHost* render_frame_host,
7343 const std::string& name) {
Alexander Timin5fdeff22020-09-08 09:20:377344 OPTIONAL_TRACE_EVENT2(
7345 "content", "WebContentsImpl::DidChangeName", "render_frame_host",
7346 base::trace_event::ToTracedValue(render_frame_host), "name", name);
Alexander Timin90c20c32020-08-12 15:28:327347 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7348 observer->FrameNameChanged(render_frame_host, name);
7349 });
alexmosbe2f4c32015-03-10 02:30:237350}
7351
John Delaneyedd8d6c2019-01-25 00:23:577352void WebContentsImpl::DidReceiveFirstUserActivation(
7353 RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:377354 OPTIONAL_TRACE_EVENT1(
7355 "content", "WebContentsImpl::DidReceiveFirstUserActivation",
7356 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host));
Alexander Timin90c20c32020-08-12 15:28:327357 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7358 observer->FrameReceivedFirstUserActivation(render_frame_host);
7359 });
John Delaneyedd8d6c2019-01-25 00:23:577360}
7361
John Delaney0146a742019-01-25 19:25:287362void WebContentsImpl::DidChangeDisplayState(RenderFrameHost* render_frame_host,
7363 bool is_display_none) {
Alexander Timin5fdeff22020-09-08 09:20:377364 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::DidChangeDisplayState",
7365 "render_frame_host",
7366 base::trace_event::ToTracedValue(render_frame_host),
7367 "is_display_none", is_display_none);
Alexander Timin90c20c32020-08-12 15:28:327368 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7369 observer->FrameDisplayStateChanged(render_frame_host, is_display_none);
7370 });
John Delaney0146a742019-01-25 19:25:287371}
7372
7373void WebContentsImpl::FrameSizeChanged(RenderFrameHost* render_frame_host,
7374 const gfx::Size& frame_size) {
Alexander Timin5fdeff22020-09-08 09:20:377375 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::FrameSizeChanged",
7376 "render_frame_host",
7377 base::trace_event::ToTracedValue(render_frame_host));
Alexander Timin90c20c32020-08-12 15:28:327378 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7379 observer->FrameSizeChanged(render_frame_host, frame_size);
7380 });
John Delaney0146a742019-01-25 19:25:287381}
7382
[email protected]39f2f9252014-05-03 00:54:017383void WebContentsImpl::DocumentOnLoadCompleted(
[email protected]50279492014-05-05 23:24:297384 RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:377385 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DocumentOnLoadCompleted",
7386 "render_frame_host",
7387 base::trace_event::ToTracedValue(render_frame_host));
falken52a56e32016-12-08 05:02:407388 ShowInsecureLocalhostWarningIfNeeded();
7389
Alexander Timindd0fa0c52019-11-06 13:03:377390 GetRenderViewHost()->DocumentOnLoadCompletedInMainFrame();
7391
Alexander Timin90c20c32020-08-12 15:28:327392 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7393 observer->DocumentOnLoadCompletedInMainFrame();
7394 });
[email protected]6578fef2013-10-14 02:35:097395
7396 // TODO(avi): Remove. http://crbug.com/170921
[email protected]8ff00d72012-10-23 19:12:217397 NotificationService::current()->Notify(
7398 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
7399 Source<WebContents>(this),
[email protected]50279492014-05-05 23:24:297400 NotificationService::NoDetails());
[email protected]25497492010-09-11 15:15:087401}
7402
creis8eb8ef22015-11-04 22:51:387403void WebContentsImpl::UpdateStateForFrame(RenderFrameHost* render_frame_host,
7404 const PageState& page_state) {
Alexander Timin5fdeff22020-09-08 09:20:377405 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::UpdateStateForFrame",
7406 "render_frame_host",
7407 base::trace_event::ToTracedValue(render_frame_host));
creis8eb8ef22015-11-04 22:51:387408 // The state update affects the last NavigationEntry associated with the given
7409 // |render_frame_host|. This may not be the last committed NavigationEntry (as
7410 // in the case of an UpdateState from a frame being swapped out). We track
7411 // which entry this is in the RenderFrameHost's nav_entry_id.
7412 RenderFrameHostImpl* rfhi =
7413 static_cast<RenderFrameHostImpl*>(render_frame_host);
7414 NavigationEntryImpl* entry =
7415 controller_.GetEntryWithUniqueID(rfhi->nav_entry_id());
7416 if (!entry)
7417 return;
7418
7419 FrameNavigationEntry* frame_entry =
7420 entry->GetFrameEntry(rfhi->frame_tree_node());
7421 if (!frame_entry)
7422 return;
7423
creisd06a9422015-11-11 03:08:457424 // The SiteInstance might not match if we do a cross-process navigation with
7425 // replacement (e.g., auto-subframe), in which case the swap out of the old
7426 // RenderFrameHost runs in the background after the old FrameNavigationEntry
7427 // has already been replaced and destroyed.
7428 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
7429 return;
7430
creis8eb8ef22015-11-04 22:51:387431 if (page_state == frame_entry->page_state())
7432 return; // Nothing to update.
7433
creis0cade2e2017-02-28 06:37:477434 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
nasko34634672016-07-29 18:46:067435
7436 // The document_sequence_number and item_sequence_number recorded in the
7437 // FrameNavigationEntry should not differ from the one coming with the update,
7438 // since it must come from the same document. Do not update it if a difference
7439 // is detected, as this indicates that |frame_entry| is not the correct one.
7440 ExplodedPageState exploded_state;
7441 if (!DecodePageState(page_state.ToEncodedData(), &exploded_state))
7442 return;
7443
7444 if (exploded_state.top.document_sequence_number !=
7445 frame_entry->document_sequence_number() ||
7446 exploded_state.top.item_sequence_number !=
7447 frame_entry->item_sequence_number()) {
7448 return;
7449 }
7450
nasko04a322f25a2016-09-01 00:00:347451 frame_entry->SetPageState(page_state);
creis8eb8ef22015-11-04 22:51:387452 controller_.NotifyEntryChanged(entry);
7453}
7454
[email protected]ef3adfc2014-05-11 00:04:547455void WebContentsImpl::UpdateTitle(RenderFrameHost* render_frame_host,
[email protected]ef3adfc2014-05-11 00:04:547456 const base::string16& title,
7457 base::i18n::TextDirection title_direction) {
Alexander Timin5fdeff22020-09-08 09:20:377458 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::UpdateTitle",
7459 "render_frame_host",
7460 base::trace_event::ToTracedValue(render_frame_host),
7461 "title", base::trace_event::ValueToString(title));
[email protected]ef3adfc2014-05-11 00:04:547462 // Try to find the navigation entry, which might not be the current one.
avi286019ce2015-07-29 01:26:587463 // For example, it might be from a recently swapped out RFH.
avi1edc8552016-10-13 21:37:167464 NavigationEntryImpl* entry = controller_.GetEntryWithUniqueID(
creisad8c31a2016-05-24 17:07:047465 static_cast<RenderFrameHostImpl*>(render_frame_host)->nav_entry_id());
[email protected]ef3adfc2014-05-11 00:04:547466
7467 // We can handle title updates when we don't have an entry in
7468 // UpdateTitleForEntry, but only if the update is from the current RVH.
7469 // TODO(avi): Change to make decisions based on the RenderFrameHost.
avi286019ce2015-07-29 01:26:587470 if (!entry && render_frame_host != GetMainFrame())
[email protected]ef3adfc2014-05-11 00:04:547471 return;
7472
7473 // TODO(evan): make use of title_direction.
7474 // http://code.google.com/p/chromium/issues/detail?id=27094
afakhry6f0c1ec22016-07-14 13:55:137475 UpdateTitleForEntry(entry, title);
[email protected]ef3adfc2014-05-11 00:04:547476}
7477
Mario Sanchez Pradadffbe66e2020-09-07 12:01:087478void WebContentsImpl::UpdateTargetURL(RenderFrameHost* render_frame_host,
7479 const GURL& url) {
Alexander Timin5fdeff22020-09-08 09:20:377480 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::UpdateTargetURL",
7481 "render_frame_host",
7482 base::trace_event::ToTracedValue(render_frame_host),
7483 "url", base::trace_event::ValueToString(url));
Mario Sanchez Pradadffbe66e2020-09-07 12:01:087484 if (fullscreen_widget_routing_id_ != MSG_ROUTING_NONE) {
7485 // If we're in flash fullscreen (i.e. Pepper plugin fullscreen) only update
7486 // the url if it's from the fullscreen renderer.
7487 RenderWidgetHostView* fs = GetFullscreenRenderWidgetHostView();
7488 RenderViewHost* render_view_host = render_frame_host->GetRenderViewHost();
7489 if (fs && fs->GetRenderWidgetHost() != render_view_host->GetWidget())
7490 return;
7491 }
7492
7493 // In case of racey updates from multiple RenderViewHosts, the last URL should
7494 // be shown - see also some discussion in https://crbug.com/807776.
7495 if (!url.is_valid() && render_frame_host != frame_that_set_last_target_url_)
7496 return;
7497 frame_that_set_last_target_url_ =
7498 url.is_valid() ? render_frame_host : nullptr;
7499
7500 if (delegate_)
7501 delegate_->UpdateTargetURL(this, url);
7502}
7503
alexmose7da5a12015-04-09 02:22:167504bool WebContentsImpl::ShouldRouteMessageEvent(
7505 RenderFrameHost* target_rfh,
7506 SiteInstance* source_site_instance) const {
Alexander Timin5fdeff22020-09-08 09:20:377507 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::ShouldRouteMessageEvent",
7508 "render_frame_host",
7509 base::trace_event::ToTracedValue(target_rfh),
7510 "source_site_instance", source_site_instance);
alexmose7da5a12015-04-09 02:22:167511 // Allow the message if this WebContents is dedicated to a browser plugin
7512 // guest.
[email protected]0eba810b2012-10-18 03:19:367513 // Note: This check means that an embedder could theoretically receive a
7514 // postMessage from anyone (not just its own guests). However, this is
7515 // probably not a risk for apps since other pages won't have references
7516 // to App windows.
alexmose7da5a12015-04-09 02:22:167517 return GetBrowserPluginGuest() || GetBrowserPluginEmbedder();
7518}
[email protected]f546640b2012-05-15 00:03:497519
alexmos58729042015-06-18 23:20:007520void WebContentsImpl::EnsureOpenerProxiesExist(RenderFrameHost* source_rfh) {
Alexander Timin5fdeff22020-09-08 09:20:377521 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::EnsureOpenerProxiesExist",
7522 "render_frame_host",
7523 base::trace_event::ToTracedValue(source_rfh));
alexmose7da5a12015-04-09 02:22:167524 WebContentsImpl* source_web_contents = static_cast<WebContentsImpl*>(
7525 WebContents::FromRenderFrameHost(source_rfh));
[email protected]f546640b2012-05-15 00:03:497526
alexmose7da5a12015-04-09 02:22:167527 if (source_web_contents) {
lazyboy6ec48b2a2015-06-29 15:18:147528 // If this message is going to outer WebContents from inner WebContents,
7529 // then we should not create a RenderView. AttachToOuterWebContentsFrame()
7530 // already created a RenderFrameProxyHost for that purpose.
7531 if (GetBrowserPluginEmbedder() &&
W. James MacLean2539adb32019-12-13 00:40:447532 source_web_contents->browser_plugin_guest_) {
lazyboy6ec48b2a2015-06-29 15:18:147533 return;
W. James MacLean2539adb32019-12-13 00:40:447534 }
lazyboy6ec48b2a2015-06-29 15:18:147535
lfg812874d2016-02-09 22:26:137536 if (this != source_web_contents && GetBrowserPluginGuest()) {
naskob3041b98a42016-03-12 04:43:067537 // We create a RenderFrameProxyHost for the embedder in the guest's render
7538 // process but we intentionally do not expose the embedder's opener chain
7539 // to it.
7540 source_web_contents->GetRenderManager()->CreateRenderFrameProxy(
7541 GetSiteInstance());
[email protected]f546640b2012-05-15 00:03:497542 } else {
alexmos58729042015-06-18 23:20:007543 RenderFrameHostImpl* source_rfhi =
7544 static_cast<RenderFrameHostImpl*>(source_rfh);
7545 source_rfhi->frame_tree_node()->render_manager()->CreateOpenerProxies(
alexmos90325cf2015-09-02 17:18:397546 GetSiteInstance(), nullptr);
[email protected]f546640b2012-05-15 00:03:497547 }
7548 }
[email protected]f546640b2012-05-15 00:03:497549}
7550
avallee9993fca2016-11-17 06:16:507551void WebContentsImpl::SetAsFocusedWebContentsIfNecessary() {
Alexander Timin5fdeff22020-09-08 09:20:377552 OPTIONAL_TRACE_EVENT0("content",
7553 "WebContentsImpl::SetAsFocusedWebContentsIfNecessary");
Adithya Srinivasan11af2c52019-12-16 22:52:557554 DCHECK(!portal());
avallee9993fca2016-11-17 06:16:507555 // Only change focus if we are not currently focused.
7556 WebContentsImpl* old_contents = GetFocusedWebContents();
7557 if (old_contents == this)
7558 return;
7559
paulmeyerfeafc2d2017-04-25 21:46:407560 GetOutermostWebContents()->node_.SetFocusedWebContents(this);
7561
avallee9993fca2016-11-17 06:16:507562 // Send a page level blur to the old contents so that it displays inactive UI
7563 // and focus this contents to activate it.
7564 if (old_contents)
7565 old_contents->GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(false);
avalleec2ff1ef2017-01-21 00:12:307566
7567 // Make sure the outer web contents knows our frame is focused. Otherwise, the
7568 // outer renderer could have the element before or after the frame element
7569 // focused which would return early without actually advancing focus.
avalleed68cdd12017-06-21 22:07:277570 FocusOuterAttachmentFrameChain();
avalleec2ff1ef2017-01-21 00:12:307571
Carlos ILd51e7702020-05-07 18:51:397572 GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(true);
avallee9993fca2016-11-17 06:16:507573}
7574
avallee0206f782016-07-28 18:55:337575void WebContentsImpl::SetFocusedFrame(FrameTreeNode* node,
7576 SiteInstance* source) {
Alexander Timin5fdeff22020-09-08 09:20:377577 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetFocusedFrame",
7578 "frame_tree_node", node, "source_site_instance",
7579 source);
Adithya Srinivasan11af2c52019-12-16 22:52:557580 DCHECK(!portal());
avallee0206f782016-07-28 18:55:337581 frame_tree_.SetFocusedFrame(node, source);
avalleed68cdd12017-06-21 22:07:277582
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:577583 if (auto* inner_contents = node_.GetInnerWebContentsInFrame(node)) {
7584 // |this| is an outer WebContents and |node| represents an inner
7585 // WebContents. Transfer the focus to the inner contents if |this| is
7586 // focused.
7587 if (GetFocusedWebContents() == this)
7588 inner_contents->SetAsFocusedWebContentsIfNecessary();
7589 } else if (node_.OuterContentsFrameTreeNode() &&
7590 node_.OuterContentsFrameTreeNode()
7591 ->current_frame_host()
7592 ->GetSiteInstance() == source) {
7593 // |this| is an inner WebContents, |node| is its main FrameTreeNode and
7594 // the outer WebContents FrameTreeNode is at |source|'s SiteInstance.
7595 // Transfer the focus to the inner WebContents if the outer WebContents is
7596 // focused. This branch is used when an inner WebContents is focused through
Lowell Mannersa9530382019-08-01 09:46:577597 // its RenderFrameProxyHost (via FrameFocused mojo call, used to
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:577598 // implement the window.focus() API).
7599 if (GetFocusedWebContents() == GetOuterWebContents())
7600 SetAsFocusedWebContentsIfNecessary();
7601 } else if (!GetOuterWebContents()) {
7602 // This is an outermost WebContents.
7603 SetAsFocusedWebContentsIfNecessary();
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:577604 }
avalleed68cdd12017-06-21 22:07:277605}
7606
Avi Drissman36f801f2018-02-01 20:06:047607void WebContentsImpl::DidCallFocus() {
Alexander Timin5fdeff22020-09-08 09:20:377608 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidCallFocus");
Avi Drissman36f801f2018-02-01 20:06:047609 // Any explicit focusing of another window while this WebContents is in
7610 // fullscreen can be used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:457611 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
7612 // The other contents is independent of this contents, so release the
7613 // fullscreen block.
7614 fullscreen_block.RunAndReset();
Avi Drissman36f801f2018-02-01 20:06:047615}
7616
avalleed68cdd12017-06-21 22:07:277617RenderFrameHost* WebContentsImpl::GetFocusedFrameIncludingInnerWebContents() {
Alexander Timin5fdeff22020-09-08 09:20:377618 OPTIONAL_TRACE_EVENT0(
7619 "content", "WebContentsImpl::GetFocusedFrameIncludingInnerWebContents");
avalleed68cdd12017-06-21 22:07:277620 WebContentsImpl* contents = this;
7621 FrameTreeNode* focused_node = contents->frame_tree_.GetFocusedFrame();
7622
7623 // If there is no focused frame in the outer WebContents, we need to return
7624 // null.
7625 if (!focused_node)
7626 return nullptr;
7627
7628 // If the focused frame is embedding an inner WebContents, we must descend
7629 // into that contents. If the current WebContents does not have a focused
7630 // frame, return the main frame of this contents instead of the focused empty
7631 // frame embedding this contents.
7632 while (true) {
7633 contents = contents->node_.GetInnerWebContentsInFrame(focused_node);
7634 if (!contents)
7635 return focused_node->current_frame_host();
7636
7637 focused_node = contents->frame_tree_.GetFocusedFrame();
7638 if (!focused_node)
7639 return contents->GetMainFrame();
7640 }
avallee0206f782016-07-28 18:55:337641}
7642
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:577643void WebContentsImpl::OnAdvanceFocus(RenderFrameHostImpl* source_rfh) {
Alexander Timin5fdeff22020-09-08 09:20:377644 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnAdvanceFocus",
7645 "render_frame_host",
7646 base::trace_event::ToTracedValue(source_rfh));
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:577647 // When a RenderFrame needs to advance focus to a RenderFrameProxy (by hitting
7648 // TAB), the RenderFrameProxy sends an IPC to RenderFrameProxyHost. When this
7649 // RenderFrameProxyHost represents an inner WebContents, the outer WebContents
7650 // needs to focus the inner WebContents.
7651 if (GetOuterWebContents() &&
7652 GetOuterWebContents() == source_rfh->delegate()->GetAsWebContents() &&
7653 GetFocusedWebContents() == GetOuterWebContents()) {
7654 SetAsFocusedWebContentsIfNecessary();
7655 }
7656}
7657
ekaramada110f642016-12-21 19:47:287658void WebContentsImpl::OnFocusedElementChangedInFrame(
7659 RenderFrameHostImpl* frame,
Emily Stark023dbacc2020-08-27 22:31:407660 const gfx::Rect& bounds_in_root_view,
7661 blink::mojom::FocusType focus_type) {
Alexander Timin5fdeff22020-09-08 09:20:377662 OPTIONAL_TRACE_EVENT1(
7663 "content", "WebContentsImpl::OnFocusedElementChangedInFrame",
7664 "render_frame_host", base::trace_event::ToTracedValue(frame));
ekaramada110f642016-12-21 19:47:287665 RenderWidgetHostViewBase* root_view =
7666 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
7667 if (!root_view || !frame->GetView())
7668 return;
Katie De0131372020-07-09 23:03:107669 // Convert to screen coordinates from window coordinates by adding the
7670 // window's origin.
ekaramada110f642016-12-21 19:47:287671 gfx::Point origin = bounds_in_root_view.origin();
7672 origin += root_view->GetViewBounds().OffsetFromOrigin();
7673 gfx::Rect bounds_in_screen(origin, bounds_in_root_view.size());
7674
7675 root_view->FocusedNodeChanged(frame->has_focused_editable_element(),
7676 bounds_in_screen);
7677
7678 FocusedNodeDetails details = {frame->has_focused_editable_element(),
Emily Stark023dbacc2020-08-27 22:31:407679 bounds_in_screen, focus_type};
ekaramada110f642016-12-21 19:47:287680
7681 // TODO(ekaramad): We should replace this with an observer notification
7682 // (https://crbug.com/675975).
7683 NotificationService::current()->Notify(
7684 NOTIFICATION_FOCUS_CHANGED_IN_PAGE,
7685 Source<RenderViewHost>(GetRenderViewHost()),
7686 Details<FocusedNodeDetails>(&details));
Jeff Fisher709b4c52019-07-29 20:07:347687
Alexander Timin90c20c32020-08-12 15:28:327688 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7689 observer->OnFocusChangedInPage(&details);
7690 });
ekaramada110f642016-12-21 19:47:287691}
7692
Lowell Manners1de5242e2019-04-25 10:18:467693bool WebContentsImpl::DidAddMessageToConsole(
7694 blink::mojom::ConsoleMessageLevel log_level,
7695 const base::string16& message,
7696 int32_t line_no,
7697 const base::string16& source_id) {
Alexander Timin5fdeff22020-09-08 09:20:377698 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DidAddMessageToConsole",
7699 "message", base::trace_event::ValueToString(message));
7700
Alexander Timin90c20c32020-08-12 15:28:327701 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7702 observer->OnDidAddMessageToConsole(log_level, message, line_no, source_id);
7703 });
Alexander Timin5fdeff22020-09-08 09:20:377704
[email protected]a796f202012-05-30 14:14:257705 if (!delegate_)
7706 return false;
Lowell Manners1de5242e2019-04-25 10:18:467707 return delegate_->DidAddMessageToConsole(this, log_level, message, line_no,
avia90ae4e2016-11-11 20:49:337708 source_id);
[email protected]a796f202012-05-30 14:14:257709}
7710
Daniel Cheng90196c82018-04-25 21:49:147711void WebContentsImpl::DidReceiveInputEvent(
dominickn9c7ceaa32016-02-27 01:52:537712 RenderWidgetHostImpl* render_widget_host,
Emily Starkc7bd40c42020-07-21 19:12:557713 const blink::WebInputEvent& event) {
Alexander Timin5fdeff22020-09-08 09:20:377714 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DidReceiveInputEvent",
7715 "render_widget_host", render_widget_host);
7716
Emily Starkc7bd40c42020-07-21 19:12:557717 if (!IsUserInteractionInputType(event.GetType()))
Daniel Cheng90196c82018-04-25 21:49:147718 return;
7719
kenrb19221852016-04-29 17:21:407720 // Ignore unless the widget is currently in the frame tree.
7721 if (!HasMatchingWidgetHost(&frame_tree_, render_widget_host))
avic3aa8422015-11-09 20:57:227722 return;
7723
Emily Starkc7bd40c42020-07-21 19:12:557724 if (event.GetType() != blink::WebInputEvent::Type::kGestureScrollBegin)
Daniel Cheng90196c82018-04-25 21:49:147725 last_interactive_input_event_time_ = ui::EventTimeForNow();
dominickn9c7ceaa32016-02-27 01:52:537726
Alexander Timin90c20c32020-08-12 15:28:327727 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7728 observer->DidGetUserInteraction(event);
7729 });
dominickn2dd142dd2015-10-29 05:30:507730}
7731
Avi Drissman738ea192018-08-29 20:24:167732bool WebContentsImpl::ShouldIgnoreInputEvents() {
7733 WebContentsImpl* web_contents = this;
7734 while (web_contents) {
7735 if (web_contents->ignore_input_events_)
7736 return true;
7737 web_contents = web_contents->GetOuterWebContents();
7738 }
7739
7740 return false;
7741}
7742
avallee9993fca2016-11-17 06:16:507743void WebContentsImpl::FocusOwningWebContents(
7744 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:377745 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::FocusOwningWebContents",
7746 "render_widget_host", render_widget_host);
Alex Moshchukc4f0a722019-11-19 22:41:287747 RenderWidgetHostImpl* main_frame_widget_host =
7748 GetMainFrame()->GetRenderWidgetHost();
avallee9993fca2016-11-17 06:16:507749 RenderWidgetHostImpl* focused_widget =
Alex Moshchukc4f0a722019-11-19 22:41:287750 GetFocusedRenderWidgetHost(main_frame_widget_host);
avallee9993fca2016-11-17 06:16:507751
7752 if (focused_widget != render_widget_host &&
avallee8e881592016-11-19 00:39:307753 (!focused_widget ||
7754 focused_widget->delegate() != render_widget_host->delegate())) {
avallee9993fca2016-11-17 06:16:507755 SetAsFocusedWebContentsIfNecessary();
7756 }
7757}
7758
[email protected]b172aee2012-04-10 17:05:267759void WebContentsImpl::OnIgnoredUIEvent() {
Alexander Timin5fdeff22020-09-08 09:20:377760 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnIgnoredUIEvent");
[email protected]31145092011-09-30 01:49:447761 // Notify observers.
Alexander Timin90c20c32020-08-12 15:28:327762 observers_.ForEachObserver(
7763 [&](WebContentsObserver* observer) { observer->DidGetIgnoredUIEvent(); });
[email protected]fa1cf0b82010-01-15 21:49:447764}
7765
avic3aa8422015-11-09 20:57:227766void WebContentsImpl::RendererUnresponsive(
Lukasz Anforowicz52b93722018-06-20 16:11:397767 RenderWidgetHostImpl* render_widget_host,
7768 base::RepeatingClosure hang_monitor_restarter) {
Alexander Timin5fdeff22020-09-08 09:20:377769 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RendererUnresponsive",
7770 "render_widget_host", render_widget_host);
avic031d392017-03-03 03:09:427771 if (ShouldIgnoreUnresponsiveRenderer())
[email protected]e5fc1632011-08-08 07:51:537772 return;
7773
Lukasz Anforowicz4f0593d2018-09-21 18:33:547774 // Do not report hangs (to task manager, to hang renderer dialog, etc.) for
7775 // invisible tabs (like extension background page, background tabs). See
7776 // https://crbug.com/881812 for rationale and for choosing the visibility
7777 // (rather than process priority) as the signal here.
7778 if (GetVisibility() != Visibility::VISIBLE)
7779 return;
7780
Avi Drissman8920def2018-01-31 19:53:367781 if (!render_widget_host->renderer_initialized())
[email protected]55452902011-06-01 21:57:477782 return;
7783
Alexander Timin90c20c32020-08-12 15:28:327784 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7785 observer->OnRendererUnresponsive(render_widget_host->GetProcess());
7786 });
Dave Tapuskac6146c52017-12-20 22:48:157787 if (delegate_)
Lukasz Anforowicz52b93722018-06-20 16:11:397788 delegate_->RendererUnresponsive(this, render_widget_host,
7789 std::move(hang_monitor_restarter));
[email protected]420ae012009-04-24 05:16:327790}
7791
avic3aa8422015-11-09 20:57:227792void WebContentsImpl::RendererResponsive(
7793 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:377794 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderResponsive",
7795 "render_widget_host", render_widget_host);
Alexander Timin90c20c32020-08-12 15:28:327796 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7797 observer->OnRendererResponsive(render_widget_host->GetProcess());
7798 });
Alexander Timin5fdeff22020-09-08 09:20:377799
[email protected]6934a702011-12-20 00:04:517800 if (delegate_)
Avi Drissman1572e8c3c2018-02-02 19:06:367801 delegate_->RendererResponsive(this, render_widget_host);
[email protected]420ae012009-04-24 05:16:327802}
7803
Alex Moshchuk7b4f0652019-05-30 18:54:417804void WebContentsImpl::SubframeCrashed(
7805 blink::mojom::FrameVisibility visibility) {
Alexander Timin5fdeff22020-09-08 09:20:377806 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SubframeCrashed",
7807 "visibility",
7808 base::trace_event::ValueToString(visibility));
Alex Moshchuk7b4f0652019-05-30 18:54:417809 // If a subframe crashed on a hidden tab, mark the tab for reload to avoid
7810 // showing a sad frame to the user if they ever switch back to that tab. Do
7811 // this for subframes that are either visible in viewport or visible but
7812 // scrolled out of view, but skip subframes that are not rendered (e.g., via
7813 // "display:none"), since in that case the user wouldn't see a sad frame
7814 // anyway.
7815 bool did_mark_for_reload = false;
7816 if (IsHidden() && visibility != blink::mojom::FrameVisibility::kNotRendered &&
7817 base::FeatureList::IsEnabled(
7818 features::kReloadHiddenTabsWithCrashedSubframes)) {
7819 controller_.SetNeedsReload(
7820 NavigationControllerImpl::NeedsReloadType::kCrashedSubframe);
7821 did_mark_for_reload = true;
7822 UMA_HISTOGRAM_ENUMERATION(
7823 "Stability.ChildFrameCrash.TabMarkedForReload.Visibility", visibility);
7824 }
7825
7826 UMA_HISTOGRAM_BOOLEAN("Stability.ChildFrameCrash.TabMarkedForReload",
7827 did_mark_for_reload);
7828}
7829
[email protected]b172aee2012-04-10 17:05:267830void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
[email protected]feaded02012-09-25 19:12:557831 bool proceed, const base::TimeTicks& proceed_time,
[email protected]420ae012009-04-24 05:16:327832 bool* proceed_to_fire_unload) {
Alexander Timin5fdeff22020-09-08 09:20:377833 OPTIONAL_TRACE_EVENT0("content",
7834 "WebContentsImpl::BeforeUnloadFiredFromRenderManager");
Alexander Timin90c20c32020-08-12 15:28:327835 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7836 observer->BeforeUnloadFired(proceed, proceed_time);
7837 });
[email protected]6934a702011-12-20 00:04:517838 if (delegate_)
7839 delegate_->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
[email protected]e80af492013-06-24 21:52:097840 // Note: |this| might be deleted at this point.
[email protected]420ae012009-04-24 05:16:327841}
7842
[email protected]58d5cfe2013-07-10 02:40:527843void WebContentsImpl::RenderProcessGoneFromRenderManager(
[email protected]3a3d47472010-07-15 21:03:547844 RenderViewHost* render_view_host) {
[email protected]443b80e2010-12-14 00:42:237845 DCHECK(crashed_status_ != base::TERMINATION_STATUS_STILL_RUNNING);
[email protected]ec6a7eb2013-04-22 17:34:227846 RenderViewTerminated(render_view_host, crashed_status_, crashed_error_code_);
[email protected]3a3d47472010-07-15 21:03:547847}
7848
[email protected]af905902013-10-01 21:38:517849void WebContentsImpl::CancelModalDialogsForRenderManager() {
Alexander Timin5fdeff22020-09-08 09:20:377850 OPTIONAL_TRACE_EVENT0("content",
7851 "WebContentsImpl::CancelModalDialogsForRenderManager");
[email protected]af905902013-10-01 21:38:517852 // We need to cancel modal dialogs when doing a process swap, since the load
avi2460c762015-04-17 15:21:547853 // deferrer would prevent us from swapping out. We also clear the state
7854 // because this is a cross-process navigation, which means that it's a new
7855 // site that should not have to pay for the sins of its predecessor.
creis89a0f782015-05-27 16:13:177856 //
Lei Zhang6410ec1a2019-01-31 21:38:587857 // Note that we don't bother telling |browser_plugin_embedder_| because the
creis89a0f782015-05-27 16:13:177858 // cross-process navigation will either destroy the browser plugins or not
7859 // require their dialogs to close.
avi5d3b8692016-10-12 22:00:467860 if (dialog_manager_) {
avi6879fcf2017-01-21 05:27:537861 dialog_manager_->CancelDialogs(this, /*reset_state=*/true);
avi5d3b8692016-10-12 22:00:467862 }
[email protected]af905902013-10-01 21:38:517863}
7864
danakja0bce4c952020-05-12 20:40:287865void WebContentsImpl::NotifySwappedFromRenderManager(RenderFrameHost* old_frame,
7866 RenderFrameHost* new_frame,
[email protected]02d7b6e2014-06-24 21:01:507867 bool is_main_frame) {
Alexander Timin5fdeff22020-09-08 09:20:377868 TRACE_EVENT2(
7869 "content", "WebContentsImpl::NotifySwappedFromRenderManager",
7870 "old_render_frame_host", base::trace_event::ToTracedValue(old_frame),
7871 "new_render_frame_host", base::trace_event::ToTracedValue(new_frame));
[email protected]02d7b6e2014-06-24 21:01:507872 if (is_main_frame) {
danakja0bce4c952020-05-12 20:40:287873 // The |new_frame| and its various compadres are already swapped into place
7874 // for the WebContentsImpl when this method is called.
7875 DCHECK(GetMainFrame() == new_frame);
7876 DCHECK(GetRenderViewHost() == new_frame->GetRenderViewHost());
7877 DCHECK(GetRenderWidgetHostView() == new_frame->GetView());
7878
Fergal Daly6767b2e2020-02-04 03:15:167879 RenderViewHost* old_rvh =
danakja0bce4c952020-05-12 20:40:287880 old_frame ? old_frame->GetRenderViewHost() : nullptr;
7881 RenderViewHost* new_rvh = new_frame->GetRenderViewHost();
Fergal Daly6767b2e2020-02-04 03:15:167882 // |old_rvh| and |new_rvh| might be equal when navigating from a crashed
7883 // RenderFrameHost to a new same-site one. With RenderDocument, this will
7884 // happen for every same-site navigation.
7885 if (old_rvh != new_rvh)
7886 NotifyViewSwapped(old_rvh, new_rvh);
[email protected]a6b73c62013-02-11 23:05:087887
[email protected]02d7b6e2014-06-24 21:01:507888 // Make sure the visible RVH reflects the new delegate's preferences.
7889 if (delegate_)
7890 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
[email protected]d56a49e2013-02-23 00:47:397891
danakja0bce4c952020-05-12 20:40:287892 auto* rwhv = static_cast<RenderWidgetHostViewBase*>(new_frame->GetView());
7893 if (rwhv) {
7894 rwhv->SetMainFrameAXTreeID(new_frame->GetAXTreeID());
7895
7896 // The RenderWidgetHostView for the speculative RenderFrameHost is not
7897 // resized with the current RenderFrameHost while a navigation is
7898 // pending. So when we swap in the main frame, we need to update the
7899 // RenderWidgetHostView's size.
7900 //
7901 // Historically, this was done to fix b/1079768 for interstitials.
7902 rwhv->SetSize(GetSizeForMainFrame());
7903 }
[email protected]02d7b6e2014-06-24 21:01:507904 }
7905
danakja0bce4c952020-05-12 20:40:287906 NotifyFrameSwapped(old_frame, new_frame, is_main_frame);
[email protected]3a3d47472010-07-15 21:03:547907}
7908
naskof5940b9f2015-03-02 23:04:057909void WebContentsImpl::NotifyMainFrameSwappedFromRenderManager(
danakja0bce4c952020-05-12 20:40:287910 RenderFrameHost* old_frame,
7911 RenderFrameHost* new_frame) {
7912 NotifyViewSwapped(old_frame ? old_frame->GetRenderViewHost() : nullptr,
7913 new_frame->GetRenderViewHost());
naskof5940b9f2015-03-02 23:04:057914}
7915
[email protected]b172aee2012-04-10 17:05:267916NavigationControllerImpl& WebContentsImpl::GetControllerForRenderManager() {
[email protected]d1198fd2012-08-13 22:50:197917 return GetController();
[email protected]3a3d47472010-07-15 21:03:547918}
7919
dcheng59716272016-04-09 05:19:087920std::unique_ptr<WebUIImpl> WebContentsImpl::CreateWebUIForRenderFrameHost(
Miyoung Shin072d4052020-07-13 07:52:447921 RenderFrameHost* frame_host,
Denis Kuznetsov [CET]2c6f0159f2020-05-18 14:18:167922 const GURL& url) {
Miyoung Shin072d4052020-07-13 07:52:447923 return CreateWebUI(frame_host, url);
[email protected]420ae012009-04-24 05:16:327924}
7925
lfgbede6392015-09-11 21:54:067926void WebContentsImpl::CreateRenderWidgetHostViewForRenderManager(
7927 RenderViewHost* render_view_host) {
Alexander Timin5fdeff22020-09-08 09:20:377928 OPTIONAL_TRACE_EVENT1(
7929 "content", "WebContentsImpl::CreateRenderWidgetHostViewForRenderManager",
7930 "render_view_host", render_view_host);
lfgc740d4b22016-04-15 16:45:337931 RenderWidgetHostViewBase* rwh_view =
W. James MacLean13d834d2019-12-04 16:06:457932 view_->CreateViewForWidget(render_view_host->GetWidget());
danakja0bce4c952020-05-12 20:40:287933 rwh_view->SetSize(GetSizeForMainFrame());
lfgbede6392015-09-11 21:54:067934}
7935
7936bool WebContentsImpl::CreateRenderViewForRenderManager(
7937 RenderViewHost* render_view_host,
Antonio Gomesb3dd5fc2020-05-25 22:53:277938 const base::Optional<base::UnguessableToken>& opener_frame_token,
Daniel Chengabfdb002020-06-04 06:02:307939 int proxy_routing_id) {
Alexander Timin5fdeff22020-09-08 09:20:377940 TRACE_EVENT1("browser,navigation",
7941 "WebContentsImpl::CreateRenderViewForRenderManager",
7942 "render_view_host", render_view_host);
lfgbede6392015-09-11 21:54:067943
piman00cf9402017-04-03 17:09:207944 if (proxy_routing_id == MSG_ROUTING_NONE)
lfg9431efd2016-12-14 14:45:267945 CreateRenderWidgetHostViewForRenderManager(render_view_host);
lfg9431efd2016-12-14 14:45:267946
piman00cf9402017-04-03 17:09:207947 if (!static_cast<RenderViewHostImpl*>(render_view_host)
Daniel Chengabfdb002020-06-04 06:02:307948 ->CreateRenderView(opener_frame_token, proxy_routing_id,
Antonio Gomesb3dd5fc2020-05-25 22:53:277949 created_with_opener_)) {
[email protected]a4127722011-04-27 23:13:527950 return false;
[email protected]14392a52012-05-02 20:28:447951 }
W. James MacLean62198672019-06-04 16:46:107952 // Set the TextAutosizer state from the main frame's renderer on the new view,
7953 // but only if it's not for the main frame. Main frame renderers should create
7954 // this state themselves from up-to-date values, so we shouldn't override it
7955 // with the cached values.
7956 if (!render_view_host->GetMainFrame()) {
Antonio Gomesda7e03d2020-08-05 15:03:087957 auto* proxy_host = GetRenderManager()->GetRenderFrameProxyHost(
7958 render_view_host->GetSiteInstance());
7959 proxy_host->GetAssociatedRemoteMainFrame()->UpdateTextAutosizerPageInfo(
7960 text_autosizer_page_info_.Clone());
W. James MacLean62198672019-06-04 16:46:107961 }
[email protected]a4127722011-04-27 23:13:527962
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:147963 if (proxy_routing_id == MSG_ROUTING_NONE && node_.outer_web_contents())
7964 ReattachToOuterWebContentsFrame();
7965
avi2b177592014-12-10 02:08:027966 SetHistoryOffsetAndLengthForView(render_view_host,
7967 controller_.GetLastCommittedEntryIndex(),
7968 controller_.GetEntryCount());
7969
Avi Drissman7c57be72020-07-29 20:09:467970#if defined(OS_POSIX) && !defined(OS_MAC) && !defined(OS_ANDROID)
[email protected]f8233cc2011-05-31 20:24:507971 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
7972 // linux. See crbug.com/83941.
avif9ab5d942015-10-15 14:05:447973 RenderWidgetHostView* rwh_view = render_view_host->GetWidget()->GetView();
[email protected]245f7d52011-11-28 15:36:447974 if (rwh_view) {
7975 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
Fady Samuel0b911822018-04-25 13:22:167976 render_widget_host->SynchronizeVisualProperties();
[email protected]245f7d52011-11-28 15:36:447977 }
[email protected]f8233cc2011-05-31 20:24:507978#endif
7979
[email protected]420ae012009-04-24 05:16:327980 return true;
7981}
7982
mfomitchev2b8b066a2016-01-28 19:23:157983#if defined(OS_ANDROID)
[email protected]fc2b46b2014-05-03 16:33:457984
[email protected]155c7f22013-12-09 17:07:187985base::android::ScopedJavaLocalRef<jobject>
7986WebContentsImpl::GetJavaWebContents() {
mostynb042582e2015-03-16 22:13:407987 DCHECK_CURRENTLY_ON(BrowserThread::UI);
[email protected]0e813a52014-08-13 10:34:567988 return GetWebContentsAndroid()->GetJavaObject();
7989}
[email protected]155c7f22013-12-09 17:07:187990
[email protected]0e813a52014-08-13 10:34:567991WebContentsAndroid* WebContentsImpl::GetWebContentsAndroid() {
Kevin McNee576bb5d82019-05-29 16:47:517992 if (!web_contents_android_) {
7993 web_contents_android_ = std::make_unique<WebContentsAndroid>(this);
[email protected]155c7f22013-12-09 17:07:187994 }
Kevin McNee576bb5d82019-05-29 16:47:517995 return web_contents_android_.get();
7996}
7997
7998void WebContentsImpl::ClearWebContentsAndroid() {
7999 DCHECK_CURRENTLY_ON(BrowserThread::UI);
8000 web_contents_android_.reset();
[email protected]155c7f22013-12-09 17:07:188001}
8002
paulmeyerc0b762b2016-04-13 11:55:178003void WebContentsImpl::ActivateNearestFindResult(float x,
8004 float y) {
Alexander Timin5fdeff22020-09-08 09:20:378005 OPTIONAL_TRACE_EVENT0("content",
8006 "WebContentsImpl::ActivateNearestFindResult");
paulmeyerc0b762b2016-04-13 11:55:178007 GetOrCreateFindRequestManager()->ActivateNearestFindResult(x, y);
8008}
8009
8010void WebContentsImpl::RequestFindMatchRects(int current_version) {
Alexander Timin5fdeff22020-09-08 09:20:378011 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::RequestFindMatchRects");
paulmeyerc0b762b2016-04-13 11:55:178012 GetOrCreateFindRequestManager()->RequestFindMatchRects(current_version);
8013}
8014
rockot400ea35b2016-10-15 19:15:328015service_manager::InterfaceProvider* WebContentsImpl::GetJavaInterfaces() {
sammcf5f1b0f2016-09-20 23:05:118016 if (!java_interfaces_) {
Gyuyoung Kim6c9ce9022019-11-26 05:40:088017 mojo::PendingRemote<service_manager::mojom::InterfaceProvider> provider;
8018 BindInterfaceRegistryForWebContents(
8019 provider.InitWithNewPipeAndPassReceiver(), this);
rockot400ea35b2016-10-15 19:15:328020 java_interfaces_.reset(new service_manager::InterfaceProvider);
sammcf5f1b0f2016-09-20 23:05:118021 java_interfaces_->Bind(std::move(provider));
8022 }
8023 return java_interfaces_.get();
8024}
8025
Francois Doray6c26f3342018-08-24 17:17:228026#endif
8027
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:418028bool WebContentsImpl::CompletedFirstVisuallyNonEmptyPaint() {
Carlos Caballero91fffb22019-10-29 15:24:308029 return GetRenderViewHost()->did_first_visually_non_empty_paint();
spqchane72c3cb2017-06-30 23:02:108030}
8031
pkotwicz75ca8ffd2016-02-16 23:10:198032void WebContentsImpl::OnDidDownloadImage(
Avi Drissmana5a52dd2018-03-27 03:39:028033 ImageDownloadCallback callback,
pkotwicz75ca8ffd2016-02-16 23:10:198034 int id,
8035 const GURL& image_url,
leon.hancbc4bc3c2016-02-26 07:08:528036 int32_t http_status_code,
leon.hanc2228532016-08-16 05:59:188037 const std::vector<SkBitmap>& images,
8038 const std::vector<gfx::Size>& original_image_sizes) {
Alexander Timin5fdeff22020-09-08 09:20:378039 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnDidDownloadImage",
8040 "image_url",
8041 base::trace_event::ValueToString(image_url));
Avi Drissmana5a52dd2018-03-27 03:39:028042 std::move(callback).Run(id, http_status_code, image_url, images,
8043 original_image_sizes);
pkotwicz75ca8ffd2016-02-16 23:10:198044}
8045
[email protected]6fba26d2014-04-29 09:38:288046void WebContentsImpl::OnDialogClosed(int render_process_id,
8047 int render_frame_id,
Dave Tapuskacdf545cc2020-01-23 18:38:528048 JavaScriptDialogCallback response_callback,
Avi Drissman1a55a9d62020-03-10 18:56:458049 base::ScopedClosureRunner fullscreen_block,
[email protected]87de04b02014-04-08 22:14:498050 bool dialog_was_suppressed,
[email protected]b172aee2012-04-10 17:05:268051 bool success,
[email protected]fcf75d42013-12-03 20:11:268052 const base::string16& user_input) {
[email protected]6fba26d2014-04-29 09:38:288053 RenderFrameHostImpl* rfh = RenderFrameHostImpl::FromID(render_process_id,
8054 render_frame_id);
Alexander Timin5fdeff22020-09-08 09:20:378055 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnDialogClosed",
8056 "render_frame_host",
8057 base::trace_event::ToTracedValue(rfh));
[email protected]87de04b02014-04-08 22:14:498058 last_dialog_suppressed_ = dialog_was_suppressed;
Avi Drissman1a55a9d62020-03-10 18:56:458059 fullscreen_block.RunAndReset();
[email protected]87de04b02014-04-08 22:14:498060
Charlie Reis96077362019-07-04 00:34:048061 javascript_dialog_navigation_deferrer_.reset();
8062
[email protected]beb440c2009-11-06 04:08:548063 if (is_showing_before_unload_dialog_ && !success) {
clamybc6f4152016-04-01 20:14:238064 // It is possible for the current RenderFrameHost to have changed in the
8065 // meantime. Do not reset the navigation state in that case.
8066 if (rfh && rfh == rfh->frame_tree_node()->current_frame_host()) {
clamy44e84ce2016-02-22 15:38:258067 rfh->frame_tree_node()->BeforeUnloadCanceled();
clamybc6f4152016-04-01 20:14:238068 controller_.DiscardNonCommittedEntries();
8069 }
[email protected]ec8e8b02013-06-19 04:57:108070
Charles Reis15d60b132017-11-03 17:43:478071 // Update the URL display either way, to avoid showing a stale URL.
8072 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
8073
Alexander Timin90c20c32020-08-12 15:28:328074 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8075 observer->BeforeUnloadDialogCancelled();
8076 });
[email protected]beb440c2009-11-06 04:08:548077 }
[email protected]87de04b02014-04-08 22:14:498078
Dave Tapuskacdf545cc2020-01-23 18:38:528079 std::move(response_callback).Run(success, user_input);
Pavel Feldman3c1842b2017-08-02 05:00:168080
Dave Tapuskacdf545cc2020-01-23 18:38:528081 std::vector<protocol::PageHandler*> page_handlers =
8082 protocol::PageHandler::EnabledForWebContents(this);
8083 for (auto* handler : page_handlers)
8084 handler->DidCloseJavaScriptDialog(success, user_input);
avi1c51fb62017-02-27 20:43:038085
8086 is_showing_javascript_dialog_ = false;
8087 is_showing_before_unload_dialog_ = false;
[email protected]beb440c2009-11-06 04:08:548088}
8089
[email protected]1ac10dca2013-08-20 20:47:048090bool WebContentsImpl::IsHidden() {
Francois Doraye6161152018-03-27 22:05:378091 return !IsBeingCaptured() && visibility_ != Visibility::VISIBLE;
[email protected]1ac10dca2013-08-20 20:47:048092}
8093
rob97250742015-12-10 17:45:158094int WebContentsImpl::GetOuterDelegateFrameTreeNodeId() {
lfg601233692017-03-06 22:45:448095 return node_.outer_contents_frame_tree_node_id();
lazyboy6ec48b2a2015-06-29 15:18:148096}
8097
ekaramadaeb3c5c2016-11-09 03:22:358098RenderWidgetHostImpl* WebContentsImpl::GetFullscreenRenderWidgetHost() const {
8099 return RenderWidgetHostImpl::FromID(fullscreen_widget_process_id_,
8100 fullscreen_widget_routing_id_);
8101}
8102
[email protected]b0936d22013-11-28 06:47:368103RenderFrameHostManager* WebContentsImpl::GetRenderManager() const {
[email protected]fa944cb82013-11-15 17:51:218104 return frame_tree_.root()->render_manager();
8105}
8106
[email protected]f8497342013-02-05 22:15:028107BrowserPluginGuest* WebContentsImpl::GetBrowserPluginGuest() const {
[email protected]7a846df2012-09-20 19:17:398108 return browser_plugin_guest_.get();
8109}
8110
Albert J. Wongc55cc64d2018-10-12 02:50:048111void WebContentsImpl::SetBrowserPluginGuest(
8112 std::unique_ptr<BrowserPluginGuest> guest) {
Alexander Timin5fdeff22020-09-08 09:20:378113 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetBrowserPluginGuest");
Albert J. Wongc55cc64d2018-10-12 02:50:048114 DCHECK(!browser_plugin_guest_);
8115 DCHECK(guest);
8116 browser_plugin_guest_ = std::move(guest);
[email protected]738f57a2013-06-29 21:06:548117}
8118
Aidan Wolter52bcc12a2018-11-14 03:27:298119base::UnguessableToken WebContentsImpl::GetAudioGroupId() {
Aidan Wolter52bcc12a2018-11-14 03:27:298120 return GetAudioStreamFactory()->group_id();
8121}
8122
Miyoung Shin5709ab02020-02-19 06:50:418123const std::vector<blink::mojom::FaviconURLPtr>&
8124WebContentsImpl::GetFaviconURLs() {
Mounir Lamouri7b4a1f232019-12-23 16:32:108125 return favicon_urls_;
8126}
8127
Mugdha Lakhani0a0d7862020-07-29 09:58:458128// The Mac implementation of the next two methods is in
8129// web_contents_impl_mac.mm
Avi Drissmand4d79f72020-07-30 18:35:188130#if !defined(OS_MAC)
Mugdha Lakhani0a0d7862020-07-29 09:58:458131
8132void WebContentsImpl::Resize(const gfx::Rect& new_bounds) {
Alexander Timin5fdeff22020-09-08 09:20:378133 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Resize");
Mugdha Lakhani0a0d7862020-07-29 09:58:458134#if defined(USE_AURA)
8135 aura::Window* window = GetNativeView();
8136 window->SetBounds(gfx::Rect(window->bounds().origin(), new_bounds.size()));
8137#elif defined(OS_ANDROID)
8138 content::RenderWidgetHostView* view = GetRenderWidgetHostView();
8139 if (view)
8140 view->SetBounds(new_bounds);
8141#endif
8142}
8143
8144gfx::Size WebContentsImpl::GetSize() {
8145#if defined(USE_AURA)
8146 aura::Window* window = GetNativeView();
8147 return window->bounds().size();
8148#elif defined(OS_ANDROID)
8149 ui::ViewAndroid* view_android = GetNativeView();
8150 return view_android->bounds().size();
8151#endif
8152}
8153
Avi Drissmand4d79f72020-07-30 18:35:188154#endif // !defined(OS_MAC)
Mugdha Lakhani0a0d7862020-07-29 09:58:458155
[email protected]f8497342013-02-05 22:15:028156BrowserPluginEmbedder* WebContentsImpl::GetBrowserPluginEmbedder() const {
[email protected]7a846df2012-09-20 19:17:398157 return browser_plugin_embedder_.get();
8158}
[email protected]8ff00d72012-10-23 19:12:218159
fsamuel60b42282015-03-10 03:29:148160void WebContentsImpl::CreateBrowserPluginEmbedderIfNecessary() {
Alexander Timin5fdeff22020-09-08 09:20:378161 OPTIONAL_TRACE_EVENT0(
8162 "content", "WebContentsImpl::CreateBrowserPluginEmbedderIfNecessary");
fsamuel60b42282015-03-10 03:29:148163 if (browser_plugin_embedder_)
8164 return;
8165 browser_plugin_embedder_.reset(BrowserPluginEmbedder::Create(this));
8166}
8167
danakja0bce4c952020-05-12 20:40:288168gfx::Size WebContentsImpl::GetSizeForMainFrame() {
8169 if (delegate_) {
8170 // The delegate has a chance to specify a size independent of the UI.
8171 gfx::Size delegate_size = delegate_->GetSizeForNewRenderView(this);
8172 if (!delegate_size.IsEmpty())
8173 return delegate_size;
8174 }
8175
8176 // Device emulation, when enabled, can specify a size independent of the UI.
8177 if (!device_emulation_size_.IsEmpty())
8178 return device_emulation_size_;
8179
8180 return GetContainerBounds().size();
[email protected]dc0fd432013-08-27 15:29:218181}
8182
[email protected]ae7eeda2014-07-04 01:53:268183void WebContentsImpl::OnFrameRemoved(RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:378184 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnFrameRemoved",
8185 "render_frame_host",
8186 base::trace_event::ToTracedValue(render_frame_host));
Alexander Timin90c20c32020-08-12 15:28:328187 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8188 observer->FrameDeleted(render_frame_host);
8189 });
[email protected]9b159a52013-10-03 17:24:558190}
8191
[email protected]222f5822014-02-05 23:40:498192void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size& old_size) {
Alexander Timin5fdeff22020-09-08 09:20:378193 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnPreferredSizeChanged");
[email protected]222f5822014-02-05 23:40:498194 if (!delegate_)
8195 return;
8196 const gfx::Size new_size = GetPreferredSize();
8197 if (new_size != old_size)
8198 delegate_->UpdatePreferredSize(this, new_size);
8199}
8200
Miyoung Shin072d4052020-07-13 07:52:448201std::unique_ptr<WebUIImpl> WebContentsImpl::CreateWebUI(
8202 RenderFrameHost* frame_host,
8203 const GURL& url) {
Alexander Timin5fdeff22020-09-08 09:20:378204 TRACE_EVENT2("content", "WebContentsImpl::CreateWebUI", "frame_host",
8205 base::trace_event::ToTracedValue(frame_host), "url",
8206 base::trace_event::ValueToString(url));
Miyoung Shin072d4052020-07-13 07:52:448207 std::unique_ptr<WebUIImpl> web_ui =
8208 std::make_unique<WebUIImpl>(this, frame_host);
Lei Zhangee3b63ad2018-06-06 23:25:318209 std::unique_ptr<WebUIController> controller(
avie865b1d2016-10-24 19:42:598210 WebUIControllerFactoryRegistry::GetInstance()
Lei Zhangee3b63ad2018-06-06 23:25:318211 ->CreateWebUIControllerForURL(web_ui.get(), url));
dbeama1b926a2015-08-31 23:17:518212 if (controller) {
Lei Zhangee3b63ad2018-06-06 23:25:318213 web_ui->SetController(std::move(controller));
dbeama1b926a2015-08-31 23:17:518214 return web_ui;
8215 }
8216
avie865b1d2016-10-24 19:42:598217 return nullptr;
dbeama1b926a2015-08-31 23:17:518218}
8219
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:418220FindRequestManager* WebContentsImpl::GetFindRequestManager() {
8221 for (auto* contents = this; contents;
paulmeyerfeafc2d2017-04-25 21:46:408222 contents = contents->GetOuterWebContents()) {
8223 if (contents->find_request_manager_)
8224 return contents->find_request_manager_.get();
8225 }
8226
8227 return nullptr;
8228}
8229
paulmeyerc0b762b2016-04-13 11:55:178230FindRequestManager* WebContentsImpl::GetOrCreateFindRequestManager() {
paulmeyerfeafc2d2017-04-25 21:46:408231 if (FindRequestManager* manager = GetFindRequestManager())
8232 return manager;
8233
Ehsan Karamad6beb2ea2018-11-25 18:15:138234 DCHECK(!browser_plugin_guest_ || GetOuterWebContents());
8235
paulmeyerfeafc2d2017-04-25 21:46:408236 // No existing FindRequestManager found, so one must be created.
Fergal Daly55b6d722020-09-11 07:56:338237 find_request_manager_ = std::make_unique<FindRequestManager>(this);
paulmeyerfeafc2d2017-04-25 21:46:408238
8239 // Concurrent find sessions must not overlap, so destroy any existing
8240 // FindRequestManagers in any inner WebContentses.
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:168241 for (WebContents* contents : GetWebContentsAndAllInner()) {
8242 auto* web_contents_impl = static_cast<WebContentsImpl*>(contents);
8243 if (web_contents_impl == this)
paulmeyerfeafc2d2017-04-25 21:46:408244 continue;
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:168245 if (web_contents_impl->find_request_manager_) {
8246 web_contents_impl->find_request_manager_->StopFinding(
8247 STOP_FIND_ACTION_CLEAR_SELECTION);
8248 web_contents_impl->find_request_manager_.release();
paulmeyerfeafc2d2017-04-25 21:46:408249 }
8250 }
paulmeyerc0b762b2016-04-13 11:55:178251
8252 return find_request_manager_.get();
8253}
8254
8255void WebContentsImpl::NotifyFindReply(int request_id,
8256 int number_of_matches,
8257 const gfx::Rect& selection_rect,
8258 int active_match_ordinal,
8259 bool final_update) {
Alexander Timin5fdeff22020-09-08 09:20:378260 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::NotifyFindReply");
Sebastien Marchandcf97ed52017-07-24 23:50:348261 if (delegate_ && !is_being_destroyed_ &&
Lukasz Anforowicze9ae3722017-09-29 17:37:388262 !GetMainFrame()->GetProcess()->FastShutdownStarted()) {
paulmeyerc0b762b2016-04-13 11:55:178263 delegate_->FindReply(this, request_id, number_of_matches, selection_rect,
8264 active_match_ordinal, final_update);
8265 }
8266}
8267
ortuno467e5792016-06-10 04:32:398268void WebContentsImpl::IncrementBluetoothConnectedDeviceCount() {
Alexander Timin5fdeff22020-09-08 09:20:378269 OPTIONAL_TRACE_EVENT0(
8270 "content", "WebContentsImpl::IncrementBluetoothConnectedDeviceCount");
ortuno467e5792016-06-10 04:32:398271 // Trying to invalidate the tab state while being destroyed could result in a
8272 // use after free.
8273 if (IsBeingDestroyed()) {
8274 return;
8275 }
8276 // Notify for UI updates if the state changes.
8277 bluetooth_connected_device_count_++;
8278 if (bluetooth_connected_device_count_ == 1) {
Francois Doray66766a572019-12-17 20:56:498279 OnIsConnectedToBluetoothDeviceChanged(true);
ortuno467e5792016-06-10 04:32:398280 }
8281}
8282
8283void WebContentsImpl::DecrementBluetoothConnectedDeviceCount() {
Alexander Timin5fdeff22020-09-08 09:20:378284 OPTIONAL_TRACE_EVENT0(
8285 "content", "WebContentsImpl::DecrementBluetoothConnectedDeviceCount");
ortuno467e5792016-06-10 04:32:398286 // Trying to invalidate the tab state while being destroyed could result in a
8287 // use after free.
8288 if (IsBeingDestroyed()) {
8289 return;
8290 }
8291 // Notify for UI updates if the state changes.
Lukasz Anforowicze9ae3722017-09-29 17:37:388292 DCHECK_NE(bluetooth_connected_device_count_, 0u);
ortuno467e5792016-06-10 04:32:398293 bluetooth_connected_device_count_--;
8294 if (bluetooth_connected_device_count_ == 0) {
Francois Doray66766a572019-12-17 20:56:498295 OnIsConnectedToBluetoothDeviceChanged(false);
8296 }
8297}
8298
8299void WebContentsImpl::OnIsConnectedToBluetoothDeviceChanged(
8300 bool is_connected_to_bluetooth_device) {
Alexander Timin5fdeff22020-09-08 09:20:378301 OPTIONAL_TRACE_EVENT0(
8302 "content", "WebContentsImpl::OnIsConnectedToBluetoothDeviceChanged");
Francois Doray66766a572019-12-17 20:56:498303 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
Alexander Timin90c20c32020-08-12 15:28:328304 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8305 observer->OnIsConnectedToBluetoothDeviceChanged(
Francois Doray66766a572019-12-17 20:56:498306 is_connected_to_bluetooth_device);
Alexander Timin90c20c32020-08-12 15:28:328307 });
ortuno467e5792016-06-10 04:32:398308}
8309
Ovidio Henriquez76696f62020-07-08 03:06:598310void WebContentsImpl::IncrementBluetoothScanningSessionsCount() {
Alexander Timin5fdeff22020-09-08 09:20:378311 OPTIONAL_TRACE_EVENT0(
8312 "content", "WebContentsImpl::IncrementBluetoothScanningSessionsCount");
Ovidio Henriquez76696f62020-07-08 03:06:598313 // Trying to invalidate the tab state while being destroyed could result in a
8314 // use after free.
8315 if (IsBeingDestroyed())
8316 return;
8317
8318 // Notify for UI updates if the state changes.
8319 bluetooth_scanning_sessions_count_++;
8320 if (bluetooth_scanning_sessions_count_ == 1)
8321 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8322}
8323
8324void WebContentsImpl::DecrementBluetoothScanningSessionsCount() {
Alexander Timin5fdeff22020-09-08 09:20:378325 OPTIONAL_TRACE_EVENT0(
8326 "content", "WebContentsImpl::DecrementBluetoothScanningSessionsCount");
Ovidio Henriquez76696f62020-07-08 03:06:598327 // Trying to invalidate the tab state while being destroyed could result in a
8328 // use after free.
8329 if (IsBeingDestroyed())
8330 return;
8331
8332 DCHECK_NE(0u, bluetooth_scanning_sessions_count_);
8333 bluetooth_scanning_sessions_count_--;
8334 if (bluetooth_scanning_sessions_count_ == 0)
8335 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8336}
8337
Reilly Grant5e7c79b22019-04-09 17:26:208338void WebContentsImpl::IncrementSerialActiveFrameCount() {
Alexander Timin5fdeff22020-09-08 09:20:378339 OPTIONAL_TRACE_EVENT0("content",
8340 "WebContentsImpl::IncrementSerialActiveFrameCount");
Reilly Grant5e7c79b22019-04-09 17:26:208341 // Trying to invalidate the tab state while being destroyed could result in a
8342 // use after free.
8343 if (IsBeingDestroyed())
8344 return;
8345
8346 // Notify for UI updates if the state changes.
8347 serial_active_frame_count_++;
8348 if (serial_active_frame_count_ == 1)
8349 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8350}
8351
8352void WebContentsImpl::DecrementSerialActiveFrameCount() {
Alexander Timin5fdeff22020-09-08 09:20:378353 OPTIONAL_TRACE_EVENT0("content",
8354 "WebContentsImpl::DecrementSerialActiveFrameCount");
Reilly Grant5e7c79b22019-04-09 17:26:208355 // Trying to invalidate the tab state while being destroyed could result in a
8356 // use after free.
8357 if (IsBeingDestroyed())
8358 return;
8359
8360 // Notify for UI updates if the state changes.
8361 DCHECK_NE(0u, serial_active_frame_count_);
8362 serial_active_frame_count_--;
8363 if (serial_active_frame_count_ == 0)
8364 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8365}
8366
Matt Reynoldse8c6c1f2019-11-02 09:53:538367void WebContentsImpl::IncrementHidActiveFrameCount() {
Alexander Timin5fdeff22020-09-08 09:20:378368 OPTIONAL_TRACE_EVENT0("content",
8369 "WebContentsImpl::IncrementHidActiveFrameCount");
Matt Reynoldse8c6c1f2019-11-02 09:53:538370 // Trying to invalidate the tab state while being destroyed could result in a
8371 // use after free.
8372 if (IsBeingDestroyed())
8373 return;
8374
8375 // Notify for UI updates if the active frame count transitions from zero to
8376 // non-zero.
8377 hid_active_frame_count_++;
8378 if (hid_active_frame_count_ == 1)
8379 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8380}
8381
8382void WebContentsImpl::DecrementHidActiveFrameCount() {
Alexander Timin5fdeff22020-09-08 09:20:378383 OPTIONAL_TRACE_EVENT0("content",
8384 "WebContentsImpl::DecrementHidActiveFrameCount");
Matt Reynoldse8c6c1f2019-11-02 09:53:538385 // Trying to invalidate the tab state while being destroyed could result in a
8386 // use after free.
8387 if (IsBeingDestroyed())
8388 return;
8389
8390 // Notify for UI updates if the active frame count transitions from non-zero
8391 // to zero.
8392 DCHECK_NE(0u, hid_active_frame_count_);
8393 hid_active_frame_count_--;
8394 if (hid_active_frame_count_ == 0)
8395 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8396}
8397
Marijn Kruisselbrink29051042019-08-06 22:56:558398void WebContentsImpl::IncrementNativeFileSystemHandleCount() {
Alexander Timin5fdeff22020-09-08 09:20:378399 OPTIONAL_TRACE_EVENT0(
8400 "content", "WebContentsImpl::IncrementNativeFileSystemHandleCount");
Marijn Kruisselbrink29051042019-08-06 22:56:558401 // Trying to invalidate the tab state while being destroyed could result in a
8402 // use after free.
8403 if (IsBeingDestroyed())
8404 return;
8405
8406 // Notify for UI updates if the state changes. Need both TYPE_TAB and TYPE_URL
8407 // to update both the tab-level usage indicator and the usage indicator in the
8408 // omnibox.
8409 native_file_system_handle_count_++;
8410 if (native_file_system_handle_count_ == 1) {
8411 NotifyNavigationStateChanged(static_cast<content::InvalidateTypes>(
8412 INVALIDATE_TYPE_TAB | INVALIDATE_TYPE_URL));
8413 }
8414}
8415
8416void WebContentsImpl::DecrementNativeFileSystemHandleCount() {
Alexander Timin5fdeff22020-09-08 09:20:378417 OPTIONAL_TRACE_EVENT0(
8418 "content", "WebContentsImpl::DecrementNativeFileSystemHandleCount");
Marijn Kruisselbrink29051042019-08-06 22:56:558419 // Trying to invalidate the tab state while being destroyed could result in a
8420 // use after free.
8421 if (IsBeingDestroyed())
8422 return;
8423
8424 // Notify for UI updates if the state changes. Need both TYPE_TAB and TYPE_URL
8425 // to update both the tab-level usage indicator and the usage indicator in the
8426 // omnibox.
8427 DCHECK_NE(0u, native_file_system_handle_count_);
8428 native_file_system_handle_count_--;
8429 if (native_file_system_handle_count_ == 0) {
8430 NotifyNavigationStateChanged(static_cast<content::InvalidateTypes>(
8431 INVALIDATE_TYPE_TAB | INVALIDATE_TYPE_URL));
8432 }
8433}
8434
zqzhang8ac49002017-03-16 21:51:358435void WebContentsImpl::SetHasPersistentVideo(bool has_persistent_video) {
Alexander Timin5fdeff22020-09-08 09:20:378436 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetHasPersistentVideo",
8437 "has_persistent_video", has_persistent_video,
8438 "had_persistent_value", has_persistent_video_);
zqzhang8ac49002017-03-16 21:51:358439 if (has_persistent_video_ == has_persistent_video)
mlamouri5cd9ae82017-02-18 11:05:098440 return;
8441
zqzhang8ac49002017-03-16 21:51:358442 has_persistent_video_ = has_persistent_video;
mlamouri5cd9ae82017-02-18 11:05:098443 NotifyPreferencesChanged();
zqzhang8ac49002017-03-16 21:51:358444 media_web_contents_observer()->RequestPersistentVideo(has_persistent_video);
mlamouri5cd9ae82017-02-18 11:05:098445}
8446
Ian Vollick5d5c37f2019-06-19 22:50:578447void WebContentsImpl::SetSpatialNavigationDisabled(bool disabled) {
Alexander Timin5fdeff22020-09-08 09:20:378448 OPTIONAL_TRACE_EVENT2(
8449 "content", "WebContentsImpl::SetSpatialNavigationDisabled", "disabled",
8450 disabled, "was_disabled", is_spatial_navigation_disabled_);
Ian Vollick5d5c37f2019-06-19 22:50:578451 if (is_spatial_navigation_disabled_ == disabled)
8452 return;
8453
8454 is_spatial_navigation_disabled_ = disabled;
8455 NotifyPreferencesChanged();
8456}
8457
paulmeyerfeafc2d2017-04-25 21:46:408458void WebContentsImpl::BrowserPluginGuestWillDetach() {
Alexander Timin5fdeff22020-09-08 09:20:378459 OPTIONAL_TRACE_EVENT0("content",
8460 "WebContentsImpl::BrowserPluginGuestWillDetach");
paulmeyerfeafc2d2017-04-25 21:46:408461 WebContentsImpl* outermost = GetOutermostWebContents();
8462 if (this != outermost && ContainsOrIsFocusedWebContents())
8463 outermost->SetAsFocusedWebContentsIfNecessary();
8464}
8465
Becca Hughes112832e2019-06-11 17:19:028466PictureInPictureResult WebContentsImpl::EnterPictureInPicture(
Mounir Lamouri11e9ef42018-05-22 03:10:168467 const viz::SurfaceId& surface_id,
8468 const gfx::Size& natural_size) {
Alexander Timin5fdeff22020-09-08 09:20:378469 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::EnterPictureInPicture");
François Beaufortf09e4462019-01-18 14:34:518470 return delegate_
8471 ? delegate_->EnterPictureInPicture(this, surface_id, natural_size)
Becca Hughes112832e2019-06-11 17:19:028472 : PictureInPictureResult::kNotSupported;
Mounir Lamouri11e9ef42018-05-22 03:10:168473}
8474
Mounir Lamouri6d759e12018-05-16 20:01:308475void WebContentsImpl::ExitPictureInPicture() {
Alexander Timin5fdeff22020-09-08 09:20:378476 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ExitPictureInPicture");
Mounir Lamouri6d759e12018-05-16 20:01:308477 if (delegate_)
8478 delegate_->ExitPictureInPicture();
8479}
8480
paulmeyerc0b762b2016-04-13 11:55:178481#if defined(OS_ANDROID)
8482void WebContentsImpl::NotifyFindMatchRectsReply(
8483 int version,
8484 const std::vector<gfx::RectF>& rects,
8485 const gfx::RectF& active_rect) {
Alexander Timin5fdeff22020-09-08 09:20:378486 OPTIONAL_TRACE_EVENT0("content",
8487 "WebContentsImpl::NotifyFindMatchRectsReply");
paulmeyerc0b762b2016-04-13 11:55:178488 if (delegate_)
8489 delegate_->FindMatchRectsReply(this, version, rects, active_rect);
8490}
8491#endif
8492
[email protected]34ff1cfc2014-08-20 06:16:058493void WebContentsImpl::SetForceDisableOverscrollContent(bool force_disable) {
Alexander Timin5fdeff22020-09-08 09:20:378494 OPTIONAL_TRACE_EVENT1("content",
8495 "WebContentsImpl::SetForceDisableOverscrollContent",
8496 "force_disable", force_disable);
[email protected]34ff1cfc2014-08-20 06:16:058497 force_disable_overscroll_content_ = force_disable;
8498 if (view_)
8499 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
8500}
8501
Jianzhou Fengd8720c72018-01-18 03:06:308502bool WebContentsImpl::SetDeviceEmulationSize(const gfx::Size& new_size) {
Alexander Timin5fdeff22020-09-08 09:20:378503 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetDeviceEmulationSize");
Jianzhou Fengd8720c72018-01-18 03:06:308504 device_emulation_size_ = new_size;
8505 RenderWidgetHostView* rwhv = GetMainFrame()->GetView();
8506
8507 const gfx::Size current_size = rwhv->GetViewBounds().size();
8508 if (view_size_before_emulation_.IsEmpty())
8509 view_size_before_emulation_ = current_size;
8510
8511 if (current_size != new_size)
8512 rwhv->SetSize(new_size);
8513
8514 return current_size != new_size;
8515}
8516
8517void WebContentsImpl::ClearDeviceEmulationSize() {
Alexander Timin5fdeff22020-09-08 09:20:378518 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ClearDeviceEmulationSize");
Jianzhou Fengd8720c72018-01-18 03:06:308519 RenderWidgetHostView* rwhv = GetMainFrame()->GetView();
8520 // WebContentsView could get resized during emulation, which also resizes
8521 // RWHV. If it happens, assume user would like to keep using the size after
8522 // emulation.
8523 // TODO(jzfeng): Prohibit resizing RWHV through any other means (at least when
8524 // WebContentsView size changes).
Dmitry Gozmanc63707182018-03-06 00:09:398525 if (!view_size_before_emulation_.IsEmpty() && rwhv &&
8526 rwhv->GetViewBounds().size() == device_emulation_size_) {
Jianzhou Fengd8720c72018-01-18 03:06:308527 rwhv->SetSize(view_size_before_emulation_);
Dmitry Gozmanc63707182018-03-06 00:09:398528 }
Jianzhou Fengd8720c72018-01-18 03:06:308529 device_emulation_size_ = gfx::Size();
8530 view_size_before_emulation_ = gfx::Size();
8531}
8532
Max Morin5bc74f52018-05-09 07:00:218533ForwardingAudioStreamFactory* WebContentsImpl::GetAudioStreamFactory() {
8534 if (!audio_stream_factory_) {
8535 audio_stream_factory_.emplace(
8536 this,
Max Morinddebb972018-09-20 10:04:148537 // BrowserMainLoop::GetInstance() may be null in unit tests.
8538 BrowserMainLoop::GetInstance()
8539 ? static_cast<media::UserInputMonitorBase*>(
8540 BrowserMainLoop::GetInstance()->user_input_monitor())
8541 : nullptr,
Ken Rockot72964402019-12-06 10:40:518542 AudioStreamBrokerFactory::CreateImpl());
Max Morin5bc74f52018-05-09 07:00:218543 }
8544
8545 return &*audio_stream_factory_;
8546}
8547
dalecurtis88c240072015-12-09 02:11:188548void WebContentsImpl::MediaStartedPlaying(
billorr21c005d2016-11-17 03:57:048549 const WebContentsObserver::MediaPlayerInfo& media_info,
Mounir Lamouri0f5bdf52019-04-04 16:32:358550 const MediaPlayerId& id) {
Alexander Timin5fdeff22020-09-08 09:20:378551 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MediaStartedPlaying");
billorr21c005d2016-11-17 03:57:048552 if (media_info.has_video)
8553 currently_playing_video_count_++;
8554
Alexander Timin90c20c32020-08-12 15:28:328555 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8556 observer->MediaStartedPlaying(media_info, id);
8557 });
dalecurtis88c240072015-12-09 02:11:188558}
8559
8560void WebContentsImpl::MediaStoppedPlaying(
billorr21c005d2016-11-17 03:57:048561 const WebContentsObserver::MediaPlayerInfo& media_info,
Mounir Lamouri0f5bdf52019-04-04 16:32:358562 const MediaPlayerId& id,
Becca Hughes220bfc102017-11-14 18:24:078563 WebContentsObserver::MediaStoppedReason reason) {
Alexander Timin5fdeff22020-09-08 09:20:378564 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MediaStoppedPlaying");
billorr21c005d2016-11-17 03:57:048565 if (media_info.has_video)
8566 currently_playing_video_count_--;
8567
Alexander Timin90c20c32020-08-12 15:28:328568 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8569 observer->MediaStoppedPlaying(media_info, id, reason);
8570 });
billorr21c005d2016-11-17 03:57:048571}
8572
Mounir Lamouri0f5bdf52019-04-04 16:32:358573void WebContentsImpl::MediaResized(const gfx::Size& size,
8574 const MediaPlayerId& id) {
Alexander Timin5fdeff22020-09-08 09:20:378575 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MediaResized");
peconn257951522017-06-09 18:24:598576 cached_video_sizes_[id] = size;
8577
Alexander Timin90c20c32020-08-12 15:28:328578 observers_.ForEachObserver(
8579 [&](WebContentsObserver* observer) { observer->MediaResized(size, id); });
peconn257951522017-06-09 18:24:598580}
8581
Michael Crousee75c7a42020-07-31 21:11:558582void WebContentsImpl::MediaBufferUnderflow(const MediaPlayerId& id) {
Alexander Timin5fdeff22020-09-08 09:20:378583 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MediaBufferUnderflow");
Alexander Timin90c20c32020-08-12 15:28:328584 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8585 observer->MediaBufferUnderflow(id);
8586 });
Michael Crousee75c7a42020-07-31 21:11:558587}
8588
Peter E Conneccb34c22017-09-08 09:37:588589void WebContentsImpl::MediaEffectivelyFullscreenChanged(bool is_fullscreen) {
Alexander Timin5fdeff22020-09-08 09:20:378590 OPTIONAL_TRACE_EVENT1("content",
8591 "WebContentsImpl::MediaEffectivelyFullscreenChanged",
8592 "is_fullscreen", is_fullscreen);
Alexander Timin90c20c32020-08-12 15:28:328593 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8594 observer->MediaEffectivelyFullscreenChanged(is_fullscreen);
8595 });
Peter E Conneccb34c22017-09-08 09:37:588596}
8597
Peter Conn31c726a2017-08-17 11:07:348598base::Optional<gfx::Size> WebContentsImpl::GetFullscreenVideoSize() {
Mounir Lamouri0f5bdf52019-04-04 16:32:358599 base::Optional<MediaPlayerId> id =
Peter Conn31c726a2017-08-17 11:07:348600 media_web_contents_observer_->GetFullscreenVideoMediaPlayerId();
Jan Wilken Dörrie531be7ca2019-06-07 10:05:578601 if (id && base::Contains(cached_video_sizes_, id.value()))
Peter Conn31c726a2017-08-17 11:07:348602 return base::Optional<gfx::Size>(cached_video_sizes_[id.value()]);
Lei Zhang6410ec1a2019-01-31 21:38:588603 return base::nullopt;
peconn257951522017-06-09 18:24:598604}
8605
billorr21c005d2016-11-17 03:57:048606int WebContentsImpl::GetCurrentlyPlayingVideoCount() {
8607 return currently_playing_video_count_;
dalecurtis88c240072015-12-09 02:11:188608}
8609
Raymond Toye413650c2018-08-31 00:12:478610void WebContentsImpl::AudioContextPlaybackStarted(RenderFrameHost* host,
8611 int context_id) {
Alexander Timin5fdeff22020-09-08 09:20:378612 OPTIONAL_TRACE_EVENT1(
8613 "content", "WebContentsImpl::AudioContextPlaybackStarted",
8614 "render_frame_host", base::trace_event::ToTracedValue(host));
Raymond Toye413650c2018-08-31 00:12:478615 WebContentsObserver::AudioContextId audio_context_id(host, context_id);
Alexander Timin90c20c32020-08-12 15:28:328616 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8617 observer->AudioContextPlaybackStarted(audio_context_id);
8618 });
Raymond Toye413650c2018-08-31 00:12:478619}
8620
8621void WebContentsImpl::AudioContextPlaybackStopped(RenderFrameHost* host,
8622 int context_id) {
Alexander Timin5fdeff22020-09-08 09:20:378623 OPTIONAL_TRACE_EVENT1(
8624 "content", "WebContentsImpl::AudioContextPlaybackStopped",
8625 "render_frame_host", base::trace_event::ToTracedValue(host));
Raymond Toye413650c2018-08-31 00:12:478626 WebContentsObserver::AudioContextId audio_context_id(host, context_id);
Alexander Timin90c20c32020-08-12 15:28:328627 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8628 observer->AudioContextPlaybackStopped(audio_context_id);
8629 });
Raymond Toye413650c2018-08-31 00:12:478630}
8631
Chris Hamilton16ca64a2020-05-14 23:13:178632void WebContentsImpl::OnFrameAudioStateChanged(RenderFrameHost* host,
8633 bool is_audible) {
Alexander Timin5fdeff22020-09-08 09:20:378634 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnFrameAudioStateChanged",
8635 "render_frame_host",
8636 base::trace_event::ToTracedValue(host), "is_audible",
8637 is_audible);
Alexander Timin90c20c32020-08-12 15:28:328638 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8639 observer->OnFrameAudioStateChanged(host, is_audible);
8640 });
Chris Hamilton16ca64a2020-05-14 23:13:178641}
8642
evliu7f736f02019-11-07 17:43:508643media::MediaMetricsProvider::RecordAggregateWatchTimeCallback
8644WebContentsImpl::GetRecordAggregateWatchTimeCallback() {
Alexander Timin5fdeff22020-09-08 09:20:378645 OPTIONAL_TRACE_EVENT0("content",
8646 "WebContentsImpl::RecordAggregateWatchTimeCallback");
Becca Hughes53652442020-03-17 15:35:428647 if (!delegate_ || !delegate_->GetDelegateWeakPtr())
8648 return base::DoNothing();
8649
evliu7f736f02019-11-07 17:43:508650 return base::BindRepeating(
Becca Hughes53652442020-03-17 15:35:428651 [](base::WeakPtr<WebContentsDelegate> delegate, GURL last_committed_url,
8652 base::TimeDelta total_watch_time, base::TimeDelta time_stamp,
8653 bool has_video, bool has_audio) {
evliua283c9e2019-11-08 22:57:228654 content::MediaPlayerWatchTime watch_time(
8655 last_committed_url, last_committed_url.GetOrigin(),
8656 total_watch_time, time_stamp, has_video, has_audio);
evliu7f736f02019-11-07 17:43:508657
8658 // Save the watch time if the delegate is still alive.
8659 if (delegate)
8660 delegate->MediaWatchTimeChanged(watch_time);
8661 },
Becca Hughes53652442020-03-17 15:35:428662 delegate_->GetDelegateWeakPtr(), GetMainFrameLastCommittedURL());
evliu7f736f02019-11-07 17:43:508663}
8664
Ehsan Karamad1c631762019-05-13 23:04:018665RenderFrameHostImpl* WebContentsImpl::GetMainFrameForInnerDelegate(
8666 FrameTreeNode* frame_tree_node) {
8667 if (auto* web_contents = node_.GetInnerWebContentsInFrame(frame_tree_node))
8668 return web_contents->GetMainFrame();
8669 return nullptr;
8670}
8671
John Budorickee1c9512019-10-17 15:32:198672bool WebContentsImpl::IsFrameLowPriority(
8673 const RenderFrameHost* render_frame_host) {
8674 if (!delegate_)
8675 return false;
8676 return delegate_->IsFrameLowPriority(this, render_frame_host);
8677}
8678
Roger Tawa03ffdbd2020-01-16 18:12:548679void WebContentsImpl::IsClipboardPasteAllowed(
8680 const GURL& url,
8681 const ui::ClipboardFormatType& data_type,
8682 const std::string& data,
8683 IsClipboardPasteAllowedCallback callback) {
Dominique Fauteux-Chapleau99244382020-07-08 20:37:008684 ++suppress_unresponsive_renderer_count_;
Roger Tawa03ffdbd2020-01-16 18:12:548685 GetContentClient()->browser()->IsClipboardPasteAllowed(
Dominique Fauteux-Chapleau99244382020-07-08 20:37:008686 this, url, data_type, data,
8687 base::BindOnce(&WebContentsImpl::IsClipboardPasteAllowedWrapperCallback,
8688 weak_factory_.GetWeakPtr(), std::move(callback)));
8689}
8690
8691void WebContentsImpl::IsClipboardPasteAllowedWrapperCallback(
8692 IsClipboardPasteAllowedCallback callback,
8693 ClipboardPasteAllowed allowed) {
8694 std::move(callback).Run(allowed);
8695 --suppress_unresponsive_renderer_count_;
Roger Tawa03ffdbd2020-01-16 18:12:548696}
8697
Lan Weif81c6e7c2020-02-12 16:46:098698bool WebContentsImpl::HasSeenRecentScreenOrientationChange() {
8699 static constexpr base::TimeDelta kMaxInterval =
8700 base::TimeDelta::FromSeconds(1);
8701 base::TimeDelta delta =
8702 ui::EventTimeForNow() - last_screen_orientation_change_time_;
8703 // Return whether there is a screen orientation change happened in the recent
8704 // 1 second.
8705 return delta <= kMaxInterval;
8706}
8707
8708void WebContentsImpl::DidChangeScreenOrientation() {
8709 last_screen_orientation_change_time_ = ui::EventTimeForNow();
8710}
8711
Miyoung Shin8f2e1832020-04-27 09:00:028712bool WebContentsImpl::ShowPopupMenu(
Miyoung Shin4d947d22020-04-24 04:48:338713 RenderFrameHostImpl* render_frame_host,
Miyoung Shin8f2e1832020-04-27 09:00:028714 mojo::PendingRemote<blink::mojom::PopupMenuClient>* popup_client,
Miyoung Shin4d947d22020-04-24 04:48:338715 const gfx::Rect& bounds,
8716 int32_t item_height,
8717 double font_size,
8718 int32_t selected_item,
8719 std::vector<blink::mojom::MenuItemPtr>* menu_items,
8720 bool right_aligned,
8721 bool allow_multiple_selection) {
Alexander Timin5fdeff22020-09-08 09:20:378722 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ShowPopupMenu",
8723 "render_frame_host",
8724 base::trace_event::ToTracedValue(render_frame_host));
Alexander Timin90c20c32020-08-12 15:28:328725 for (auto& observer : observers_.observer_list()) {
Miyoung Shin8f2e1832020-04-27 09:00:028726 if (observer.ShowPopupMenu(render_frame_host, popup_client, bounds,
8727 item_height, font_size, selected_item,
8728 menu_items, right_aligned,
8729 allow_multiple_selection)) {
Miyoung Shin4d947d22020-04-24 04:48:338730 return true;
8731 }
8732 }
8733 return false;
8734}
8735
Francois Doraye6161152018-03-27 22:05:378736void WebContentsImpl::UpdateWebContentsVisibility(Visibility visibility) {
Alexander Timin5fdeff22020-09-08 09:20:378737 OPTIONAL_TRACE_EVENT1("content",
8738 "WebContentsImpl::UpdateWebContentsVisibility",
8739 "visibility", visibility);
Francois Doray3f2afbd2018-04-06 19:18:188740 // Occlusion is disabled when |features::kWebContentsOcclusion| is disabled
8741 // (for power and speed impact assessment) or when
8742 // |switches::kDisableBackgroundingOccludedWindowsForTesting| is specified on
8743 // the command line (to avoid flakiness in browser tests).
8744 const bool occlusion_is_disabled =
8745 !base::FeatureList::IsEnabled(features::kWebContentsOcclusion) ||
Francois Doraye6161152018-03-27 22:05:378746 base::CommandLine::ForCurrentProcess()->HasSwitch(
8747 switches::kDisableBackgroundingOccludedWindowsForTesting);
8748 if (occlusion_is_disabled && visibility == Visibility::OCCLUDED)
8749 visibility = Visibility::VISIBLE;
8750
tapted65ff2ea72016-03-01 23:39:008751 if (!did_first_set_visible_) {
Francois Doraye6161152018-03-27 22:05:378752 if (visibility == Visibility::VISIBLE) {
8753 // A WebContents created with CreateParams::initially_hidden = false
8754 // starts with GetVisibility() == Visibility::VISIBLE even though it is
8755 // not really visible. Call WasShown() when it becomes visible for real as
8756 // the page load mechanism and some WebContentsObserver rely on that.
tapted65ff2ea72016-03-01 23:39:008757 WasShown();
Francois Dorayfe4a1772018-02-17 04:17:098758 did_first_set_visible_ = true;
tapted65ff2ea72016-03-01 23:39:008759 }
Francois Doraye6161152018-03-27 22:05:378760
8761 // Trust the initial visibility of the WebContents and do not switch it to
8762 // HIDDEN or OCCLUDED before it becomes VISIBLE for real. Doing so would
8763 // result in destroying resources that would immediately be recreated (e.g.
8764 // UpdateWebContents(HIDDEN) can be called when a WebContents is added to a
8765 // hidden window that is about to be shown).
8766
tapted65ff2ea72016-03-01 23:39:008767 return;
8768 }
Francois Doraye6161152018-03-27 22:05:378769
8770 if (visibility == visibility_)
tapted65ff2ea72016-03-01 23:39:008771 return;
8772
Collin Baker989e0882019-11-01 01:27:178773 UpdateVisibilityAndNotifyPageAndView(visibility);
tapted65ff2ea72016-03-01 23:39:008774}
8775
aelias5252baa2016-04-10 01:18:028776void WebContentsImpl::UpdateOverridingUserAgent() {
Alexander Timin5fdeff22020-09-08 09:20:378777 OPTIONAL_TRACE_EVENT0("content",
8778 "WebContentsImpl::UpdateOverridingUserAgent");
mlamouri5cd9ae82017-02-18 11:05:098779 NotifyPreferencesChanged();
aelias5252baa2016-04-10 01:18:028780}
8781
avid53461d2016-02-25 17:15:048782void WebContentsImpl::SetJavaScriptDialogManagerForTesting(
8783 JavaScriptDialogManager* dialog_manager) {
Alexander Timin5fdeff22020-09-08 09:20:378784 OPTIONAL_TRACE_EVENT0(
8785 "content", "WebContentsImpl::SetJavaScriptDialogManagerForTesting");
avid53461d2016-02-25 17:15:048786 dialog_manager_ = dialog_manager;
8787}
8788
Julie Jeongeun Kim7d0986172019-12-04 03:17:258789void WebContentsImpl::RemoveReceiverSet(const std::string& interface_name) {
Alexander Timin5fdeff22020-09-08 09:20:378790 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RemoveReceiverSet",
8791 "interface_name", interface_name);
Julie Jeongeun Kim7d0986172019-12-04 03:17:258792 auto it = receiver_sets_.find(interface_name);
8793 if (it != receiver_sets_.end())
8794 receiver_sets_.erase(it);
rockotf62002a2016-09-15 00:08:598795}
8796
nzolghadrd87a308d2016-12-07 15:45:568797bool WebContentsImpl::AddDomainInfoToRapporSample(rappor::Sample* sample) {
Alexander Timin5fdeff22020-09-08 09:20:378798 OPTIONAL_TRACE_EVENT0("content",
8799 "WebContentsImpl::AddDomainInfoToRapporSample");
nzolghadrbbffc6c2017-05-25 17:56:398800 // Here we associate this metric to the main frame URL regardless of what
8801 // caused it.
nzolghadrd87a308d2016-12-07 15:45:568802 sample->SetStringField("Domain", ::rappor::GetDomainAndRegistrySampleFromGURL(
8803 GetLastCommittedURL()));
nzolghadrd87a308d2016-12-07 15:45:568804 return true;
8805}
8806
falken52a56e32016-12-08 05:02:408807void WebContentsImpl::ShowInsecureLocalhostWarningIfNeeded() {
Alexander Timin5fdeff22020-09-08 09:20:378808 OPTIONAL_TRACE_EVENT0(
8809 "content", "WebContentsImpl::ShowInsecureLocalhostWarningIfNeeded");
falken52a56e32016-12-08 05:02:408810 bool allow_localhost = base::CommandLine::ForCurrentProcess()->HasSwitch(
8811 switches::kAllowInsecureLocalhost);
8812 if (!allow_localhost)
8813 return;
8814
8815 content::NavigationEntry* entry = GetController().GetLastCommittedEntry();
Rob Wuf79b3ba2018-01-14 01:54:318816 if (!entry || !net::IsLocalhost(entry->GetURL()))
falken52a56e32016-12-08 05:02:408817 return;
8818
8819 content::SSLStatus ssl_status = entry->GetSSL();
Matt Mueller936511442019-09-03 18:15:128820 if (!net::IsCertStatusError(ssl_status.cert_status))
falken52a56e32016-12-08 05:02:408821 return;
8822
8823 GetMainFrame()->AddMessageToConsole(
Abhijeet Kandalkara5928a0a2019-03-13 05:04:428824 blink::mojom::ConsoleMessageLevel::kWarning,
falken52a56e32016-12-08 05:02:408825 base::StringPrintf("This site does not have a valid SSL "
8826 "certificate! Without SSL, your site's and "
8827 "visitors' data is vulnerable to theft and "
8828 "tampering. Get a valid SSL certificate before"
8829 " releasing your website to the public."));
8830}
8831
ekaramadf6750aa2017-06-06 18:29:428832bool WebContentsImpl::IsShowingContextMenuOnPage() const {
8833 return showing_context_menu_;
8834}
8835
Min Qina904f3302018-02-13 23:33:348836download::DownloadUrlParameters::RequestHeadersType
8837WebContentsImpl::ParseDownloadHeaders(const std::string& headers) {
Alexander Timin5fdeff22020-09-08 09:20:378838 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ParseDownloadHeaders",
8839 "headers", headers);
Min Qina904f3302018-02-13 23:33:348840 download::DownloadUrlParameters::RequestHeadersType request_headers;
Megan Jablonski2f6a4c52017-07-10 23:01:258841 for (const base::StringPiece& key_value : base::SplitStringPiece(
8842 headers, "\r\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) {
8843 std::vector<std::string> pair = base::SplitString(
8844 key_value, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
8845 if (2ul == pair.size())
8846 request_headers.push_back(make_pair(pair[0], pair[1]));
8847 }
8848 return request_headers;
8849}
8850
lukasza6f8ac622017-06-06 03:10:208851void WebContentsImpl::SetOpenerForNewContents(FrameTreeNode* opener,
8852 bool opener_suppressed) {
Alexander Timin5fdeff22020-09-08 09:20:378853 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetOpenerForNewContents");
lukasza6f8ac622017-06-06 03:10:208854 if (opener) {
8855 FrameTreeNode* new_root = GetFrameTree()->root();
8856
8857 // For the "original opener", track the opener's main frame instead, because
8858 // if the opener is a subframe, the opener tracking could be easily bypassed
8859 // by spawning from a subframe and deleting the subframe.
8860 // https://crbug.com/705316
8861 new_root->SetOriginalOpener(opener->frame_tree()->root());
8862
8863 if (!opener_suppressed) {
8864 new_root->SetOpener(opener);
8865 created_with_opener_ = true;
8866 }
8867 }
8868}
8869
Mounir Lamouri0f5bdf52019-04-04 16:32:358870void WebContentsImpl::MediaMutedStatusChanged(const MediaPlayerId& id,
8871 bool muted) {
Alexander Timin5fdeff22020-09-08 09:20:378872 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::MediaMutedStatusChanged",
8873 "muted", muted);
Alexander Timin90c20c32020-08-12 15:28:328874 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8875 observer->MediaMutedStatusChanged(id, muted);
8876 });
Becca Hughes9f6fd4b82017-06-15 10:01:408877}
8878
EhsanK2075c7e2017-08-21 02:42:398879void WebContentsImpl::SetVisibilityForChildViews(bool visible) {
Alexander Timin5fdeff22020-09-08 09:20:378880 OPTIONAL_TRACE_EVENT1("content",
8881 "WebContentsImpl::SetVisibilityForChildViews",
8882 "visible", visible);
EhsanK2075c7e2017-08-21 02:42:398883 GetMainFrame()->SetVisibilityForChildViews(visible);
8884}
8885
Alison Maher7f366dc62020-03-03 19:46:008886void WebContentsImpl::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) {
Alexander Timin5fdeff22020-09-08 09:20:378887 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnNativeThemeUpdated");
Alison Maher7f366dc62020-03-03 19:46:008888 DCHECK(native_theme_observer_.IsObserving(observed_theme));
8889
8890 bool using_dark_colors = observed_theme->ShouldUseDarkColors();
8891 ui::NativeTheme::PreferredColorScheme preferred_color_scheme =
8892 observed_theme->GetPreferredColorScheme();
8893 bool preferences_changed = false;
8894
8895 if (using_dark_colors_ != using_dark_colors) {
8896 using_dark_colors_ = using_dark_colors;
8897 preferences_changed = true;
8898 }
8899 if (preferred_color_scheme_ != preferred_color_scheme) {
8900 preferred_color_scheme_ = preferred_color_scheme;
8901 preferences_changed = true;
8902 }
8903
8904 if (preferences_changed)
8905 NotifyPreferencesChanged();
8906}
8907
Dave Tapuska58a099e2020-06-08 21:48:408908blink::mojom::FrameWidgetInputHandler*
8909WebContentsImpl::GetFocusedFrameWidgetInputHandler() {
8910 auto* focused_render_widget_host =
8911 GetFocusedRenderWidgetHost(GetMainFrame()->GetRenderWidgetHost());
8912 if (!focused_render_widget_host)
Dave Tapuskae782bea2019-07-09 16:21:518913 return nullptr;
Dave Tapuska58a099e2020-06-08 21:48:408914 return focused_render_widget_host->GetFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:518915}
8916
Alexander Timine3ec4192020-04-20 16:39:408917ukm::SourceId WebContentsImpl::GetCurrentPageUkmSourceId() {
8918 return GetMainFrame()->GetPageUkmSourceId();
8919}
8920
Yuzu Saijo232076f2020-05-29 07:14:028921std::set<RenderViewHostImpl*>
8922WebContentsImpl::GetRenderViewHostsIncludingBackForwardCached() {
8923 std::set<RenderViewHostImpl*> render_view_hosts;
8924
8925 // Add RenderViewHostImpls outside of BackForwardCache.
8926 for (auto& render_view_host : frame_tree_.render_view_hosts()) {
8927 render_view_hosts.insert(render_view_host.second);
8928 }
8929
8930 // Add RenderViewHostImpls in BackForwardCache.
8931 const auto& entries = GetController().GetBackForwardCache().GetEntries();
8932 for (const auto& entry : entries) {
8933 std::set<RenderViewHostImpl*> bfcached_hosts = entry->render_view_hosts;
8934 render_view_hosts.insert(bfcached_hosts.begin(), bfcached_hosts.end());
8935 }
8936
8937 return render_view_hosts;
8938}
8939
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:508940void WebContentsImpl::RenderFrameHostStateChanged(
8941 RenderFrameHost* render_frame_host,
8942 LifecycleState old_state,
8943 LifecycleState new_state) {
Alexander Timin5fdeff22020-09-08 09:20:378944 OPTIONAL_TRACE_EVENT2(
8945 "content", "WebContentsImpl::RenderFrameHostStateChanged",
8946 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host),
8947 "states",
8948 base::trace_event::TracedValue::Build(
8949 {{"old", base::trace_event::ValueToString(old_state)},
8950 {"new", base::trace_event::ValueToString(new_state)}}));
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:508951 if (render_frame_host->GetParent())
8952 return;
8953
8954 if (old_state == LifecycleState::kActive &&
8955 new_state != LifecycleState::kActive) {
8956 // TODO(sreejakshetty): Remove this reset when ColorChooser becomes
8957 // per-frame.
8958 // Close the color chooser popup when RenderFrameHost changes state from
8959 // kActive.
8960 color_chooser_.reset();
8961 }
8962}
8963
danakjc5ce67602020-09-23 20:06:578964void WebContentsImpl::GetFrameSequenceNumbersForDebugging(
8965 RenderFrameHostImpl* render_frame_host,
8966 int64_t& item_sequence_number,
8967 int64_t& document_sequence_number) {
8968 NavigationEntryImpl* entry =
8969 controller_.GetEntryWithUniqueID(render_frame_host->nav_entry_id());
8970 if (!entry)
8971 return;
8972
8973 FrameNavigationEntry* frame_entry =
8974 entry->GetFrameEntry(render_frame_host->frame_tree_node());
8975 if (frame_entry) {
8976 item_sequence_number = frame_entry->item_sequence_number();
8977 document_sequence_number = frame_entry->document_sequence_number();
8978 }
8979}
8980
[email protected]8ff00d72012-10-23 19:12:218981} // namespace content