blob: 6c85ecab8aacfa4fe2690fa023f773791893dcff [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"
Rakina Zata Amni4029b6d2020-07-28 02:36:20103#include "content/common/content_switches_internal.h"
Paul Meyer0c58c3712016-11-17 22:59:51104#include "content/common/drag_messages.h"
[email protected]f114fa42013-12-06 17:06:44105#include "content/common/frame_messages.h"
[email protected]1f3fc1d2014-04-03 14:50:17106#include "content/common/input_messages.h"
lfgdb5c4ed2016-03-04 23:09:07107#include "content/common/page_messages.h"
rockot5c478a72016-09-28 23:14:18108#include "content/common/render_message_filter.mojom.h"
[email protected]2c5569662011-03-22 20:45:02109#include "content/common/view_messages.h"
Albert J. Wong3c93c182018-09-27 17:29:43110#include "content/common/widget_messages.h"
Abigail Kleinabb428332019-09-13 18:26:21111#include "content/public/browser/accessibility_tree_formatter.h"
[email protected]31a71eaf2014-03-13 01:47:36112#include "content/public/browser/ax_event_notification_details.h"
[email protected]ccb797302011-12-15 16:55:11113#include "content/public/browser/browser_context.h"
Eric Seckler8652dcd52018-09-20 10:42:28114#include "content/public/browser/browser_task_traits.h"
Gabriel Charette790754c2018-03-16 21:32:59115#include "content/public/browser/browser_thread.h"
[email protected]87f3c082011-10-19 18:07:44116#include "content/public/browser/content_browser_client.h"
Lukasz Anforowicz8c4446dc2020-03-11 22:16:42117#include "content/public/browser/context_menu_params.h"
Ken Rockotce010f02019-12-12 23:32:32118#include "content/public/browser/device_service.h"
[email protected]e582fdd2011-12-20 16:48:17119#include "content/public/browser/download_manager.h"
Kent Tamura512a27e2018-10-04 00:49:32120#include "content/public/browser/file_select_listener.h"
ekaramada110f642016-12-21 19:47:28121#include "content/public/browser/focused_node_details.h"
Danyao Wanga78f3dd22020-03-05 05:31:27122#include "content/public/browser/global_routing_id.h"
[email protected]d9083482012-01-06 00:38:46123#include "content/public/browser/invalidate_type.h"
[email protected]71a88bb2013-02-01 22:05:15124#include "content/public/browser/javascript_dialog_manager.h"
skyf65d9bb2017-03-24 02:26:39125#include "content/public/browser/keyboard_event_processing_result.h"
[email protected]09d31d52012-03-11 22:30:27126#include "content/public/browser/load_notification_details.h"
[email protected]5b96836f2011-12-22 07:39:00127#include "content/public/browser/navigation_details.h"
[email protected]375fa1b2012-05-22 22:05:37128#include "content/public/browser/notification_details.h"
[email protected]be2510c02012-05-28 14:52:14129#include "content/public/browser/notification_service.h"
scottmg011d96e32016-06-29 19:15:08130#include "content/public/browser/notification_types.h"
[email protected]95640212014-07-26 18:14:30131#include "content/public/browser/render_widget_host_iterator.h"
Lukasz Anforowicze1b954d92017-10-30 21:28:06132#include "content/public/browser/restore_type.h"
estark5ea80e52015-06-19 18:43:12133#include "content/public/browser/security_style_explanations.h"
falken52a56e32016-12-08 05:02:40134#include "content/public/browser/ssl_status.h"
[email protected]4c3a23582012-08-18 08:54:34135#include "content/public/browser/storage_partition.h"
[email protected]674bc592011-12-20 23:00:42136#include "content/public/browser/web_contents_delegate.h"
Julie Jeongeun Kim7d0986172019-12-04 03:17:25137#include "content/public/browser/web_contents_receiver_set.h"
Lei Zhangee3b63ad2018-06-06 23:25:31138#include "content/public/browser/web_ui_controller.h"
[email protected]e091df82011-10-11 18:13:21139#include "content/public/common/bindings_policy.h"
alexmosc9e76ec2016-05-16 22:59:37140#include "content/public/common/child_process_host.h"
Hans Wennborg5ffd1392019-10-16 11:00:02141#include "content/public/common/content_client.h"
[email protected]54087fe2011-10-28 22:02:48142#include "content/public/common/content_constants.h"
Francois Doray3f2afbd2018-04-06 19:18:18143#include "content/public/common/content_features.h"
[email protected]64d69de42012-02-06 00:19:54144#include "content/public/common/content_switches.h"
Leon Han963dc182018-11-06 05:41:48145#include "content/public/common/referrer_type_converters.h"
[email protected]04cbd3d2013-12-04 04:58:20146#include "content/public/common/result_codes.h"
[email protected]f16cc6782013-12-16 23:42:57147#include "content/public/common/url_utils.h"
danakjffc8baf2019-10-10 23:49:42148#include "content/public/common/use_zoom_for_dsf_policy.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20149#include "media/base/media_switches.h"
Max Morinddebb972018-09-20 10:04:14150#include "media/base/user_input_monitor.h"
wjmaclean64951902016-04-29 20:59:12151#include "net/base/url_util.h"
[email protected]8bfc8272013-09-09 20:10:53152#include "net/http/http_cache.h"
153#include "net/http/http_transaction_factory.h"
David Van Clevef99881632020-07-16 19:41:13154#include "net/http/http_util.h"
rhalavati0fbaeef32017-06-01 15:56:30155#include "net/traffic_annotation/network_traffic_annotation.h"
Scott Violet02e38b92018-03-27 23:42:14156#include "ppapi/buildflags/buildflags.h"
Mounir Lamourifd9dcefa2017-07-06 10:26:55157#include "services/metrics/public/cpp/ukm_recorder.h"
John Abd-El-Malekb175a612018-12-03 20:11:58158#include "services/network/public/cpp/features.h"
arthursonzognib93a4472020-04-10 07:38:00159#include "services/network/public/cpp/web_sandbox_flags.h"
160#include "services/network/public/mojom/web_sandbox_flags.mojom.h"
rockot734fb662016-10-15 16:41:30161#include "services/service_manager/public/cpp/interface_provider.h"
Becca Hughes6daf5662018-06-27 16:50:54162#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
Blink Reformata30d4232018-04-07 15:31:06163#include "third_party/blink/public/common/mime_util/mime_util.h"
danakj938b37a62019-09-24 18:35:54164#include "third_party/blink/public/common/page/page_zoom.h"
Miyoung Shin5d77f72072020-10-09 15:14:20165#include "third_party/blink/public/common/page_state/page_state.h"
166#include "third_party/blink/public/common/page_state/page_state_serialization.h"
Sergio Villar Senin9d9d4f52019-10-15 10:57:57167#include "third_party/blink/public/common/security/security_style.h"
Gyuyoung Kim1ac4ca782020-09-11 03:32:51168#include "third_party/blink/public/common/web_preferences/web_preferences.h"
Abhijeet Kandalkarde7348e2020-01-13 06:06:54169#include "third_party/blink/public/mojom/frame/frame.mojom.h"
Dave Tapuskaa4189512019-10-15 20:27:34170#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
Takuto Ikutaaa3b796c2019-02-06 02:54:56171#include "third_party/blink/public/mojom/loader/pause_subresource_loading_handle.mojom.h"
Antonio Gomes0d42960a2019-06-05 12:35:51172#include "third_party/blink/public/mojom/mediastream/media_stream.mojom-shared.h"
halton.huoca2eabd2015-07-06 08:17:40173#include "third_party/skia/include/core/SkBitmap.h"
dmazzonid95ae842016-04-12 21:17:39174#include "ui/accessibility/ax_tree_combiner.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20175#include "ui/base/device_form_factor.h"
Mugdha Lakhani0a0d7862020-07-29 09:58:45176#if defined(USE_AURA)
177#include "ui/aura/window.h"
178#endif
[email protected]a08412b62012-05-29 21:28:56179#include "ui/base/layout.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20180#include "ui/base/ui_base_features.h"
181#include "ui/base/ui_base_switches.h"
182#include "ui/display/screen.h"
Daniel Cheng90196c82018-04-25 21:49:14183#include "ui/events/base_event_utils.h"
chongz4a9751942016-08-17 17:49:39184#include "ui/events/blink/web_input_event_traits.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20185#include "ui/gfx/animation/animation.h"
[email protected]66bd5512012-08-01 02:02:52186#include "ui/gl/gl_switches.h"
[email protected]3c733bde2010-12-21 19:56:31187
ekaramada110f642016-12-21 19:47:28188#if defined(OS_WIN)
189#include "content/browser/renderer_host/dip_util.h"
190#include "ui/gfx/geometry/dip_util.h"
191#endif
192
[email protected]583418cc2013-01-17 14:01:10193#if defined(OS_ANDROID)
mfomitchev2b8b066a2016-01-28 19:23:15194#include "content/browser/android/date_time_chooser_android.h"
sammcf5f1b0f2016-09-20 23:05:11195#include "content/browser/android/java_interfaces_impl.h"
Leon Hanccb985f2019-08-26 02:43:24196#include "content/browser/android/nfc_host.h"
[email protected]155c7f22013-12-09 17:07:18197#include "content/browser/web_contents/web_contents_android.h"
Ke He31d0bb02018-02-24 07:16:24198#include "services/device/public/mojom/nfc.mojom.h"
Mugdha Lakhani0a0d7862020-07-29 09:58:45199#include "ui/android/view_android.h"
mcnee336ea2c2017-05-23 22:50:59200#else // !OS_ANDROID
201#include "content/browser/host_zoom_map_impl.h"
mfomitchev2b8b066a2016-01-28 19:23:15202#endif // OS_ANDROID
[email protected]583418cc2013-01-17 14:01:10203
brettw4b461082016-11-19 18:55:16204#if BUILDFLAG(ENABLE_PLUGINS)
zqzhang181047e62016-07-01 13:37:17205#include "content/browser/media/session/pepper_playback_observer.h"
Lei Zhangebcc6302018-01-12 19:46:45206#endif
zqzhang181047e62016-07-01 13:37:17207
[email protected]8ff00d72012-10-23 19:12:21208namespace content {
Abigail Kleinaa898742019-11-01 02:31:25209
210using AccessibilityEventCallback =
211 base::RepeatingCallback<void(const std::string&)>;
212
[email protected]420ae012009-04-24 05:16:32213namespace {
214
[email protected]960b0372014-05-19 18:01:00215const int kMinimumDelayBetweenLoadingUpdatesMS = 100;
[email protected]82114f52012-03-20 22:53:41216const char kDotGoogleDotCom[] = ".google.com";
[email protected]ca406032011-07-19 21:53:05217
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:50218using LifecycleState = RenderFrameHostImpl::LifecycleState;
219
Alexander Timin33bd754c02020-03-10 22:50:18220// TODO(crbug.com/1059903): Clean up after the initial investigation.
221constexpr base::Feature kCheckWebContentsAccessFromNonCurrentFrame{
222 "CheckWebContentsAccessFromNonCurrentFrame",
223 base::FEATURE_DISABLED_BY_DEFAULT};
224
Avi Drissmana9114822018-03-23 18:25:55225base::LazyInstance<std::vector<
226 WebContentsImpl::FriendWrapper::CreatedCallback>>::DestructorAtExit
227 g_created_callbacks = LAZY_INSTANCE_INITIALIZER;
[email protected]cbb1ef592013-06-05 19:49:46228
dcheng57e39e22016-01-21 00:25:38229bool HasMatchingProcess(FrameTree* tree, int render_process_id) {
230 for (FrameTreeNode* node : tree->Nodes()) {
231 if (node->current_frame_host()->GetProcess()->GetID() == render_process_id)
232 return true;
alexmos4cf2aa32015-07-15 23:40:43233 }
dcheng57e39e22016-01-21 00:25:38234 return false;
[email protected]95640212014-07-26 18:14:30235}
236
kenrb19221852016-04-29 17:21:40237bool HasMatchingWidgetHost(FrameTree* tree, RenderWidgetHost* host) {
238 // This method scans the frame tree rather than checking whether
239 // host->delegate() == this, which allows it to return false when the host
240 // for a frame that is pending or pending deletion.
241 if (!host)
242 return false;
243
244 for (FrameTreeNode* node : tree->Nodes()) {
245 if (node->current_frame_host()->GetRenderWidgetHost() == host)
246 return true;
247 }
248 return false;
249}
250
dmazzonif8a31042016-12-03 00:52:13251void UpdateAccessibilityModeOnFrame(RenderFrameHost* frame_host) {
252 static_cast<RenderFrameHostImpl*>(frame_host)->UpdateAccessibilityMode();
[email protected]95640212014-07-26 18:14:30253}
254
dtseng0dd3fa12015-07-22 19:00:52255void ResetAccessibility(RenderFrameHost* rfh) {
256 static_cast<RenderFrameHostImpl*>(rfh)->AccessibilityReset();
257}
258
Ian Clelland5cbaaf82017-11-27 22:00:03259RenderFrameHostImpl* FindOpenerRFH(const WebContents::CreateParams& params) {
260 RenderFrameHostImpl* opener_rfh = nullptr;
alexmose201c7cd2015-06-10 17:14:21261 if (params.opener_render_frame_id != MSG_ROUTING_NONE) {
Ian Clelland5cbaaf82017-11-27 22:00:03262 opener_rfh = RenderFrameHostImpl::FromID(params.opener_render_process_id,
263 params.opener_render_frame_id);
alexmose201c7cd2015-06-10 17:14:21264 }
Ian Clelland5cbaaf82017-11-27 22:00:03265 return opener_rfh;
lukasza6f8ac622017-06-06 03:10:20266}
267
Dominick Ng37a15052018-07-17 23:56:35268// Returns |true| if |type| is the kind of user input that should trigger the
269// user interaction observers.
270bool IsUserInteractionInputType(blink::WebInputEvent::Type type) {
271 // Ideally, this list would be based more off of
272 // https://whatwg.org/C/interaction.html#triggered-by-user-activation.
Dave Tapuska347d60a2020-04-21 23:55:47273 return type == blink::WebInputEvent::Type::kMouseDown ||
274 type == blink::WebInputEvent::Type::kGestureScrollBegin ||
275 type == blink::WebInputEvent::Type::kTouchStart ||
276 type == blink::WebInputEvent::Type::kRawKeyDown;
Dominick Ng37a15052018-07-17 23:56:35277}
278
Pavel Feldman3c1842b2017-08-02 05:00:16279// Ensures that OnDialogClosed is only called once.
280class CloseDialogCallbackWrapper
281 : public base::RefCountedThreadSafe<CloseDialogCallbackWrapper> {
282 public:
Avi Drissmane04d3992017-10-05 15:11:36283 using CloseCallback =
284 base::OnceCallback<void(bool, bool, const base::string16&)>;
285
286 explicit CloseDialogCallbackWrapper(CloseCallback callback)
287 : callback_(std::move(callback)) {}
Pavel Feldman3c1842b2017-08-02 05:00:16288
289 void Run(bool dialog_was_suppressed,
290 bool success,
291 const base::string16& user_input) {
Avi Drissmane04d3992017-10-05 15:11:36292 if (callback_.is_null())
Pavel Feldman3c1842b2017-08-02 05:00:16293 return;
Avi Drissmane04d3992017-10-05 15:11:36294 std::move(callback_).Run(dialog_was_suppressed, success, user_input);
Pavel Feldman3c1842b2017-08-02 05:00:16295 }
296
297 private:
298 friend class base::RefCountedThreadSafe<CloseDialogCallbackWrapper>;
Fergal Daly55b6d722020-09-11 07:56:33299 ~CloseDialogCallbackWrapper() = default;
Avi Drissmane04d3992017-10-05 15:11:36300
301 CloseCallback callback_;
Pavel Feldman3c1842b2017-08-02 05:00:16302};
303
Arthur Sonzogni929d29f2018-09-17 14:19:44304bool FrameCompareDepth(RenderFrameHostImpl* a, RenderFrameHostImpl* b) {
305 return a->frame_tree_node()->depth() < b->frame_tree_node()->depth();
306}
307
Raymes Khoury58373df2019-08-06 06:29:20308bool AreValidRegisterProtocolHandlerArguments(const std::string& protocol,
309 const GURL& url,
310 const url::Origin& origin) {
311 ChildProcessSecurityPolicyImpl* policy =
312 ChildProcessSecurityPolicyImpl::GetInstance();
313 if (policy->IsPseudoScheme(protocol))
314 return false;
315
316 url::Origin url_origin = url::Origin::Create(url);
317 if (url_origin.opaque())
318 return false;
319
320 if (!url_origin.IsSameOriginWith(origin))
321 return false;
322
323 return true;
324}
325
yilkal796e89e2019-10-02 23:58:28326void RecordMaxFrameCountUMA(size_t max_frame_count) {
327 UMA_HISTOGRAM_COUNTS_10000("Navigation.MainFrame.MaxFrameCount",
328 max_frame_count);
329}
330
Jeremy Roman03ce13ce2020-05-29 22:16:57331// Returns whether the condition provided applies to any inner contents.
332// This check is not recursive (however, the predicate provided may itself
333// recurse each contents' own inner contents).
334//
335// For example, if this is used to aggregate state from inner contents to outer
336// contents, then that propagation will gather transitive descendants without
337// need for this helper to do so. In fact, in such cases recursing on inner
338// contents here would make that operation quadratic rather than linear.
339template <typename Functor>
340bool AnyInnerWebContents(WebContents* web_contents, const Functor& f) {
341 const auto& inner_contents = web_contents->GetInnerWebContents();
342 return std::any_of(inner_contents.begin(), inner_contents.end(), f);
343}
344
Xuehui Xieb2300ae42020-06-09 20:25:05345std::vector<RenderFrameHost*> GetAllFramesImpl(FrameTree& frame_tree,
346 bool include_pending) {
347 std::vector<RenderFrameHost*> frame_hosts;
348 for (FrameTreeNode* node : frame_tree.Nodes()) {
349 frame_hosts.push_back(node->current_frame_host());
350 if (include_pending) {
351 RenderFrameHostImpl* pending_frame_host =
352 node->render_manager()->speculative_frame_host();
353 if (pending_frame_host)
354 frame_hosts.push_back(pending_frame_host);
355 }
356 }
357 return frame_hosts;
358}
359
360int SendToAllFramesImpl(FrameTree& frame_tree,
361 bool include_pending,
362 IPC::Message* message) {
363 int number_of_messages = 0;
364 std::vector<RenderFrameHost*> frame_hosts =
365 GetAllFramesImpl(frame_tree, include_pending);
366 for (RenderFrameHost* rfh : frame_hosts) {
367 if (!rfh->IsRenderFrameLive())
368 continue;
369
370 ++number_of_messages;
371 IPC::Message* message_copy = new IPC::Message(*message);
372 message_copy->set_routing_id(rfh->GetRoutingID());
373 rfh->Send(message_copy);
374 }
375 delete message;
376 return number_of_messages;
377}
378
Avi Drissman33972942020-06-19 14:16:01379// Returns the set of all WebContentses that are reachable from |web_contents|
380// by applying some combination of WebContents::GetOriginalOpener() and
381// WebContents::GetOuterWebContents(). The |web_contents| parameter will be
382// included in the returned set.
383base::flat_set<WebContentsImpl*> GetAllOpeningWebContents(
384 WebContentsImpl* web_contents) {
385 base::flat_set<WebContentsImpl*> result;
386 base::flat_set<WebContentsImpl*> current;
387
388 current.insert(web_contents);
389
390 while (!current.empty()) {
391 WebContentsImpl* current_contents = *current.begin();
392 current.erase(current.begin());
393 auto insert_result = result.insert(current_contents);
394
395 if (insert_result.second) {
396 RenderFrameHostImpl* opener_rfh = current_contents->GetOriginalOpener();
397 if (opener_rfh) {
398 current.insert(static_cast<WebContentsImpl*>(
399 WebContents::FromRenderFrameHost(opener_rfh)));
400 }
401
402 WebContentsImpl* outer_contents = current_contents->GetOuterWebContents();
403 if (outer_contents)
404 current.insert(outer_contents);
405 }
406 }
407
408 return result;
409}
410
Rakina Zata Amni4029b6d2020-07-28 02:36:20411#if defined(OS_ANDROID)
412float GetDeviceScaleAdjustment(int min_width) {
413 static const float kMinFSM = 1.05f;
414 static const int kWidthForMinFSM = 320;
415 static const float kMaxFSM = 1.3f;
416 static const int kWidthForMaxFSM = 800;
417
418 if (min_width <= kWidthForMinFSM)
419 return kMinFSM;
420 if (min_width >= kWidthForMaxFSM)
421 return kMaxFSM;
422
423 // The font scale multiplier varies linearly between kMinFSM and kMaxFSM.
424 float ratio = static_cast<float>(min_width - kWidthForMinFSM) /
425 (kWidthForMaxFSM - kWidthForMinFSM);
426 return ratio * (kMaxFSM - kMinFSM) + kMinFSM;
427}
428#endif
429
Avi Drissman33972942020-06-19 14:16:01430// Used to attach the "set of fullscreen contents" to a browser context. Storing
431// sets of WebContents on their browser context is done for two reasons. One,
432// related WebContentses must necessarily share a browser context, so this saves
433// lookup time by restricting to one specific browser context. Two, separating
434// by browser context is preemptive paranoia about keeping things separate.
435class FullscreenContentsHolder : public base::SupportsUserData::Data {
436 public:
437 FullscreenContentsHolder() = default;
438 ~FullscreenContentsHolder() override = default;
439
440 FullscreenContentsHolder(const FullscreenContentsHolder&) = delete;
441 FullscreenContentsHolder& operator=(const FullscreenContentsHolder&) = delete;
442
443 base::flat_set<WebContentsImpl*>* set() { return &set_; }
444
445 private:
446 base::flat_set<WebContentsImpl*> set_;
447};
448
449const char kFullscreenContentsSet[] = "fullscreen-contents";
450
451base::flat_set<WebContentsImpl*>* FullscreenContentsSet(
452 BrowserContext* browser_context) {
453 auto* set_holder = static_cast<FullscreenContentsHolder*>(
454 browser_context->GetUserData(kFullscreenContentsSet));
455 if (!set_holder) {
456 auto new_holder = std::make_unique<FullscreenContentsHolder>();
457 set_holder = new_holder.get();
458 browser_context->SetUserData(kFullscreenContentsSet, std::move(new_holder));
459 }
460
461 return set_holder->set();
462}
463
Mike Wasserman5b7d3bf2020-08-21 21:52:26464// Returns true if |host| has the Window Placement permission granted.
Mike Wassermandb8f4f02020-10-06 01:18:37465bool IsWindowPlacementGranted(RenderFrameHost* host) {
Mike Wasserman5b7d3bf2020-08-21 21:52:26466 auto* controller =
467 PermissionControllerImpl::FromBrowserContext(host->GetBrowserContext());
468 return controller && controller->GetPermissionStatusForFrame(
469 PermissionType::WINDOW_PLACEMENT, host,
470 host->GetLastCommittedURL()) ==
471 blink::mojom::PermissionStatus::GRANTED;
472}
473
Mike Wassermanb6bc0152020-08-25 22:46:20474// Adjust the requested |bounds| for opening or placing a window and return the
475// id of the display where the window will be placed. The bounds may not extend
476// outside a single screen's work area, and the |host| requires permission to
477// specify bounds on a screen other than its current screen.
Mike Wassermandabad612020-08-13 04:26:27478// TODO(crbug.com/897300): These adjustments are inaccurate for window.open(),
479// which specifies the inner content size, and for window.moveTo, resizeTo, etc.
480// calls on newly created windows, which may pass empty sizes or positions to
481// indicate uninitialized placement information in the renderer. Constraints
482// enforced later should resolve most inaccuracies, but this early enforcement
483// is needed to ensure bounds indicate the appropriate display.
Mike Wassermanb6bc0152020-08-25 22:46:20484int64_t AdjustRequestedWindowBounds(gfx::Rect* bounds, RenderFrameHost* host) {
Mike Wassermandabad612020-08-13 04:26:27485 auto* screen = display::Screen::GetScreen();
Mike Wassermanb6bc0152020-08-25 22:46:20486 auto display = screen->GetDisplayMatching(*bounds);
Mike Wassermandabad612020-08-13 04:26:27487
488 // Check, but do not prompt, for permission to place windows on other screens.
489 // Sites generally need permission to get such bounds in the first place.
490 // Also clamp offscreen bounds to the window's current screen.
Mike Wassermandb8f4f02020-10-06 01:18:37491 if (!bounds->Intersects(display.bounds()) || !IsWindowPlacementGranted(host))
Mike Wassermandabad612020-08-13 04:26:27492 display = screen->GetDisplayNearestView(host->GetNativeView());
Mike Wassermandabad612020-08-13 04:26:27493
Mike Wassermanb6bc0152020-08-25 22:46:20494 bounds->AdjustToFit(display.work_area());
495 return display.id();
Mike Wassermandabad612020-08-13 04:26:27496}
497
lukasza6f8ac622017-06-06 03:10:20498} // namespace
499
Joel Hockey8c2011b22020-04-30 05:07:19500CreatedWindow::CreatedWindow() = default;
501CreatedWindow::CreatedWindow(std::unique_ptr<WebContentsImpl> contents,
502 GURL target_url)
503 : contents(std::move(contents)), target_url(std::move(target_url)) {}
504CreatedWindow::~CreatedWindow() = default;
505CreatedWindow::CreatedWindow(CreatedWindow&&) = default;
506CreatedWindow& CreatedWindow::operator=(CreatedWindow&&) = default;
507
Erik Chenbb8e738e2018-04-28 14:10:43508std::unique_ptr<WebContents> WebContents::Create(
509 const WebContents::CreateParams& params) {
Albert J. Wong65fe64d2019-09-20 02:48:14510 return WebContentsImpl::Create(params);
511}
512
513std::unique_ptr<WebContentsImpl> WebContentsImpl::Create(
514 const CreateParams& params) {
515 return CreateWithOpener(params, FindOpenerRFH(params));
[email protected]d1198fd2012-08-13 22:50:19516}
517
erikchenade1fef2018-05-02 22:07:57518std::unique_ptr<WebContents> WebContents::CreateWithSessionStorage(
[email protected]54944cde2012-12-09 09:24:59519 const WebContents::CreateParams& params,
[email protected]fdac6ade2013-07-20 01:06:30520 const SessionStorageNamespaceMap& session_storage_namespace_map) {
Alexander Timin5fdeff22020-09-08 09:20:37521 OPTIONAL_TRACE_EVENT0("content", "WebContents::CreateWithSessionStorage");
erikchenade1fef2018-05-02 22:07:57522 std::unique_ptr<WebContentsImpl> new_contents(
523 new WebContentsImpl(params.browser_context));
Ian Clelland5cbaaf82017-11-27 22:00:03524 RenderFrameHostImpl* opener_rfh = FindOpenerRFH(params);
525 FrameTreeNode* opener = nullptr;
526 if (opener_rfh)
527 opener = opener_rfh->frame_tree_node();
528 new_contents->SetOpenerForNewContents(opener, params.opener_suppressed);
[email protected]fdac6ade2013-07-20 01:06:30529
Fergal Daly55b6d722020-09-11 07:56:33530 for (const auto& it : session_storage_namespace_map) {
531 new_contents->GetController().SetSessionStorageNamespace(it.first,
532 it.second.get());
[email protected]fdac6ade2013-07-20 01:06:30533 }
534
Sean Toppingbbc4a2bd2019-01-30 02:16:14535 WebContentsImpl* outer_web_contents = nullptr;
Sam McNally69a33772018-06-27 16:54:12536 if (params.guest_delegate) {
537 // This makes |new_contents| act as a guest.
538 // For more info, see comment above class BrowserPluginGuest.
Albert J. Wongc55cc64d2018-10-12 02:50:04539 BrowserPluginGuest::CreateInWebContents(new_contents.get(),
540 params.guest_delegate);
Sean Toppingbbc4a2bd2019-01-30 02:16:14541 outer_web_contents = static_cast<WebContentsImpl*>(
542 params.guest_delegate->GetOwnerWebContents());
Sam McNally69a33772018-06-27 16:54:12543 }
544
[email protected]54944cde2012-12-09 09:24:59545 new_contents->Init(params);
Sean Toppingbbc4a2bd2019-01-30 02:16:14546 if (outer_web_contents)
547 outer_web_contents->InnerWebContentsCreated(new_contents.get());
[email protected]d1198fd2012-08-13 22:50:19548 return new_contents;
[email protected]a81343d232011-12-27 07:39:20549}
[email protected]746d3052012-05-22 15:15:47550
benwells5e7260d2017-03-20 23:36:33551void WebContentsImpl::FriendWrapper::AddCreatedCallbackForTesting(
nickf9acfbe2014-12-23 19:12:37552 const CreatedCallback& callback) {
[email protected]cbb1ef592013-06-05 19:49:46553 g_created_callbacks.Get().push_back(callback);
554}
555
benwells5e7260d2017-03-20 23:36:33556void WebContentsImpl::FriendWrapper::RemoveCreatedCallbackForTesting(
nickf9acfbe2014-12-23 19:12:37557 const CreatedCallback& callback) {
[email protected]cbb1ef592013-06-05 19:49:46558 for (size_t i = 0; i < g_created_callbacks.Get().size(); ++i) {
Robert Liao1db5a352019-06-05 20:57:34559 if (g_created_callbacks.Get().at(i) == callback) {
[email protected]cbb1ef592013-06-05 19:49:46560 g_created_callbacks.Get().erase(g_created_callbacks.Get().begin() + i);
561 return;
562 }
563 }
564}
565
avidf38c952015-10-27 13:45:13566WebContents* WebContents::FromRenderViewHost(RenderViewHost* rvh) {
Alexander Timin5fdeff22020-09-08 09:20:37567 OPTIONAL_TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
568 "WebContents::FromRenderViewHost", "render_view_host",
569 rvh);
avidf38c952015-10-27 13:45:13570 if (!rvh)
571 return nullptr;
[email protected]746d3052012-05-22 15:15:47572 return rvh->GetDelegate()->GetAsWebContents();
573}
574
[email protected]a86c0e962013-12-17 17:10:39575WebContents* WebContents::FromRenderFrameHost(RenderFrameHost* rfh) {
Alexander Timin5fdeff22020-09-08 09:20:37576 OPTIONAL_TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
577 "WebContents::FromRenderFrameHost", "render_frame_host",
578 base::trace_event::ToTracedValue(rfh));
avidf38c952015-10-27 13:45:13579 if (!rfh)
580 return nullptr;
Alexander Timin33bd754c02020-03-10 22:50:18581 if (!rfh->IsCurrent() && base::FeatureList::IsEnabled(
582 kCheckWebContentsAccessFromNonCurrentFrame)) {
583 // TODO(crbug.com/1059903): return nullptr here eventually.
584 base::debug::DumpWithoutCrashing();
585 }
avidf38c952015-10-27 13:45:13586 return static_cast<RenderFrameHostImpl*>(rfh)->delegate()->GetAsWebContents();
[email protected]a86c0e962013-12-17 17:10:39587}
588
ananta4b7467a52016-09-23 01:42:38589WebContents* WebContents::FromFrameTreeNodeId(int frame_tree_node_id) {
Alexander Timin5fdeff22020-09-08 09:20:37590 OPTIONAL_TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
591 "WebContents::FromFrameTreeNodeId",
592 "frame_tree_node_id", frame_tree_node_id);
ananta4b7467a52016-09-23 01:42:38593 FrameTreeNode* frame_tree_node =
594 FrameTreeNode::GloballyFindByID(frame_tree_node_id);
anantab8cfa3b2016-10-14 22:43:19595 if (!frame_tree_node)
596 return nullptr;
jam8c4edd02017-05-06 18:50:33597 return WebContentsImpl::FromFrameTreeNode(frame_tree_node);
ananta4b7467a52016-09-23 01:42:38598}
599
leon.han552e9de2017-02-09 14:37:30600void WebContents::SetScreenOrientationDelegate(
601 ScreenOrientationDelegate* delegate) {
602 ScreenOrientationProvider::SetDelegate(delegate);
603}
604
[email protected]7fff43e2013-05-21 20:21:10605// WebContentsImpl::DestructionObserver ----------------------------------------
606
607class WebContentsImpl::DestructionObserver : public WebContentsObserver {
608 public:
609 DestructionObserver(WebContentsImpl* owner, WebContents* watched_contents)
Fergal Daly09d6c762020-05-29 02:05:18610 : WebContentsObserver(watched_contents), owner_(owner) {}
[email protected]7fff43e2013-05-21 20:21:10611
612 // WebContentsObserver:
dchengc2282aa2014-10-21 12:07:58613 void WebContentsDestroyed() override {
[email protected]12a46832014-05-09 13:35:58614 owner_->OnWebContentsDestroyed(
615 static_cast<WebContentsImpl*>(web_contents()));
[email protected]7fff43e2013-05-21 20:21:10616 }
617
618 private:
619 WebContentsImpl* owner_;
620
621 DISALLOW_COPY_AND_ASSIGN(DestructionObserver);
622};
623
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:50624// TODO(sreejakshetty): Make |WebContentsImpl::ColorChooser| per-frame instead
625// of WebContents-owned.
Joel Hockey85b379d2017-12-11 10:42:13626// WebContentsImpl::ColorChooser ----------------------------------------------
Joel Hockey163835a2017-12-20 11:51:57627class WebContentsImpl::ColorChooser : public blink::mojom::ColorChooser {
Joel Hockey85b379d2017-12-11 10:42:13628 public:
629 ColorChooser(content::ColorChooser* chooser,
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20630 mojo::PendingReceiver<blink::mojom::ColorChooser> receiver,
631 mojo::PendingRemote<blink::mojom::ColorChooserClient> client)
Joel Hockey85b379d2017-12-11 10:42:13632 : chooser_(chooser),
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20633 receiver_(this, std::move(receiver)),
Joel Hockey85b379d2017-12-11 10:42:13634 client_(std::move(client)) {
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20635 receiver_.set_disconnect_handler(
Joel Hockey85b379d2017-12-11 10:42:13636 base::BindOnce([](content::ColorChooser* chooser) { chooser->End(); },
637 base::Unretained(chooser)));
638 }
[email protected]8ed16472014-04-11 19:02:48639
Joel Hockey85b379d2017-12-11 10:42:13640 ~ColorChooser() override { chooser_->End(); }
[email protected]8ed16472014-04-11 19:02:48641
Joel Hockey85b379d2017-12-11 10:42:13642 void SetSelectedColor(SkColor color) override {
Alexander Timin5fdeff22020-09-08 09:20:37643 OPTIONAL_TRACE_EVENT0("content",
644 "WebContentsImpl::ColorChooser::SetSelectedColor");
Joel Hockey85b379d2017-12-11 10:42:13645 chooser_->SetSelectedColor(color);
646 }
647
648 void DidChooseColorInColorChooser(SkColor color) {
Alexander Timin5fdeff22020-09-08 09:20:37649 OPTIONAL_TRACE_EVENT0(
650 "content",
651 "WebContentsImpl::ColorChooser::DidChooseColorInColorChooser");
Joel Hockey85b379d2017-12-11 10:42:13652 client_->DidChooseColor(color);
653 }
654
655 private:
656 // Color chooser that was opened by this tab.
657 std::unique_ptr<content::ColorChooser> chooser_;
658
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20659 // mojo receiver.
660 mojo::Receiver<blink::mojom::ColorChooser> receiver_;
Joel Hockey85b379d2017-12-11 10:42:13661
662 // mojo renderer client.
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20663 mojo::Remote<blink::mojom::ColorChooserClient> client_;
Joel Hockey85b379d2017-12-11 10:42:13664};
nicka0ac8382016-12-15 23:59:23665
lazyboy6ec48b2a2015-06-29 15:18:14666// WebContentsImpl::WebContentsTreeNode ----------------------------------------
lfg601233692017-03-06 22:45:44667WebContentsImpl::WebContentsTreeNode::WebContentsTreeNode(
668 WebContentsImpl* current_web_contents)
669 : current_web_contents_(current_web_contents),
670 outer_web_contents_(nullptr),
lazyboy6ec48b2a2015-06-29 15:18:14671 outer_contents_frame_tree_node_id_(
avallee0206f782016-07-28 18:55:33672 FrameTreeNode::kFrameTreeNodeInvalidId),
lfg601233692017-03-06 22:45:44673 focused_web_contents_(current_web_contents) {}
lazyboy6ec48b2a2015-06-29 15:18:14674
Fergal Daly55b6d722020-09-11 07:56:33675WebContentsImpl::WebContentsTreeNode::~WebContentsTreeNode() = default;
lazyboy6ec48b2a2015-06-29 15:18:14676
Lucas Furukawa Gadani99125822019-01-03 15:41:49677std::unique_ptr<WebContents>
678WebContentsImpl::WebContentsTreeNode::DisconnectFromOuterWebContents() {
Alexander Timin5fdeff22020-09-08 09:20:37679 OPTIONAL_TRACE_EVENT0("content",
680 "WebContentsTreeNode::DisconnectFromOuterWebContents");
Lucas Furukawa Gadani99125822019-01-03 15:41:49681 std::unique_ptr<WebContents> inner_contents =
682 outer_web_contents_->node_.DetachInnerWebContents(current_web_contents_);
683 OuterContentsFrameTreeNode()->RemoveObserver(this);
684 outer_contents_frame_tree_node_id_ = FrameTreeNode::kFrameTreeNodeInvalidId;
685 outer_web_contents_ = nullptr;
686 return inner_contents;
687}
688
paulmeyerfeafc2d2017-04-25 21:46:40689void WebContentsImpl::WebContentsTreeNode::AttachInnerWebContents(
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:50690 std::unique_ptr<WebContents> inner_web_contents,
691 RenderFrameHostImpl* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:37692 OPTIONAL_TRACE_EVENT0("content",
693 "WebContentsTreeNode::AttachInnerWebContents");
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:50694 WebContentsImpl* inner_web_contents_impl =
695 static_cast<WebContentsImpl*>(inner_web_contents.get());
696 WebContentsTreeNode& inner_web_contents_node = inner_web_contents_impl->node_;
697
698 inner_web_contents_node.focused_web_contents_ = nullptr;
699 inner_web_contents_node.outer_web_contents_ = current_web_contents_;
700 inner_web_contents_node.outer_contents_frame_tree_node_id_ =
701 render_frame_host->frame_tree_node()->frame_tree_node_id();
702
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18703 inner_web_contents_.push_back(std::move(inner_web_contents));
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:50704
705 render_frame_host->frame_tree_node()->AddObserver(&inner_web_contents_node);
Jeremy Roman03ce13ce2020-05-29 22:16:57706 current_web_contents_->InnerWebContentsAttached(inner_web_contents_impl);
paulmeyerfeafc2d2017-04-25 21:46:40707}
708
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18709std::unique_ptr<WebContents>
710WebContentsImpl::WebContentsTreeNode::DetachInnerWebContents(
paulmeyerfeafc2d2017-04-25 21:46:40711 WebContentsImpl* inner_web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:37712 OPTIONAL_TRACE_EVENT0(
713 "content",
714 "WebContentsImpl::WebContentsTreeNode::DetachInnerWebContents");
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18715 std::unique_ptr<WebContents> detached_contents;
716 for (std::unique_ptr<WebContents>& web_contents : inner_web_contents_) {
717 if (web_contents.get() == inner_web_contents) {
718 detached_contents = std::move(web_contents);
719 std::swap(web_contents, inner_web_contents_.back());
720 inner_web_contents_.pop_back();
Jeremy Roman03ce13ce2020-05-29 22:16:57721 current_web_contents_->InnerWebContentsDetached(inner_web_contents);
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18722 return detached_contents;
723 }
724 }
725
726 NOTREACHED();
727 return nullptr;
paulmeyerfeafc2d2017-04-25 21:46:40728}
729
lfga3e2bdc2017-03-07 20:44:01730FrameTreeNode*
731WebContentsImpl::WebContentsTreeNode::OuterContentsFrameTreeNode() const {
732 return FrameTreeNode::GloballyFindByID(outer_contents_frame_tree_node_id_);
lfg601233692017-03-06 22:45:44733}
734
lfga3e2bdc2017-03-07 20:44:01735void WebContentsImpl::WebContentsTreeNode::OnFrameTreeNodeDestroyed(
736 FrameTreeNode* node) {
Alexander Timin5fdeff22020-09-08 09:20:37737 OPTIONAL_TRACE_EVENT0("content",
738 "WebContentsTreeNode::OnFrameTreeNodeDestroyed");
lfga3e2bdc2017-03-07 20:44:01739 DCHECK_EQ(outer_contents_frame_tree_node_id_, node->frame_tree_node_id())
740 << "WebContentsTreeNode should only receive notifications for the "
741 "FrameTreeNode in its outer WebContents that hosts it.";
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18742
743 // Deletes |this| too.
744 outer_web_contents_->node_.DetachInnerWebContents(current_web_contents_);
lazyboy6ec48b2a2015-06-29 15:18:14745}
746
avallee0206f782016-07-28 18:55:33747void WebContentsImpl::WebContentsTreeNode::SetFocusedWebContents(
748 WebContentsImpl* web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:37749 OPTIONAL_TRACE_EVENT0("content",
750 "WebContentsTreeNode::SetFocusedWebContents");
avallee0206f782016-07-28 18:55:33751 DCHECK(!outer_web_contents())
752 << "Only the outermost WebContents tracks focus.";
753 focused_web_contents_ = web_contents;
754}
755
paulmeyerfeafc2d2017-04-25 21:46:40756WebContentsImpl*
757WebContentsImpl::WebContentsTreeNode::GetInnerWebContentsInFrame(
758 const FrameTreeNode* frame) {
759 auto ftn_id = frame->frame_tree_node_id();
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18760 for (auto& contents : inner_web_contents_) {
761 WebContentsImpl* impl = static_cast<WebContentsImpl*>(contents.get());
762 if (impl->node_.outer_contents_frame_tree_node_id() == ftn_id) {
763 return impl;
paulmeyerfeafc2d2017-04-25 21:46:40764 }
765 }
766 return nullptr;
767}
768
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18769std::vector<WebContentsImpl*>
770WebContentsImpl::WebContentsTreeNode::GetInnerWebContents() const {
771 std::vector<WebContentsImpl*> inner_web_contents;
772 for (auto& contents : inner_web_contents_)
773 inner_web_contents.push_back(static_cast<WebContentsImpl*>(contents.get()));
774
775 return inner_web_contents;
paulmeyerfeafc2d2017-04-25 21:46:40776}
777
Alexander Timin90c20c32020-08-12 15:28:32778// WebContentsObserverList -----------------------------------------------------
779WebContentsImpl::WebContentsObserverList::WebContentsObserverList() = default;
780WebContentsImpl::WebContentsObserverList::~WebContentsObserverList() = default;
781
782void WebContentsImpl::WebContentsObserverList::AddObserver(
783 WebContentsObserver* observer) {
784 observers_.AddObserver(observer);
785}
786
787void WebContentsImpl::WebContentsObserverList::RemoveObserver(
788 WebContentsObserver* observer) {
789 observers_.RemoveObserver(observer);
790}
791
[email protected]b172aee2012-04-10 17:05:26792// WebContentsImpl -------------------------------------------------------------
[email protected]420ae012009-04-24 05:16:32793
alexmose201c7cd2015-06-10 17:14:21794WebContentsImpl::WebContentsImpl(BrowserContext* browser_context)
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28795 : delegate_(nullptr),
[email protected]69e797f2013-04-30 01:10:22796 controller_(this, browser_context),
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28797 render_view_host_delegate_view_(nullptr),
alexmose201c7cd2015-06-10 17:14:21798 created_with_opener_(false),
Lucas Furukawa Gadani99125822019-01-03 15:41:49799 node_(this),
Fergal Daly09d6c762020-05-29 02:05:18800 frame_tree_(&controller_, this, this, this, this, this),
[email protected]6dfed692014-05-22 04:18:03801 is_load_to_different_document_(false),
[email protected]443b80e2010-12-14 00:42:23802 crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING),
803 crashed_error_code_(0),
[email protected]d5f942ba2008-09-26 19:30:34804 waiting_for_response_(false),
[email protected]fcf75d42013-12-03 20:11:26805 load_state_(net::LOAD_STATE_IDLE, base::string16()),
[email protected]094e5b22009-09-25 04:23:56806 upload_size_(0),
807 upload_position_(0),
dfalcantarae6b7b46752015-07-10 18:14:16808 is_resume_pending_(false),
[email protected]b4c84012014-04-28 19:51:10809 has_accessed_initial_document_(false),
Collin Bakerc5259962019-11-14 17:51:58810 visible_capturer_count_(0),
811 hidden_capturer_count_(0),
[email protected]fdd61c62009-04-22 19:22:57812 is_being_destroyed_(false),
813 notify_disconnection_(false),
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28814 dialog_manager_(nullptr),
[email protected]7ab1e7d62009-10-14 23:32:01815 is_showing_before_unload_dialog_(false),
gab0dccfef2015-05-20 18:43:39816 last_active_time_(base::TimeTicks::Now()),
[email protected]ebf40a72010-07-22 01:46:38817 closed_by_user_gesture_(false),
danakj938b37a62019-09-24 18:35:54818 minimum_zoom_percent_(
819 static_cast<int>(blink::kMinimumPageZoomFactor * 100)),
820 maximum_zoom_percent_(
821 static_cast<int>(blink::kMaximumPageZoomFactor * 100)),
w.shackleton49bcd392016-01-06 17:38:22822 zoom_scroll_remainder_(0),
[email protected]34ff1cfc2014-08-20 06:16:05823 force_disable_overscroll_content_(false),
[email protected]95640212014-07-26 18:14:30824 last_dialog_suppressed_(false),
waffles1c12bf402016-02-10 17:45:48825 accessibility_mode_(
Dominic Mazzoni21fb0282019-02-13 18:32:47826 GetContentClient()->browser()->GetAXModeForBrowserContext(
827 browser_context)),
avayvodcc85bbd2015-08-28 19:11:15828 audio_stream_monitor_(this),
Thomas Guilbert882c4cec2019-02-14 05:55:45829 media_web_contents_observer_(
830 std::make_unique<MediaWebContentsObserver>(this)),
mcnee336ea2c2017-05-23 22:50:59831#if !defined(OS_ANDROID)
mcnee432e47d2015-11-09 19:37:46832 page_scale_factor_is_one_(true),
mcnee336ea2c2017-05-23 22:50:59833#endif // !defined(OS_ANDROID)
qinmin72e8bd02016-10-21 19:35:37834 is_overlay_content_(false),
ekaramadf6750aa2017-06-06 18:29:42835 showing_context_menu_(false),
W. James MacLean62198672019-06-04 16:46:10836 text_autosizer_page_info_({0, 0, 1.f}),
shivanigithubcceeacf2020-03-06 20:00:27837 native_theme_observer_(this) {
Alexander Timin5fdeff22020-09-08 09:20:37838 TRACE_EVENT0("content", "WebContentsImpl::WebContentsImpl");
danakjf4b9e942019-11-29 15:43:04839 frame_tree_.SetFrameRemoveListener(base::BindRepeating(
840 &WebContentsImpl::OnFrameRemoved, base::Unretained(this)));
brettw4b461082016-11-19 18:55:16841#if BUILDFLAG(ENABLE_PLUGINS)
Fergal Daly55b6d722020-09-11 07:56:33842 pepper_playback_observer_ = std::make_unique<PepperPlaybackObserver>(this);
zqzhang181047e62016-07-01 13:37:17843#endif
blundelle75a8f92017-03-27 08:11:17844
Becca Hughes86334622018-07-09 21:29:38845#if defined(OS_ANDROID)
Elly Fong-Jonescdd7ae82019-02-20 23:26:33846 display_cutout_host_impl_ = std::make_unique<DisplayCutoutHostImpl>(this);
Becca Hughes86334622018-07-09 21:29:38847#endif
John Delaney732721e92020-02-07 23:11:27848
Alison Maher7f366dc62020-03-03 19:46:00849 ui::NativeTheme* native_theme = ui::NativeTheme::GetInstanceForWeb();
850 native_theme_observer_.Add(native_theme);
851 using_dark_colors_ = native_theme->ShouldUseDarkColors();
852 preferred_color_scheme_ = native_theme->GetPreferredColorScheme();
853
Mike Wassermanb213b9352020-04-16 00:32:34854 screen_change_monitor_ =
855 std::make_unique<ScreenChangeMonitor>(base::BindRepeating(
856 &WebContentsImpl::OnScreensChange, base::Unretained(this)));
857
John Delaney732721e92020-02-07 23:11:27858 // ConversionHost takes a weak ref on |this|, so it must be created outside of
859 // the initializer list.
Charlie Harrison405f6212020-04-14 21:57:32860 if (base::FeatureList::IsEnabled(features::kConversionMeasurement)) {
861 conversion_host_ = std::make_unique<ConversionHost>(this);
862 }
[email protected]332af7732009-03-11 13:21:35863}
initial.commit09911bf2008-07-26 23:55:29864
[email protected]b172aee2012-04-10 17:05:26865WebContentsImpl::~WebContentsImpl() {
Alexander Timin5fdeff22020-09-08 09:20:37866 TRACE_EVENT0("content", "WebContentsImpl::~WebContentsImpl");
867
creisba91ba82017-05-12 22:56:19868 // Imperfect sanity check against double free, given some crashes unexpectedly
869 // observed in the wild.
870 CHECK(!is_being_destroyed_);
871
872 // We generally keep track of is_being_destroyed_ to let other features know
873 // to avoid certain actions during destruction.
[email protected]420ae012009-04-24 05:16:32874 is_being_destroyed_ = true;
875
creis97867aa2017-02-17 18:39:45876 // A WebContents should never be deleted while it is notifying observers,
creisba91ba82017-05-12 22:56:19877 // since this will lead to a use-after-free as it continues to notify later
creis97867aa2017-02-17 18:39:45878 // observers.
Alexander Timin90c20c32020-08-12 15:28:32879 CHECK(!observers_.is_notifying_observers());
creis97867aa2017-02-17 18:39:45880
Avi Drissman33972942020-06-19 14:16:01881 FullscreenContentsSet(GetBrowserContext())->erase(this);
882
kenrb2a565f82015-09-02 20:24:59883 rwh_input_event_router_.reset();
884
Julie Jeongeun Kim7d0986172019-12-04 03:17:25885 for (auto& entry : receiver_sets_)
886 entry.second->CloseAllReceivers();
rockotf62002a2016-09-15 00:08:59887
avallee0206f782016-07-28 18:55:33888 WebContentsImpl* outermost = GetOutermostWebContents();
avallee9993fca2016-11-17 06:16:50889 if (this != outermost && ContainsOrIsFocusedWebContents()) {
avallee0206f782016-07-28 18:55:33890 // If the current WebContents is in focus, unset it.
avallee9993fca2016-11-17 06:16:50891 outermost->SetAsFocusedWebContentsIfNecessary();
avallee0206f782016-07-28 18:55:33892 }
893
Nick Carterd73635b2018-03-13 18:31:41894 if (mouse_lock_widget_)
James Hollyerd5c9de462020-03-10 19:02:45895 mouse_lock_widget_->RejectMouseLockOrUnlockIfNecessary(
896 blink::mojom::PointerLockResult::kElementDestroyed);
Nick Carterd73635b2018-03-13 18:31:41897
dcheng72be33c2016-01-21 04:11:31898 for (FrameTreeNode* node : frame_tree_.Nodes()) {
899 // Delete all RFHs pending shutdown, which will lead the corresponding RVHs
900 // to be shutdown and be deleted as well.
dcheng57e39e22016-01-21 00:25:38901 node->render_manager()->ClearRFHsPendingShutdown();
dcheng57e39e22016-01-21 00:25:38902 node->render_manager()->ClearWebUIInstances();
dcheng72be33c2016-01-21 04:11:31903 }
carlosk35f35af2015-12-01 10:55:40904
dcheng57e39e22016-01-21 00:25:38905 for (RenderWidgetHostImpl* widget : created_widgets_)
906 widget->DetachDelegate();
[email protected]b24b68a2012-09-24 21:57:26907 created_widgets_.clear();
908
[email protected]3ab9cb82011-06-03 18:02:07909 // Clear out any JavaScript state.
avi5d3b8692016-10-12 22:00:46910 if (dialog_manager_) {
avi6879fcf2017-01-21 05:27:53911 dialog_manager_->CancelDialogs(this, /*reset_state=*/true);
avi5d3b8692016-10-12 22:00:46912 }
[email protected]3ab9cb82011-06-03 18:02:07913
Joel Hockey85b379d2017-12-11 10:42:13914 color_chooser_.reset();
Rakina Zata Amni16196122018-11-14 02:14:00915 find_request_manager_.reset();
[email protected]da8543762012-03-20 08:52:20916
[email protected]420ae012009-04-24 05:16:32917 NotifyDisconnected();
[email protected]420ae012009-04-24 05:16:32918
[email protected]ca13a442012-04-17 14:00:12919 // Notify any observer that have a reference on this WebContents.
[email protected]8ff00d72012-10-23 19:12:21920 NotificationService::current()->Notify(
921 NOTIFICATION_WEB_CONTENTS_DESTROYED,
922 Source<WebContents>(this),
923 NotificationService::NoDetails());
[email protected]420ae012009-04-24 05:16:32924
Arthur Sonzogni5a9a88c2018-10-18 13:16:00925 // Destroy all subframes now. This notifies observers.
926 GetMainFrame()->ResetChildren();
[email protected]df0c843f2014-05-23 20:37:23927 GetRenderManager()->ResetProxyHosts();
[email protected]c06c58c2014-03-12 20:31:59928
clamy0e119882015-07-31 16:12:33929 // Manually call the observer methods for the root frame tree node. It is
930 // necessary to manually delete all objects tracking navigations
931 // (NavigationHandle, NavigationRequest) for observers to be properly
932 // notified of these navigations stopping before the WebContents is
933 // destroyed.
[email protected]df0c843f2014-05-23 20:37:23934 RenderFrameHostManager* root = GetRenderManager();
naskob21fe4872015-02-24 14:15:56935
Lowell Manners20250112019-10-18 15:06:15936 GetController().GetBackForwardCache().Shutdown();
937
naskob21fe4872015-02-24 14:15:56938 root->current_frame_host()->SetRenderFrameCreated(false);
clamyfc3850d2018-02-23 14:35:28939 root->current_frame_host()->ResetNavigationRequests();
clamy0e119882015-07-31 16:12:33940
Arthur Hemeryc3380172018-01-22 14:00:17941 // Do not update state as the WebContents is being destroyed.
Arthur Hemery241b9392019-10-24 11:08:41942 frame_tree_.root()->ResetNavigationRequest(true);
Arthur Hemeryc3380172018-01-22 14:00:17943 if (root->speculative_frame_host()) {
danakjf2342432019-05-15 21:46:09944 root->speculative_frame_host()->DeleteRenderFrame(
945 FrameDeleteIntention::kSpeculativeMainFrameForShutdown);
Arthur Hemeryc3380172018-01-22 14:00:17946 root->speculative_frame_host()->SetRenderFrameCreated(false);
clamyfc3850d2018-02-23 14:35:28947 root->speculative_frame_host()->ResetNavigationRequests();
clamy0e119882015-07-31 16:12:33948 }
[email protected]f273ee52013-10-18 16:05:27949
brettw4b461082016-11-19 18:55:16950#if BUILDFLAG(ENABLE_PLUGINS)
zqzhang181047e62016-07-01 13:37:17951 // Call this before WebContentsDestroyed() is broadcasted since
952 // AudioFocusManager will be destroyed after that.
953 pepper_playback_observer_.reset();
954#endif // defined(ENABLED_PLUGINS)
955
Chris Hamiltondf0d72cd2018-05-29 16:23:53956 // If audio is playing then notify external observers of the audio stream
957 // disappearing.
958 if (is_currently_audible_) {
959 is_currently_audible_ = false;
Alexander Timin90c20c32020-08-12 15:28:32960 observers_.ForEachObserver([&](WebContentsObserver* observer) {
961 observer->OnAudioStateChanged(false);
962 });
Chris Hamiltondf0d72cd2018-05-29 16:23:53963 if (GetOuterWebContents())
964 GetOuterWebContents()->OnAudioStateChanged();
965 }
966
Alexander Timin90c20c32020-08-12 15:28:32967 observers_.ForEachObserver([&](WebContentsObserver* observer) {
968 observer->FrameDeleted(root->current_frame_host());
969 });
970 observers_.ForEachObserver([&](WebContentsObserver* observer) {
971 observer->RenderViewDeleted(root->current_host());
972 });
Kevin McNee576bb5d82019-05-29 16:47:51973#if defined(OS_ANDROID)
974 // For simplicity, destroy the Java WebContents before we notify of the
975 // destruction of the WebContents.
976 ClearWebContentsAndroid();
977#endif
978
Alexander Timin90c20c32020-08-12 15:28:32979 observers_.ForEachObserver(
980 [&](WebContentsObserver* observer) { observer->WebContentsDestroyed(); });
Becca Hughesd11d6502018-07-31 17:01:28981 if (display_cutout_host_impl_)
982 display_cutout_host_impl_->WebContentsDestroyed();
983
Alexander Timin90c20c32020-08-12 15:28:32984 observers_.ForEachObserver(
985 [&](WebContentsObserver* observer) { observer->ResetWebContents(); });
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28986 SetDelegate(nullptr);
[email protected]b5a1d11c2011-02-17 03:09:42987}
988
erikchen50735fd2018-05-05 15:08:33989std::unique_ptr<WebContentsImpl> WebContentsImpl::CreateWithOpener(
[email protected]54944cde2012-12-09 09:24:59990 const WebContents::CreateParams& params,
Ian Clelland5cbaaf82017-11-27 22:00:03991 RenderFrameHostImpl* opener_rfh) {
Alexander Timin5fdeff22020-09-08 09:20:37992 OPTIONAL_TRACE_EVENT1("browser", "WebContentsImpl::CreateWithOpener",
993 "opener", base::trace_event::ToTracedValue(opener_rfh));
Ian Clelland5cbaaf82017-11-27 22:00:03994 FrameTreeNode* opener = nullptr;
995 if (opener_rfh)
996 opener = opener_rfh->frame_tree_node();
erikchen50735fd2018-05-05 15:08:33997 std::unique_ptr<WebContentsImpl> new_contents(
998 new WebContentsImpl(params.browser_context));
lukasza6f8ac622017-06-06 03:10:20999 new_contents->SetOpenerForNewContents(opener, params.opener_suppressed);
alexmose201c7cd2015-06-10 17:14:211000
alexmosaedfc6f2016-01-21 23:57:381001 // If the opener is sandboxed, a new popup must inherit the opener's sandbox
1002 // flags, and these flags take effect immediately. An exception is if the
1003 // opener's sandbox flags lack the PropagatesToAuxiliaryBrowsingContexts
1004 // bit (which is controlled by the "allow-popups-to-escape-sandbox" token).
1005 // See https://html.spec.whatwg.org/#attr-iframe-sandbox.
lukasza6f8ac622017-06-06 03:10:201006 FrameTreeNode* new_root = new_contents->GetFrameTree()->root();
alexmosaedfc6f2016-01-21 23:57:381007 if (opener) {
arthursonzognib93a4472020-04-10 07:38:001008 network::mojom::WebSandboxFlags opener_flags =
Antonio Gomes7096ac02020-02-14 14:29:541009 opener_rfh->active_sandbox_flags();
arthursonzognib93a4472020-04-10 07:38:001010 const network::mojom::WebSandboxFlags inherit_flag =
1011 network::mojom::WebSandboxFlags::kPropagatesToAuxiliaryBrowsingContexts;
Ehsan Karamad39407082019-02-19 23:38:191012 bool sandbox_propagates_to_auxilary_context =
1013 (opener_flags & inherit_flag) == inherit_flag;
1014 if (sandbox_propagates_to_auxilary_context)
Charlie Hue1b77ac2019-12-13 21:30:171015 new_root->SetPendingFramePolicy({opener_flags,
1016 {} /* container_policy */,
1017 {} /* required_document_policy */});
arthursonzognib93a4472020-04-10 07:38:001018 if (opener_flags == network::mojom::WebSandboxFlags::kNone ||
Ehsan Karamad39407082019-02-19 23:38:191019 sandbox_propagates_to_auxilary_context) {
1020 // TODO(ekaramad, iclelland): Do not propagate feature policies from non-
1021 // sandboxed disowned openers (rel=noopener).
1022 // If the current page is not sandboxed, or if the sandbox is to propagate
1023 // to the popups then opener's feature policy will apply to the new popup
1024 // as well.
1025 new_root->SetOpenerFeaturePolicyState(
Ehsan Karamad34d10682019-02-26 20:55:041026 opener_rfh->feature_policy()->GetFeatureState());
alexmosaedfc6f2016-01-21 23:57:381027 }
arthursonzogni034bb9c2020-10-01 08:29:561028
1029 new_root->SetInitialPopupURL(params.initial_popup_url);
1030 new_root->SetPopupCreatorOrigin(opener_rfh->GetLastCommittedOrigin());
alexmosaedfc6f2016-01-21 23:57:381031 }
1032
mark a. foltzef394fce2017-10-21 09:11:021033 // Apply starting sandbox flags.
Luna Luc3fdacdf2017-11-08 04:48:531034 blink::FramePolicy frame_policy(new_root->pending_frame_policy());
mark a. foltzef394fce2017-10-21 09:11:021035 frame_policy.sandbox_flags |= params.starting_sandbox_flags;
1036 new_root->SetPendingFramePolicy(frame_policy);
Charlie Hu5ffc0152019-12-06 15:59:531037 new_root->CommitFramePolicy(frame_policy);
mark a. foltzef394fce2017-10-21 09:11:021038
alexmose201c7cd2015-06-10 17:14:211039 // This may be true even when opener is null, such as when opening blocked
1040 // popups.
alexmos090fae8e2015-05-28 17:09:281041 if (params.created_with_opener)
1042 new_contents->created_with_opener_ = true;
1043
Sean Toppingbbc4a2bd2019-01-30 02:16:141044 WebContentsImpl* outer_web_contents = nullptr;
[email protected]4858e432014-06-23 18:14:171045 if (params.guest_delegate) {
[email protected]83100cd2014-05-10 11:50:061046 // This makes |new_contents| act as a guest.
1047 // For more info, see comment above class BrowserPluginGuest.
Albert J. Wongc55cc64d2018-10-12 02:50:041048 BrowserPluginGuest::CreateInWebContents(new_contents.get(),
1049 params.guest_delegate);
Sean Toppingbbc4a2bd2019-01-30 02:16:141050 outer_web_contents = static_cast<WebContentsImpl*>(
1051 params.guest_delegate->GetOwnerWebContents());
[email protected]83100cd2014-05-10 11:50:061052 }
mark a. foltzef394fce2017-10-21 09:11:021053
[email protected]54944cde2012-12-09 09:24:591054 new_contents->Init(params);
Sean Toppingbbc4a2bd2019-01-30 02:16:141055 if (outer_web_contents)
1056 outer_web_contents->InnerWebContentsCreated(new_contents.get());
[email protected]d1198fd2012-08-13 22:50:191057 return new_contents;
1058}
1059
[email protected]95640212014-07-26 18:14:301060// static
1061std::vector<WebContentsImpl*> WebContentsImpl::GetAllWebContents() {
Alexander Timin5fdeff22020-09-08 09:20:371062 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1063 "WebContentsImpl::GetAllWebContents");
[email protected]95640212014-07-26 18:14:301064 std::vector<WebContentsImpl*> result;
dcheng59716272016-04-09 05:19:081065 std::unique_ptr<RenderWidgetHostIterator> widgets(
[email protected]95640212014-07-26 18:14:301066 RenderWidgetHostImpl::GetRenderWidgetHosts());
[email protected]95640212014-07-26 18:14:301067 while (RenderWidgetHost* rwh = widgets->GetNextHost()) {
[email protected]95640212014-07-26 18:14:301068 RenderViewHost* rvh = RenderViewHost::From(rwh);
1069 if (!rvh)
1070 continue;
1071 WebContents* web_contents = WebContents::FromRenderViewHost(rvh);
1072 if (!web_contents)
1073 continue;
avidf38c952015-10-27 13:45:131074 if (web_contents->GetRenderViewHost() != rvh)
1075 continue;
1076 // Because a WebContents can only have one current RVH at a time, there will
1077 // be no duplicate WebContents here.
1078 result.push_back(static_cast<WebContentsImpl*>(web_contents));
[email protected]95640212014-07-26 18:14:301079 }
1080 return result;
1081}
1082
clamya16aa8172015-05-26 13:07:251083// static
1084WebContentsImpl* WebContentsImpl::FromFrameTreeNode(
paulmeyerfeafc2d2017-04-25 21:46:401085 const FrameTreeNode* frame_tree_node) {
Alexander Timin5fdeff22020-09-08 09:20:371086 OPTIONAL_TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1087 "WebContentsImpl::FromFrameTreeNode", "frame_tree_node",
1088 frame_tree_node);
clamya16aa8172015-05-26 13:07:251089 return static_cast<WebContentsImpl*>(
1090 WebContents::FromRenderFrameHost(frame_tree_node->current_frame_host()));
1091}
1092
clamy0d32d6d2015-11-24 11:16:261093// static
Patrick Monette275a6f92b2020-01-09 21:05:041094WebContents* WebContentsImpl::FromRenderFrameHostID(
1095 GlobalFrameRoutingId render_frame_host_id) {
Alexander Timin5fdeff22020-09-08 09:20:371096 OPTIONAL_TRACE_EVENT2(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1097 "WebContentsImpl::FromRenderFrameHostID", "process_id",
1098 render_frame_host_id.child_id, "frame_id",
1099 render_frame_host_id.frame_routing_id);
Patrick Monette275a6f92b2020-01-09 21:05:041100 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI) ||
1101 !BrowserThread::IsThreadInitialized(BrowserThread::UI));
Patrick Monette7364e6972020-01-09 22:56:021102 RenderFrameHost* render_frame_host =
1103 RenderFrameHost::FromID(render_frame_host_id);
1104 if (!render_frame_host)
1105 return nullptr;
1106
1107 return WebContents::FromRenderFrameHost(render_frame_host);
Patrick Monette275a6f92b2020-01-09 21:05:041108}
1109
1110// static
clamy0d32d6d2015-11-24 11:16:261111WebContents* WebContentsImpl::FromRenderFrameHostID(int render_process_host_id,
1112 int render_frame_host_id) {
Patrick Monette7364e6972020-01-09 22:56:021113 return FromRenderFrameHostID(
1114 GlobalFrameRoutingId(render_process_host_id, render_frame_host_id));
clamy0d32d6d2015-11-24 11:16:261115}
1116
paulmeyerfeafc2d2017-04-25 21:46:401117// static
1118WebContentsImpl* WebContentsImpl::FromOuterFrameTreeNode(
1119 const FrameTreeNode* frame_tree_node) {
Alexander Timin5fdeff22020-09-08 09:20:371120 OPTIONAL_TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1121 "WebContentsImpl::FromOuterFrameTreeNode",
1122 "frame_tree_node", frame_tree_node);
paulmeyerfeafc2d2017-04-25 21:46:401123 return WebContentsImpl::FromFrameTreeNode(frame_tree_node)
1124 ->node_.GetInnerWebContentsInFrame(frame_tree_node);
1125}
1126
[email protected]b0936d22013-11-28 06:47:361127RenderFrameHostManager* WebContentsImpl::GetRenderManagerForTesting() {
[email protected]fa944cb82013-11-15 17:51:211128 return GetRenderManager();
[email protected]765187182012-01-11 23:59:281129}
1130
nicka0ac8382016-12-15 23:59:231131bool WebContentsImpl::OnMessageReceived(RenderViewHostImpl* render_view_host,
[email protected]7bb761892012-07-20 09:32:471132 const IPC::Message& message) {
Alexander Timin5fdeff22020-09-08 09:20:371133 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnMessageReceived",
1134 "render_view_host", render_view_host);
Alexander Timin90c20c32020-08-12 15:28:321135 for (auto& observer : observers_.observer_list()) {
Lukasz Anforowicz89f2c1b2017-08-30 21:36:461136 // TODO(nick, creis): https://crbug.com/758026: Replace all uses of this
1137 // variant of OnMessageReceived with the version that takes a
1138 // RenderFrameHost, and then delete it.
nicka0ac8382016-12-15 23:59:231139 if (observer.OnMessageReceived(message))
1140 return true;
[email protected]64ffefa2014-05-10 12:06:331141 }
[email protected]403415a2011-01-10 18:57:531142
Henrique Ferreiroba535472020-04-21 11:38:361143 return false;
nicka0ac8382016-12-15 23:59:231144}
1145
1146bool WebContentsImpl::OnMessageReceived(RenderFrameHostImpl* render_frame_host,
1147 const IPC::Message& message) {
Alexander Timin5fdeff22020-09-08 09:20:371148 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnMessageReceived",
1149 "render_frame_host",
1150 base::trace_event::ToTracedValue(render_frame_host));
1151
Alexander Timin90c20c32020-08-12 15:28:321152 for (auto& observer : observers_.observer_list()) {
nicka0ac8382016-12-15 23:59:231153 if (observer.OnMessageReceived(message, render_frame_host))
1154 return true;
1155 }
1156
1157 bool handled = true;
brettw4b461082016-11-19 18:55:161158#if BUILDFLAG(ENABLE_PLUGINS)
Hiroki Nakagawa761b9b02020-07-13 11:12:021159 IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(WebContentsImpl, message, render_frame_host)
emaxxe70f5e12015-05-29 11:26:001160 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceCreated,
1161 OnPepperInstanceCreated)
1162 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceDeleted,
1163 OnPepperInstanceDeleted)
tommyclie6633ca72014-10-31 00:40:421164 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung, OnPepperPluginHung)
zqzhang181047e62016-07-01 13:37:171165 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperStartsPlayback,
1166 OnPepperStartsPlayback)
1167 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperStopsPlayback,
1168 OnPepperStopsPlayback)
tommyclie6633ca72014-10-31 00:40:421169 IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed, OnPluginCrashed)
[email protected]724159a2010-12-30 01:11:181170 IPC_MESSAGE_UNHANDLED(handled = false)
[email protected]e44d1342014-05-16 21:29:331171 IPC_END_MESSAGE_MAP()
Hiroki Nakagawa761b9b02020-07-13 11:12:021172#else
1173 handled = false;
1174#endif
[email protected]724159a2010-12-30 01:11:181175
[email protected]724159a2010-12-30 01:11:181176 return handled;
1177}
1178
[email protected]d1198fd2012-08-13 22:50:191179NavigationControllerImpl& WebContentsImpl::GetController() {
[email protected]f5fa20e2011-12-21 22:35:561180 return controller_;
1181}
1182
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411183BrowserContext* WebContentsImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:551184 return controller_.GetBrowserContext();
[email protected]627e0512011-12-21 22:55:301185}
1186
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411187const GURL& WebContentsImpl::GetURL() {
Peter Boström101d7672018-12-15 00:43:591188 return GetVisibleURL();
[email protected]be1f56ab2011-12-22 06:55:311189}
1190
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411191const GURL& WebContentsImpl::GetVisibleURL() {
[email protected]c854a7e2013-05-21 16:42:241192 // We may not have a navigation entry yet.
[email protected]59167c22013-06-03 18:07:321193 NavigationEntry* entry = controller_.GetVisibleEntry();
[email protected]c854a7e2013-05-21 16:42:241194 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
1195}
1196
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411197const GURL& WebContentsImpl::GetLastCommittedURL() {
[email protected]c854a7e2013-05-21 16:42:241198 // We may not have a navigation entry yet.
1199 NavigationEntry* entry = controller_.GetLastCommittedEntry();
1200 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
1201}
1202
[email protected]8ff00d72012-10-23 19:12:211203WebContentsDelegate* WebContentsImpl::GetDelegate() {
[email protected]be1f56ab2011-12-22 06:55:311204 return delegate_;
1205}
1206
[email protected]8ff00d72012-10-23 19:12:211207void WebContentsImpl::SetDelegate(WebContentsDelegate* delegate) {
Alexander Timin5fdeff22020-09-08 09:20:371208 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetDelegate", "delegate",
1209 delegate);
[email protected]be1f56ab2011-12-22 06:55:311210 // TODO(cbentzel): remove this debugging code?
1211 if (delegate == delegate_)
1212 return;
1213 if (delegate_)
1214 delegate_->Detach(this);
1215 delegate_ = delegate;
[email protected]a6b73c62013-02-11 23:05:081216 if (delegate_) {
[email protected]be1f56ab2011-12-22 06:55:311217 delegate_->Attach(this);
[email protected]a6b73c62013-02-11 23:05:081218 // Ensure the visible RVH reflects the new delegate's preferences.
[email protected]86f98a22013-03-20 14:35:001219 if (view_)
[email protected]e85165c642014-06-10 14:34:311220 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
Joel Einbinder848001c2017-09-19 21:39:311221 if (GetRenderViewHost())
1222 RenderFrameDevToolsAgentHost::WebContentsCreated(this);
[email protected]a6b73c62013-02-11 23:05:081223 }
[email protected]be1f56ab2011-12-22 06:55:311224}
1225
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411226RenderFrameHostImpl* WebContentsImpl::GetMainFrame() {
[email protected]94d0cc12013-12-18 00:07:411227 return frame_tree_.root()->current_frame_host();
[email protected]60eca4eb2013-12-06 00:02:161228}
1229
nick53d5cbf2015-04-23 22:50:141230RenderFrameHostImpl* WebContentsImpl::GetFocusedFrame() {
1231 FrameTreeNode* focused_node = frame_tree_.GetFocusedFrame();
1232 if (!focused_node)
1233 return nullptr;
1234 return focused_node->current_frame_host();
[email protected]9c9343b2014-03-08 02:56:071235}
1236
rob3e2a0732016-01-06 21:22:091237RenderFrameHostImpl* WebContentsImpl::FindFrameByFrameTreeNodeId(
creisf71a2632017-05-04 19:03:501238 int frame_tree_node_id,
1239 int process_id) {
Alexander Timin5fdeff22020-09-08 09:20:371240 OPTIONAL_TRACE_EVENT2(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1241 "WebContentsImpl::FindFrameByFrameTreeNodeId",
1242 "frame_tree_node_id", frame_tree_node_id, "process_id",
1243 process_id);
creisf71a2632017-05-04 19:03:501244 FrameTreeNode* frame = frame_tree_.FindByID(frame_tree_node_id);
1245
1246 // Sanity check that this is in the caller's expected process. Otherwise a
1247 // recent cross-process navigation may have led to a privilege change that the
1248 // caller is not expecting.
1249 if (!frame ||
1250 frame->current_frame_host()->GetProcess()->GetID() != process_id)
1251 return nullptr;
1252
1253 return frame->current_frame_host();
1254}
1255
1256RenderFrameHostImpl* WebContentsImpl::UnsafeFindFrameByFrameTreeNodeId(
rob3e2a0732016-01-06 21:22:091257 int frame_tree_node_id) {
Alexander Timin5fdeff22020-09-08 09:20:371258 OPTIONAL_TRACE_EVENT1("content",
1259 "WebContentsImpl::UnsafeFindFrameByFrameTreeNodeId",
1260 "frame_tree_node_id", frame_tree_node_id);
creisf71a2632017-05-04 19:03:501261 // Beware using this! The RenderFrameHost may have changed since the caller
1262 // obtained frame_tree_node_id.
rob3e2a0732016-01-06 21:22:091263 FrameTreeNode* frame = frame_tree_.FindByID(frame_tree_node_id);
1264 return frame ? frame->current_frame_host() : nullptr;
1265}
1266
[email protected]a86c0e962013-12-17 17:10:391267void WebContentsImpl::ForEachFrame(
Lei Zhangebcc6302018-01-12 19:46:451268 const base::RepeatingCallback<void(RenderFrameHost*)>& on_frame) {
Alexander Timin5fdeff22020-09-08 09:20:371269 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1270 "WebContentsImpl::ForEachFrame");
dcheng57e39e22016-01-21 00:25:381271 for (FrameTreeNode* node : frame_tree_.Nodes()) {
1272 on_frame.Run(node->current_frame_host());
1273 }
[email protected]a86c0e962013-12-17 17:10:391274}
1275
dchengafb53e22016-02-04 08:11:081276std::vector<RenderFrameHost*> WebContentsImpl::GetAllFrames() {
Xuehui Xieb2300ae42020-06-09 20:25:051277 return GetAllFramesImpl(frame_tree_, /*include_pending=*/false);
1278}
1279
1280std::vector<RenderFrameHost*> WebContentsImpl::GetAllFramesIncludingPending() {
1281 return GetAllFramesImpl(frame_tree_, /*include_pending=*/true);
dchengafb53e22016-02-04 08:11:081282}
1283
lukaszacbdf52e2016-01-15 21:19:511284int WebContentsImpl::SendToAllFrames(IPC::Message* message) {
Alexander Timin5fdeff22020-09-08 09:20:371285 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SendToAllFrames");
Xuehui Xieb2300ae42020-06-09 20:25:051286 return SendToAllFramesImpl(frame_tree_, /*include_pending=*/false, message);
1287}
lukasza1a9ab2422016-03-02 18:47:251288
Xuehui Xieb2300ae42020-06-09 20:25:051289int WebContentsImpl::SendToAllFramesIncludingPending(IPC::Message* message) {
Alexander Timin5fdeff22020-09-08 09:20:371290 OPTIONAL_TRACE_EVENT0("content",
1291 "WebContentsImpl::SentToAllFramesIncludingPending");
Xuehui Xieb2300ae42020-06-09 20:25:051292 return SendToAllFramesImpl(frame_tree_, /*include_pending=*/true, message);
[email protected]a86c0e962013-12-17 17:10:391293}
1294
lfgdb5c4ed2016-03-04 23:09:071295void WebContentsImpl::SendPageMessage(IPC::Message* msg) {
Alexander Timin5fdeff22020-09-08 09:20:371296 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SendPageMessage");
alexmos136fd6e62016-08-15 20:58:411297 frame_tree_.root()->render_manager()->SendPageMessage(msg, nullptr);
lfgdb5c4ed2016-03-04 23:09:071298}
1299
Gyuyoung Kim877e86d2020-07-21 04:01:021300void WebContentsImpl::ExecutePageBroadcastMethod(
1301 PageBroadcastMethodCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:371302 OPTIONAL_TRACE_EVENT0("content",
1303 "WebContentsImpl::ExecutePageBroadcastMethod");
Gyuyoung Kim877e86d2020-07-21 04:01:021304 frame_tree_.root()->render_manager()->ExecutePageBroadcastMethod(callback);
1305}
1306
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411307RenderViewHostImpl* WebContentsImpl::GetRenderViewHost() {
[email protected]fa944cb82013-11-15 17:51:211308 return GetRenderManager()->current_host();
[email protected]be1f56ab2011-12-22 06:55:311309}
1310
creis89a0f782015-05-27 16:13:171311void WebContentsImpl::CancelActiveAndPendingDialogs() {
Alexander Timin5fdeff22020-09-08 09:20:371312 OPTIONAL_TRACE_EVENT0("content",
1313 "WebContentsImpl::CancelActiveAndPendingDialogs");
Evan Stade753fc202020-07-13 18:09:541314 if (dialog_manager_) {
avi6879fcf2017-01-21 05:27:531315 dialog_manager_->CancelDialogs(this, /*reset_state=*/false);
Evan Stade753fc202020-07-13 18:09:541316 }
creis89a0f782015-05-27 16:13:171317 if (browser_plugin_embedder_)
1318 browser_plugin_embedder_->CancelGuestDialogs();
1319}
1320
naskoc0fceff2015-04-30 15:53:521321void WebContentsImpl::ClosePage() {
Alexander Timin5fdeff22020-09-08 09:20:371322 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ClosePage");
naskoc0fceff2015-04-30 15:53:521323 GetRenderViewHost()->ClosePage();
1324}
1325
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411326RenderWidgetHostView* WebContentsImpl::GetRenderWidgetHostView() {
[email protected]fa944cb82013-11-15 17:51:211327 return GetRenderManager()->GetRenderWidgetHostView();
[email protected]be1f56ab2011-12-22 06:55:311328}
1329
lfg265a2672016-04-23 03:11:021330RenderWidgetHostView* WebContentsImpl::GetTopLevelRenderWidgetHostView() {
1331 if (GetOuterWebContents())
1332 return GetOuterWebContents()->GetTopLevelRenderWidgetHostView();
1333 return GetRenderManager()->GetRenderWidgetHostView();
1334}
1335
[email protected]8ff00d72012-10-23 19:12:211336WebContentsView* WebContentsImpl::GetView() const {
[email protected]be1f56ab2011-12-22 06:55:311337 return view_.get();
1338}
1339
Mike Wasserman5a3cc61d2020-08-27 21:12:031340void WebContentsImpl::OnScreensChange(bool is_multi_screen_changed) {
Alexander Timin5fdeff22020-09-08 09:20:371341 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnScreensChange",
1342 "is_multi_screen_changed", is_multi_screen_changed);
Mike Wassermandb8f4f02020-10-06 01:18:371343 // Allow fullscreen requests shortly after user-generated screens changes.
1344 transient_allow_fullscreen_.Activate();
Mike Wasserman5a3cc61d2020-08-27 21:12:031345 // Send |is_multi_screen_changed| events to all visible frames, but limit
1346 // other events to frames with the Window Placement permission. This obviates
1347 // the most pressing need for sites to poll isMultiScreen(), which is exposed
1348 // without explicit permission, while also protecting privacy.
1349 // TODO(crbug.com/1109989): Postpone events; refine utility/privacy balance.
Mike Wassermanb213b9352020-04-16 00:32:341350 for (FrameTreeNode* node : frame_tree_.Nodes()) {
1351 RenderFrameHostImpl* rfh = node->current_frame_host();
Mike Wasserman5a3cc61d2020-08-27 21:12:031352 if ((is_multi_screen_changed &&
1353 rfh->GetVisibilityState() == PageVisibilityState::kVisible) ||
Mike Wassermandb8f4f02020-10-06 01:18:371354 IsWindowPlacementGranted(rfh)) {
Mike Wasserman5a3cc61d2020-08-27 21:12:031355 rfh->GetAssociatedLocalFrame()->OnScreensChange();
1356 }
Mike Wassermanb213b9352020-04-16 00:32:341357 }
1358}
1359
leon.han552e9de2017-02-09 14:37:301360void WebContentsImpl::OnScreenOrientationChange() {
Alexander Timin5fdeff22020-09-08 09:20:371361 OPTIONAL_TRACE_EVENT0("content",
1362 "WebContentsImpl::OnScreenOrientationChange");
leon.han552e9de2017-02-09 14:37:301363 DCHECK(screen_orientation_provider_);
Lan Weif81c6e7c2020-02-12 16:46:091364 DidChangeScreenOrientation();
Becca Hughese9e27952018-06-25 17:08:271365 screen_orientation_provider_->OnOrientationChange();
leon.hane4db177a2017-02-07 14:19:161366}
1367
Alan Cutter92d59252019-03-29 02:32:331368base::Optional<SkColor> WebContentsImpl::GetThemeColor() {
Carlos Caballero1215f882019-10-29 15:58:431369 return GetRenderViewHost()->theme_color();
yusufod41c5f92015-03-06 00:14:281370}
1371
Alan Cutterd73a15d92020-08-21 07:12:451372base::Optional<SkColor> WebContentsImpl::GetBackgroundColor() {
1373 return GetRenderViewHost()->background_color();
1374}
1375
Doug Turner63f3c7b2017-07-29 05:10:011376void WebContentsImpl::SetAccessibilityMode(ui::AXMode mode) {
Alexander Timin5fdeff22020-09-08 09:20:371377 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetAccessibilityMode",
1378 "mode", mode.ToString(), "previous_mode",
1379 accessibility_mode_.ToString());
1380
[email protected]95640212014-07-26 18:14:301381 if (mode == accessibility_mode_)
1382 return;
1383
dmazzonif8a31042016-12-03 00:52:131384 // Don't allow accessibility to be enabled for WebContents that are never
danakj77eb7e82020-01-09 19:38:461385 // user-visible, like background pages.
1386 if (IsNeverComposited())
dmazzonif8a31042016-12-03 00:52:131387 return;
1388
[email protected]95640212014-07-26 18:14:301389 accessibility_mode_ = mode;
dcheng57e39e22016-01-21 00:25:381390
1391 for (FrameTreeNode* node : frame_tree_.Nodes()) {
dmazzonif8a31042016-12-03 00:52:131392 UpdateAccessibilityModeOnFrame(node->current_frame_host());
clamy610c63b32017-12-22 15:05:181393 // Also update accessibility mode on the speculative RenderFrameHost for
1394 // this FrameTreeNode, if one exists.
Alex Moshchuk3d8a1f392017-10-24 19:01:261395 RenderFrameHost* speculative_frame_host =
1396 node->render_manager()->speculative_frame_host();
1397 if (speculative_frame_host)
1398 UpdateAccessibilityModeOnFrame(speculative_frame_host);
dcheng57e39e22016-01-21 00:25:381399 }
[email protected]95640212014-07-26 18:14:301400}
1401
Doug Turner63f3c7b2017-07-29 05:10:011402void WebContentsImpl::AddAccessibilityMode(ui::AXMode mode) {
1403 ui::AXMode new_mode(accessibility_mode_);
dougtcd3dad732017-03-14 03:26:231404 new_mode |= mode;
1405 SetAccessibilityMode(new_mode);
[email protected]95640212014-07-26 18:14:301406}
1407
Avi Drissman1e620f32018-03-16 13:57:291408// Helper class used by WebContentsImpl::RequestAXTreeSnapshot.
1409// Handles the callbacks from parallel snapshot requests to each frame,
1410// and feeds the results to an AXTreeCombiner, which converts them into a
1411// single combined accessibility tree.
1412class WebContentsImpl::AXTreeSnapshotCombiner
1413 : public base::RefCounted<AXTreeSnapshotCombiner> {
1414 public:
1415 explicit AXTreeSnapshotCombiner(AXTreeSnapshotCallback callback)
1416 : callback_(std::move(callback)) {}
1417
1418 AXTreeSnapshotCallback AddFrame(bool is_root) {
1419 // Adds a reference to |this|.
1420 return base::BindOnce(&AXTreeSnapshotCombiner::ReceiveSnapshot, this,
1421 is_root);
1422 }
1423
1424 void ReceiveSnapshot(bool is_root, const ui::AXTreeUpdate& snapshot) {
1425 combiner_.AddTree(snapshot, is_root);
1426 }
1427
1428 private:
1429 friend class base::RefCounted<AXTreeSnapshotCombiner>;
1430
1431 // This is called automatically after the last call to ReceiveSnapshot
1432 // when there are no more references to this object.
1433 ~AXTreeSnapshotCombiner() {
1434 combiner_.Combine();
1435 std::move(callback_).Run(combiner_.combined());
1436 }
1437
1438 ui::AXTreeCombiner combiner_;
1439 AXTreeSnapshotCallback callback_;
1440};
1441
1442void WebContentsImpl::RequestAXTreeSnapshot(AXTreeSnapshotCallback callback,
1443 ui::AXMode ax_mode) {
Alexander Timin5fdeff22020-09-08 09:20:371444 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RequestAXTreeSnapshot",
1445 "mode", ax_mode.ToString());
dmazzonid95ae842016-04-12 21:17:391446 // Send a request to each of the frames in parallel. Each one will return
1447 // an accessibility tree snapshot, and AXTreeSnapshotCombiner will combine
1448 // them into a single tree and call |callback| with that result, then
1449 // delete |combiner|.
Avi Drissman1e620f32018-03-16 13:57:291450 FrameTreeNode* root_node = frame_tree_.root();
tzik58faa742018-08-01 10:54:181451 auto combiner =
1452 base::MakeRefCounted<AXTreeSnapshotCombiner>(std::move(callback));
Avi Drissman1e620f32018-03-16 13:57:291453
tzik58faa742018-08-01 10:54:181454 RecursiveRequestAXTreeSnapshotOnFrame(root_node, combiner.get(), ax_mode);
Avi Drissman1e620f32018-03-16 13:57:291455}
1456
1457void WebContentsImpl::RecursiveRequestAXTreeSnapshotOnFrame(
1458 FrameTreeNode* root_node,
1459 AXTreeSnapshotCombiner* combiner,
1460 ui::AXMode ax_mode) {
Alexander Timin5fdeff22020-09-08 09:20:371461 OPTIONAL_TRACE_EVENT0(
1462 "content", "WebContentsImpl::RecursiveRequestAXTreeSnapshotOnFrame");
dmazzonid95ae842016-04-12 21:17:391463 for (FrameTreeNode* frame_tree_node : frame_tree_.Nodes()) {
Avi Drissman1e620f32018-03-16 13:57:291464 WebContentsImpl* inner_contents =
1465 node_.GetInnerWebContentsInFrame(frame_tree_node);
1466 if (inner_contents) {
1467 inner_contents->RecursiveRequestAXTreeSnapshotOnFrame(root_node, combiner,
1468 ax_mode);
1469 } else {
1470 bool is_root = frame_tree_node == root_node;
1471 frame_tree_node->current_frame_host()->RequestAXTreeSnapshot(
1472 combiner->AddFrame(is_root), ax_mode);
1473 }
dmazzonid95ae842016-04-12 21:17:391474 }
dmazzoni83ba5c82015-04-14 07:11:511475}
1476
Becca Hughes3b5a43482018-07-17 22:31:551477void WebContentsImpl::NotifyViewportFitChanged(
1478 blink::mojom::ViewportFit value) {
Alexander Timin5fdeff22020-09-08 09:20:371479 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::NotifyViewportFitChanged",
1480 "value", static_cast<int>(value));
Alexander Timin90c20c32020-08-12 15:28:321481 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1482 observer->ViewportFitChanged(value);
1483 });
Becca Hughes3b5a43482018-07-17 22:31:551484}
1485
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411486FindRequestManager* WebContentsImpl::GetFindRequestManagerForTesting() {
Ehsan Karamad6beb2ea2018-11-25 18:15:131487 return GetFindRequestManager();
1488}
1489
mcnee336ea2c2017-05-23 22:50:591490#if !defined(OS_ANDROID)
akabac6bd1212018-06-25 20:10:481491void WebContentsImpl::UpdateZoom() {
Alexander Timin5fdeff22020-09-08 09:20:371492 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::UpdateZoom");
akabac6bd1212018-06-25 20:10:481493 RenderWidgetHostImpl* rwh = GetRenderViewHost()->GetWidget();
1494 if (rwh->GetView())
1495 rwh->SynchronizeVisualProperties();
wjmaclean64951902016-04-29 20:59:121496}
1497
wjmaclean64951902016-04-29 20:59:121498
1499void WebContentsImpl::UpdateZoomIfNecessary(const std::string& scheme,
akabac6bd1212018-06-25 20:10:481500 const std::string& host) {
Alexander Timin5fdeff22020-09-08 09:20:371501 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::UpdateZoomIfNecessary",
1502 "scheme", scheme, "host", host);
wjmaclean64951902016-04-29 20:59:121503 NavigationEntry* entry = GetController().GetLastCommittedEntry();
1504 if (!entry)
1505 return;
1506
1507 GURL url = HostZoomMap::GetURLFromEntry(entry);
1508 if (host != net::GetHostOrSpecFromURL(url) ||
1509 (!scheme.empty() && !url.SchemeIs(scheme))) {
1510 return;
1511 }
1512
akabac6bd1212018-06-25 20:10:481513 UpdateZoom();
wjmaclean64951902016-04-29 20:59:121514}
mcnee336ea2c2017-05-23 22:50:591515#endif // !defined(OS_ANDROID)
wjmaclean64951902016-04-29 20:59:121516
Julie Jeongeun Kim7d0986172019-12-04 03:17:251517base::OnceClosure WebContentsImpl::AddReceiverSet(
rockotf62002a2016-09-15 00:08:591518 const std::string& interface_name,
Julie Jeongeun Kim7d0986172019-12-04 03:17:251519 WebContentsReceiverSet* receiver_set) {
Alexander Timin5fdeff22020-09-08 09:20:371520 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::AddReceiverSet",
1521 "interface_name", interface_name);
rockotf62002a2016-09-15 00:08:591522 auto result =
Julie Jeongeun Kim7d0986172019-12-04 03:17:251523 receiver_sets_.insert(std::make_pair(interface_name, receiver_set));
rockotf62002a2016-09-15 00:08:591524 DCHECK(result.second);
Julie Jeongeun Kim7d0986172019-12-04 03:17:251525 return base::BindOnce(&WebContentsImpl::RemoveReceiverSet,
danakjf4b9e942019-11-29 15:43:041526 weak_factory_.GetWeakPtr(), interface_name);
rockotf62002a2016-09-15 00:08:591527}
1528
Julie Jeongeun Kim7d0986172019-12-04 03:17:251529WebContentsReceiverSet* WebContentsImpl::GetReceiverSet(
rockot8bbad222017-03-22 04:34:051530 const std::string& interface_name) {
Julie Jeongeun Kim7d0986172019-12-04 03:17:251531 auto it = receiver_sets_.find(interface_name);
1532 if (it == receiver_sets_.end())
rockot8bbad222017-03-22 04:34:051533 return nullptr;
1534 return it->second;
1535}
1536
John Delaney732721e92020-02-07 23:11:271537void WebContentsImpl::RemoveReceiverSetForTesting(
1538 const std::string& interface_name) {
Alexander Timin5fdeff22020-09-08 09:20:371539 OPTIONAL_TRACE_EVENT1("content",
1540 "WebContentsImpl::RemoveReceiverSetForTesting",
1541 "interface_name", interface_name);
John Delaney732721e92020-02-07 23:11:271542 RemoveReceiverSet(interface_name);
1543}
1544
paulmeyerfeafc2d2017-04-25 21:46:401545std::vector<WebContentsImpl*> WebContentsImpl::GetWebContentsAndAllInner() {
1546 std::vector<WebContentsImpl*> all_contents(1, this);
1547
1548 for (size_t i = 0; i != all_contents.size(); ++i) {
1549 for (auto* inner_contents : all_contents[i]->GetInnerWebContents()) {
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:161550 all_contents.push_back(static_cast<WebContentsImpl*>(inner_contents));
paulmeyerfeafc2d2017-04-25 21:46:401551 }
1552 }
1553
1554 return all_contents;
1555}
1556
Sam McNally145fb172017-05-10 00:13:231557void WebContentsImpl::NotifyManifestUrlChanged(
Yuzu Saijo0c263c702020-06-08 03:41:241558 RenderFrameHost* rfh,
Sam McNally145fb172017-05-10 00:13:231559 const base::Optional<GURL>& manifest_url) {
Alexander Timin5fdeff22020-09-08 09:20:371560 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::NotifyManifestUrlChanged",
1561 "render_frame_host",
1562 base::trace_event::ToTracedValue(rfh), "manifest_url",
1563 base::trace_event::ValueToString(manifest_url));
Alexander Timin90c20c32020-08-12 15:28:321564 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1565 observer->DidUpdateWebManifestURL(rfh, manifest_url);
1566 });
Sam McNally145fb172017-05-10 00:13:231567}
1568
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411569WebUI* WebContentsImpl::GetWebUI() {
Nasko Oskov2f7d2112019-10-29 03:26:571570 WebUI* committed_web_ui = GetCommittedWebUI();
1571 if (committed_web_ui)
1572 return committed_web_ui;
1573
1574 if (GetRenderManager()->speculative_frame_host())
1575 return GetRenderManager()->speculative_frame_host()->web_ui();
1576
1577 return nullptr;
[email protected]be1f56ab2011-12-22 06:55:311578}
1579
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411580WebUI* WebContentsImpl::GetCommittedWebUI() {
carlosk35f35af2015-12-01 10:55:401581 return frame_tree_.root()->current_frame_host()->web_ui();
[email protected]d5f942ba2008-09-26 19:30:341582}
1583
Maks Orlovich73f374d2020-04-02 12:46:131584void WebContentsImpl::SetUserAgentOverride(
1585 const blink::UserAgentOverride& ua_override,
1586 bool override_in_new_tabs) {
Alexander Timin5fdeff22020-09-08 09:20:371587 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetUserAgentOverride",
1588 "ua_override", ua_override.ua_string_override,
1589 "override_in_new_tabs", override_in_new_tabs);
Maks Orlovich73f374d2020-04-02 12:46:131590 DCHECK(!ua_override.ua_metadata_override.has_value() ||
1591 !ua_override.ua_string_override.empty());
1592
1593 if (GetUserAgentOverride() == ua_override)
[email protected]bf70edce2012-06-20 22:32:221594 return;
1595
Changwan Ryuc1134a82018-03-07 02:10:141596 should_override_user_agent_in_new_tabs_ = override_in_new_tabs;
1597
Maks Orlovich73f374d2020-04-02 12:46:131598 renderer_preferences_.user_agent_override = ua_override;
[email protected]bf70edce2012-06-20 22:32:221599
Bruce Long1e3e1f542019-10-16 17:56:281600 // Send the new override string to all renderers in the current page.
1601 SyncRendererPrefs();
[email protected]bf70edce2012-06-20 22:32:221602
1603 // Reload the page if a load is currently in progress to avoid having
1604 // different parts of the page loaded using different user agents.
Scott Violete1d58cc2020-04-28 23:07:171605 // No need to reload if the current entry matches that of the
1606 // NavigationRequest supplied to DidStartNavigation() as NavigationRequest
1607 // handles it.
[email protected]6286a372013-10-09 04:03:271608 NavigationEntry* entry = controller_.GetVisibleEntry();
Scott Violete1d58cc2020-04-28 23:07:171609 if (IsLoading() && entry != nullptr && entry->GetIsOverridingUserAgent() &&
1610 (!frame_tree_.root()->navigation_request() ||
1611 frame_tree_.root()->navigation_request()->ua_change_requires_reload())) {
toyoshim6142d96f2016-12-19 09:07:251612 controller_.Reload(ReloadType::BYPASSING_CACHE, true);
Scott Violete1d58cc2020-04-28 23:07:171613 }
[email protected]8d0f3312012-08-18 01:47:531614
Alexander Timin90c20c32020-08-12 15:28:321615 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1616 observer->UserAgentOverrideSet(ua_override);
1617 });
[email protected]86ef6a392012-05-11 22:03:111618}
1619
Scott Violet2a6c5bff2020-04-29 23:59:061620void WebContentsImpl::SetRendererInitiatedUserAgentOverrideOption(
1621 NavigationController::UserAgentOverrideOption option) {
Alexander Timin5fdeff22020-09-08 09:20:371622 OPTIONAL_TRACE_EVENT0(
1623 "content",
1624 "WebContentsImpl::SetRendererInitiatedUserAgentOverrideOption");
Scott Violet2a6c5bff2020-04-29 23:59:061625 renderer_initiated_user_agent_override_option_ = option;
1626}
1627
Maks Orlovich73f374d2020-04-02 12:46:131628const blink::UserAgentOverride& WebContentsImpl::GetUserAgentOverride() {
[email protected]bf70edce2012-06-20 22:32:221629 return renderer_preferences_.user_agent_override;
[email protected]86ef6a392012-05-11 22:03:111630}
1631
Scott Violet2a6c5bff2020-04-29 23:59:061632bool WebContentsImpl::ShouldOverrideUserAgentForRendererInitiatedNavigation() {
1633 NavigationEntryImpl* current_entry = controller_.GetLastCommittedEntry();
1634 if (!current_entry)
1635 return should_override_user_agent_in_new_tabs_;
1636
1637 switch (renderer_initiated_user_agent_override_option_) {
1638 case NavigationController::UA_OVERRIDE_INHERIT:
1639 return current_entry->GetIsOverridingUserAgent();
1640 case NavigationController::UA_OVERRIDE_TRUE:
1641 return true;
1642 case NavigationController::UA_OVERRIDE_FALSE:
1643 return false;
1644 default:
1645 break;
1646 }
1647 return false;
Changwan Ryuc1134a82018-03-07 02:10:141648}
1649
dmazzonidd3d51a72016-12-14 18:41:011650void WebContentsImpl::EnableWebContentsOnlyAccessibilityMode() {
Alexander Timin5fdeff22020-09-08 09:20:371651 OPTIONAL_TRACE_EVENT0(
1652 "content", "WebContentsImpl::EnableWebContentsOnlyAccessibilityMode");
Dominic Mazzonid9fda172019-03-07 17:12:071653 // If accessibility is already enabled, we'll need to force a reset
1654 // in order to ensure new observers of accessibility events get the
1655 // full accessibility tree from scratch.
1656 bool need_reset = GetAccessibilityMode().has_mode(ui::AXMode::kWebContents);
1657
1658 ui::AXMode desired_mode =
1659 GetContentClient()->browser()->GetAXModeForBrowserContext(
1660 GetBrowserContext());
1661 desired_mode |= ui::kAXModeWebContentsOnly;
1662 AddAccessibilityMode(desired_mode);
1663
1664 if (need_reset) {
dchengafb53e22016-02-04 08:11:081665 for (RenderFrameHost* rfh : GetAllFrames())
1666 ResetAccessibility(rfh);
dchengafb53e22016-02-04 08:11:081667 }
[email protected]95640212014-07-26 18:14:301668}
1669
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411670bool WebContentsImpl::IsWebContentsOnlyAccessibilityModeForTesting() {
Doug Turner63f3c7b2017-07-29 05:10:011671 return accessibility_mode_ == ui::kAXModeWebContentsOnly;
[email protected]95640212014-07-26 18:14:301672}
1673
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411674bool WebContentsImpl::IsFullAccessibilityModeForTesting() {
Doug Turner63f3c7b2017-07-29 05:10:011675 return accessibility_mode_ == ui::kAXModeComplete;
[email protected]95640212014-07-26 18:14:301676}
1677
Becca Hughes6daf5662018-06-27 16:50:541678#if defined(OS_ANDROID)
1679
1680void WebContentsImpl::SetDisplayCutoutSafeArea(gfx::Insets insets) {
Alexander Timin5fdeff22020-09-08 09:20:371681 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetDisplayCutoutSafeArea");
Becca Hughes86334622018-07-09 21:29:381682 if (display_cutout_host_impl_)
1683 display_cutout_host_impl_->SetDisplayCutoutSafeArea(insets);
Becca Hughes6daf5662018-06-27 16:50:541684}
1685
1686#endif
1687
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411688const base::string16& WebContentsImpl::GetTitle() {
Nasko Oskov2f7d2112019-10-29 03:26:571689 WebUI* our_web_ui =
1690 GetRenderManager()->speculative_frame_host()
1691 ? GetRenderManager()->speculative_frame_host()->web_ui()
1692 : GetRenderManager()->current_frame_host()->web_ui();
[email protected]7ade2732011-02-10 00:13:581693 if (our_web_ui) {
[email protected]96d185d2009-04-24 03:28:541694 // Don't override the title in view source mode.
Carlos IL4dea8902020-05-26 15:14:291695 NavigationEntry* entry = controller_.GetVisibleEntry();
[email protected]96d185d2009-04-24 03:28:541696 if (!(entry && entry->IsViewSourceMode())) {
[email protected]e0112912011-02-02 22:54:351697 // Give the Web UI the chance to override our title.
[email protected]fcf75d42013-12-03 20:11:261698 const base::string16& title = our_web_ui->GetOverriddenTitle();
[email protected]96d185d2009-04-24 03:28:541699 if (!title.empty())
1700 return title;
1701 }
1702 }
1703
1704 // We use the title for the last committed entry rather than a pending
1705 // navigation entry. For example, when the user types in a URL, we want to
1706 // keep the old page's title until the new load has committed and we get a new
1707 // title.
Carlos IL4dea8902020-05-26 15:14:291708 NavigationEntry* entry = controller_.GetLastCommittedEntry();
[email protected]59167c22013-06-03 18:07:321709
creis072b61f2015-09-28 20:52:241710 // We make an exception for initial navigations. We only want to use the title
1711 // from the visible entry if:
1712 // 1. The pending entry has been explicitly assigned a title to display.
1713 // 2. The user is doing a history navigation in a new tab (e.g., Ctrl+Back),
1714 // which case there is a pending entry index other than -1.
1715 //
1716 // Otherwise, we want to stick with the last committed entry's title during
1717 // new navigations, which have pending entries at index -1 with no title.
1718 if (controller_.IsInitialNavigation() &&
1719 ((controller_.GetVisibleEntry() &&
1720 !controller_.GetVisibleEntry()->GetTitle().empty()) ||
1721 controller_.GetPendingEntryIndex() != -1)) {
1722 entry = controller_.GetVisibleEntry();
[email protected]9eeafc012013-11-25 23:49:471723 }
[email protected]59167c22013-06-03 18:07:321724
[email protected]45d0ef7f2011-01-05 13:46:231725 if (entry) {
jshin1fb76462016-04-05 22:13:031726 return entry->GetTitleForDisplay();
[email protected]45d0ef7f2011-01-05 13:46:231727 }
[email protected]987fc3a2011-05-26 14:18:091728
1729 // |page_title_when_no_navigation_entry_| is finally used
1730 // if no title cannot be retrieved.
1731 return page_title_when_no_navigation_entry_;
[email protected]96d185d2009-04-24 03:28:541732}
1733
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411734SiteInstanceImpl* WebContentsImpl::GetSiteInstance() {
[email protected]fa944cb82013-11-15 17:51:211735 return GetRenderManager()->current_host()->GetSiteInstance();
[email protected]96d185d2009-04-24 03:28:541736}
1737
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411738bool WebContentsImpl::IsLoading() {
Carlos ILd51e7702020-05-07 18:51:391739 return frame_tree_.IsLoading();
[email protected]3c9e1872010-11-18 16:17:491740}
1741
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411742double WebContentsImpl::GetLoadProgress() {
Peter Boström18a40fa2018-10-31 19:03:501743 return frame_tree_.load_progress();
1744}
1745
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411746bool WebContentsImpl::IsLoadingToDifferentDocument() {
clamy44e84ce2016-02-22 15:38:251747 return IsLoading() && is_load_to_different_document_;
[email protected]6dfed692014-05-22 04:18:031748}
1749
Alexander Timindd0fa0c52019-11-06 13:03:371750bool WebContentsImpl::IsDocumentOnLoadCompletedInMainFrame() {
1751 return GetRenderViewHost()->IsDocumentOnLoadCompletedInMainFrame();
1752}
1753
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411754bool WebContentsImpl::IsWaitingForResponse() {
Peter Boströma9a27f6e2018-11-21 13:12:191755 NavigationRequest* ongoing_navigation_request =
1756 frame_tree_.root()->navigation_request();
1757
1758 // An ongoing navigation request means we're waiting for a response.
1759 return ongoing_navigation_request != nullptr;
[email protected]be1f56ab2011-12-22 06:55:311760}
1761
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411762const net::LoadStateWithParam& WebContentsImpl::GetLoadState() {
[email protected]be1f56ab2011-12-22 06:55:311763 return load_state_;
1764}
1765
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411766const base::string16& WebContentsImpl::GetLoadStateHost() {
[email protected]be1f56ab2011-12-22 06:55:311767 return load_state_host_;
1768}
1769
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411770uint64_t WebContentsImpl::GetUploadSize() {
[email protected]be1f56ab2011-12-22 06:55:311771 return upload_size_;
1772}
1773
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411774uint64_t WebContentsImpl::GetUploadPosition() {
[email protected]be1f56ab2011-12-22 06:55:311775 return upload_position_;
1776}
1777
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411778const std::string& WebContentsImpl::GetEncoding() {
Alexander Timine5f20e22019-10-09 23:22:351779 return GetMainFrame()->GetEncoding();
[email protected]be1f56ab2011-12-22 06:55:311780}
1781
Charles Zhaod72f99d2018-09-17 14:18:271782bool WebContentsImpl::WasDiscarded() {
1783 return GetFrameTree()->root()->was_discarded();
1784}
1785
Shubhie Panickerddf2a4e2018-03-06 00:09:061786void WebContentsImpl::SetWasDiscarded(bool was_discarded) {
1787 GetFrameTree()->root()->set_was_discarded();
1788}
1789
Collin Bakerc5259962019-11-14 17:51:581790void WebContentsImpl::IncrementCapturerCount(const gfx::Size& capture_size,
1791 bool stay_hidden) {
Alexander Timin5fdeff22020-09-08 09:20:371792 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::IncrementCapturerCount");
[email protected]5a652232013-02-12 06:15:251793 DCHECK(!is_being_destroyed_);
Xianzhu Wang724e08f2020-09-01 21:35:071794 if (stay_hidden) {
1795 // A hidden capture should not have side effect on the web contents, so it
1796 // should not pass a non-empty |capture_size| which will cause side effect.
1797 DCHECK(capture_size.IsEmpty());
Collin Bakerc5259962019-11-14 17:51:581798 ++hidden_capturer_count_;
Xianzhu Wang724e08f2020-09-01 21:35:071799 } else {
Collin Bakerc5259962019-11-14 17:51:581800 ++visible_capturer_count_;
Xianzhu Wang724e08f2020-09-01 21:35:071801 }
[email protected]222f5822014-02-05 23:40:491802
1803 // Note: This provides a hint to upstream code to size the views optimally
1804 // for quality (e.g., to avoid scaling).
1805 if (!capture_size.IsEmpty() && preferred_size_for_capture_.IsEmpty()) {
1806 preferred_size_for_capture_ = capture_size;
1807 OnPreferredSizeChanged(preferred_size_);
1808 }
ccameron8807c38f2015-01-17 00:29:191809
Collin Bakerc5259962019-11-14 17:51:581810 UpdateVisibilityAndNotifyPageAndView(GetVisibility());
[email protected]54597982013-02-06 01:59:551811}
1812
Collin Bakerc5259962019-11-14 17:51:581813void WebContentsImpl::DecrementCapturerCount(bool stay_hidden) {
Alexander Timin5fdeff22020-09-08 09:20:371814 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DecrementCapturerCount");
Collin Bakerc5259962019-11-14 17:51:581815 if (stay_hidden)
1816 --hidden_capturer_count_;
1817 else
1818 --visible_capturer_count_;
1819 DCHECK_GE(hidden_capturer_count_, 0);
1820 DCHECK_GE(visible_capturer_count_, 0);
[email protected]54597982013-02-06 01:59:551821
[email protected]5a652232013-02-12 06:15:251822 if (is_being_destroyed_)
1823 return;
1824
Francois Doray24fc62c2017-12-11 17:27:331825 if (!IsBeingCaptured()) {
[email protected]222f5822014-02-05 23:40:491826 const gfx::Size old_size = preferred_size_for_capture_;
1827 preferred_size_for_capture_ = gfx::Size();
1828 OnPreferredSizeChanged(old_size);
[email protected]54597982013-02-06 01:59:551829 }
Collin Bakerc5259962019-11-14 17:51:581830
1831 UpdateVisibilityAndNotifyPageAndView(GetVisibility());
[email protected]be1f56ab2011-12-22 06:55:311832}
1833
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411834bool WebContentsImpl::IsBeingCaptured() {
Collin Bakerc5259962019-11-14 17:51:581835 return visible_capturer_count_ + hidden_capturer_count_ > 0;
[email protected]f2bd40812013-07-20 04:30:441836}
1837
Xianzhu Wangc61434c2020-08-21 19:17:301838bool WebContentsImpl::IsBeingVisiblyCaptured() {
1839 return visible_capturer_count_ > 0;
1840}
1841
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411842bool WebContentsImpl::IsAudioMuted() {
Guido Urdanetaf8372942019-11-15 09:47:211843 return audio_stream_factory_ && audio_stream_factory_->IsMuted();
miu50f97892014-09-22 22:49:521844}
1845
1846void WebContentsImpl::SetAudioMuted(bool mute) {
Alexander Timin5fdeff22020-09-08 09:20:371847 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetAudioMuted", "mute",
1848 mute);
miu50f97892014-09-22 22:49:521849 DVLOG(1) << "SetAudioMuted(mute=" << mute << "), was " << IsAudioMuted()
1850 << " for WebContentsImpl@" << this;
1851
1852 if (mute == IsAudioMuted())
1853 return;
1854
Guido Urdanetaf8372942019-11-15 09:47:211855 GetAudioStreamFactory()->SetMuted(mute);
miu50f97892014-09-22 22:49:521856
Alexander Timin90c20c32020-08-12 15:28:321857 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1858 observer->DidUpdateAudioMutingState(mute);
1859 });
Jan Rucka442c83f2017-08-08 13:27:541860 // Notification for UI updates in response to the changed muting state.
Collin Bakeraf540cf2019-09-20 20:54:161861 NotifyNavigationStateChanged(INVALIDATE_TYPE_AUDIO);
Jan Rucka442c83f2017-08-08 13:27:541862}
1863
1864bool WebContentsImpl::IsCurrentlyAudible() {
Chris Hamiltondf0d72cd2018-05-29 16:23:531865 return is_currently_audible_;
miu50f97892014-09-22 22:49:521866}
1867
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411868bool WebContentsImpl::IsConnectedToBluetoothDevice() {
ortunodf4d7982016-04-08 02:33:351869 return bluetooth_connected_device_count_ > 0;
ortuno32e7db3c2016-03-29 16:14:201870}
1871
Ovidio Henriquez76696f62020-07-08 03:06:591872bool WebContentsImpl::IsScanningForBluetoothDevices() {
1873 return bluetooth_scanning_sessions_count_ > 0;
1874}
1875
Lucas Furukawa Gadani4b4eed02019-06-04 23:12:041876bool WebContentsImpl::IsConnectedToSerialPort() {
Reilly Grant5e7c79b22019-04-09 17:26:201877 return serial_active_frame_count_ > 0;
1878}
1879
Matt Reynoldse8c6c1f2019-11-02 09:53:531880bool WebContentsImpl::IsConnectedToHidDevice() {
1881 return hid_active_frame_count_ > 0;
1882}
1883
Marijn Kruisselbrink29051042019-08-06 22:56:551884bool WebContentsImpl::HasNativeFileSystemHandles() {
1885 return native_file_system_handle_count_ > 0;
1886}
Marijn Kruisselbrinkf1714aa22019-07-02 03:45:331887
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411888bool WebContentsImpl::HasPictureInPictureVideo() {
sawtellea7333a82018-05-31 02:36:361889 return has_picture_in_picture_video_;
1890}
1891
1892void WebContentsImpl::SetHasPictureInPictureVideo(
1893 bool has_picture_in_picture_video) {
Alexander Timin5fdeff22020-09-08 09:20:371894 OPTIONAL_TRACE_EVENT1("content",
1895 "WebContentsImpl::SetHasPictureInPictureVideo",
1896 "has_pip_video", has_picture_in_picture_video);
sawtellea7333a82018-05-31 02:36:361897 // If status of |this| is already accurate, there is no need to update.
1898 if (has_picture_in_picture_video == has_picture_in_picture_video_)
1899 return;
1900 has_picture_in_picture_video_ = has_picture_in_picture_video;
1901 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
Alexander Timin90c20c32020-08-12 15:28:321902 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1903 observer->MediaPictureInPictureChanged(has_picture_in_picture_video_);
1904 });
sawtellea7333a82018-05-31 02:36:361905}
1906
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411907bool WebContentsImpl::IsCrashed() {
Dominic Mazzoni73a48322018-05-25 18:14:071908 switch (crashed_status_) {
1909 case base::TERMINATION_STATUS_PROCESS_CRASHED:
1910 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
1911 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED:
1912 case base::TERMINATION_STATUS_OOM:
1913 case base::TERMINATION_STATUS_LAUNCH_FAILED:
Darin Fisher6cf20e782020-08-07 22:25:361914#if defined(OS_CHROMEOS) || BUILDFLAG(IS_LACROS)
Dominic Mazzoni73a48322018-05-25 18:14:071915 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM:
oshima620225722015-06-04 19:45:271916#endif
Dominic Mazzoni73a48322018-05-25 18:14:071917#if defined(OS_ANDROID)
1918 case base::TERMINATION_STATUS_OOM_PROTECTED:
1919#endif
Will Harris07925d12019-10-31 03:03:051920#if defined(OS_WIN)
1921 case base::TERMINATION_STATUS_INTEGRITY_FAILURE:
1922#endif
Dominic Mazzoni73a48322018-05-25 18:14:071923 return true;
1924 case base::TERMINATION_STATUS_NORMAL_TERMINATION:
1925 case base::TERMINATION_STATUS_STILL_RUNNING:
1926 return false;
1927 case base::TERMINATION_STATUS_MAX_ENUM:
1928 NOTREACHED();
1929 return false;
1930 }
1931
1932 NOTREACHED();
1933 return false;
[email protected]3c9e1872010-11-18 16:17:491934}
1935
[email protected]b172aee2012-04-10 17:05:261936void WebContentsImpl::SetIsCrashed(base::TerminationStatus status,
1937 int error_code) {
Alexander Timin5fdeff22020-09-08 09:20:371938 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetIsCrashed", "status",
1939 static_cast<int>(status), "old_status",
1940 static_cast<int>(crashed_status_));
[email protected]443b80e2010-12-14 00:42:231941 if (status == crashed_status_)
[email protected]d5f942ba2008-09-26 19:30:341942 return;
1943
[email protected]443b80e2010-12-14 00:42:231944 crashed_status_ = status;
1945 crashed_error_code_ = error_code;
[email protected]8ff00d72012-10-23 19:12:211946 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
[email protected]d5f942ba2008-09-26 19:30:341947}
1948
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411949base::TerminationStatus WebContentsImpl::GetCrashedStatus() {
[email protected]be1f56ab2011-12-22 06:55:311950 return crashed_status_;
1951}
1952
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411953int WebContentsImpl::GetCrashedErrorCode() {
afakhry98241832016-03-11 19:27:471954 return crashed_error_code_;
1955}
1956
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411957bool WebContentsImpl::IsBeingDestroyed() {
[email protected]be1f56ab2011-12-22 06:55:311958 return is_being_destroyed_;
1959}
1960
[email protected]7f924832014-08-09 05:57:221961void WebContentsImpl::NotifyNavigationStateChanged(
1962 InvalidateTypes changed_flags) {
Alexander Timin5fdeff22020-09-08 09:20:371963 TRACE_EVENT1("content,navigation",
1964 "WebContentsImpl::NotifyNavigationStateChanged", "changed_flags",
1965 static_cast<int>(changed_flags));
dalecurtis88c240072015-12-09 02:11:181966 // Notify the media observer of potential audibility changes.
Collin Bakeraf540cf2019-09-20 20:54:161967 if (changed_flags & INVALIDATE_TYPE_AUDIO) {
mlamouri44e4ef42016-01-20 18:42:271968 media_web_contents_observer_->MaybeUpdateAudibleState();
dalecurtisbc6572e12014-09-12 19:22:301969 }
1970
[email protected]d5f942ba2008-09-26 19:30:341971 if (delegate_)
1972 delegate_->NavigationStateChanged(this, changed_flags);
wjmaclean1dabf3e32016-05-13 23:34:441973
1974 if (GetOuterWebContents())
1975 GetOuterWebContents()->NotifyNavigationStateChanged(changed_flags);
[email protected]d5f942ba2008-09-26 19:30:341976}
1977
W. James MacLean6f34b042019-07-12 19:25:301978RenderFrameHostImpl* WebContentsImpl::GetFocusedFrameFromFocusedDelegate() {
1979 FrameTreeNode* focused_node =
1980 GetFocusedWebContents()->frame_tree_.GetFocusedFrame();
1981 return focused_node ? focused_node->current_frame_host() : nullptr;
1982}
1983
David Black9cca3592019-11-06 23:02:221984void WebContentsImpl::OnVerticalScrollDirectionChanged(
1985 viz::VerticalScrollDirection scroll_direction) {
Alexander Timin5fdeff22020-09-08 09:20:371986 OPTIONAL_TRACE_EVENT1("content",
1987 "WebContentsImpl::OnVerticalScrollDirectionChanged",
1988 "scroll_direction", static_cast<int>(scroll_direction));
Alexander Timin90c20c32020-08-12 15:28:321989 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1990 observer->DidChangeVerticalScrollDirection(scroll_direction);
1991 });
David Black9cca3592019-11-06 23:02:221992}
1993
Chris Hamiltondf0d72cd2018-05-29 16:23:531994void WebContentsImpl::OnAudioStateChanged() {
1995 // This notification can come from any embedded contents or from this
1996 // WebContents' stream monitor. Aggregate these signals to get the actual
1997 // state.
Jeremy Roman03ce13ce2020-05-29 22:16:571998 //
1999 // Note that guests may not be attached as inner contents, and so may need to
2000 // be checked separately.
Chris Hamiltondf0d72cd2018-05-29 16:23:532001 bool is_currently_audible =
2002 audio_stream_monitor_.IsCurrentlyAudible() ||
2003 (browser_plugin_embedder_ &&
Jeremy Roman03ce13ce2020-05-29 22:16:572004 browser_plugin_embedder_->AreAnyGuestsCurrentlyAudible()) ||
2005 AnyInnerWebContents(this, [](WebContents* inner_contents) {
2006 return inner_contents->IsCurrentlyAudible();
2007 });
Alexander Timin5fdeff22020-09-08 09:20:372008 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnAudioStateChanged",
2009 "is_currently_audible", is_currently_audible,
2010 "was_audible", is_currently_audible_);
Chris Hamiltondf0d72cd2018-05-29 16:23:532011 if (is_currently_audible == is_currently_audible_)
2012 return;
2013
2014 // Update internal state.
2015 is_currently_audible_ = is_currently_audible;
2016 was_ever_audible_ = was_ever_audible_ || is_currently_audible_;
2017
Gyuyoung Kim877e86d2020-07-21 04:01:022018 ExecutePageBroadcastMethod(base::BindRepeating(
2019 [](bool is_currently_audible, RenderViewHostImpl* rvh) {
2020 if (auto& broadcast = rvh->GetAssociatedPageBroadcast())
2021 broadcast->AudioStateChanged(is_currently_audible);
2022 },
2023 is_currently_audible_));
altimind8bd26c2016-11-04 11:44:542024
altiminec87fd1f2016-11-17 20:22:492025 // Notification for UI updates in response to the changed audio state.
Collin Bakeraf540cf2019-09-20 20:54:162026 NotifyNavigationStateChanged(INVALIDATE_TYPE_AUDIO);
Jan Rucka442c83f2017-08-08 13:27:542027
Chris Hamiltondf0d72cd2018-05-29 16:23:532028 // Ensure that audio state changes propagate from innermost to outermost
2029 // WebContents.
2030 if (GetOuterWebContents())
2031 GetOuterWebContents()->OnAudioStateChanged();
Tommy Steimel18360512017-11-01 00:38:192032
Alexander Timin90c20c32020-08-12 15:28:322033 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2034 observer->OnAudioStateChanged(is_currently_audible_);
2035 });
altimind8bd26c2016-11-04 11:44:542036}
2037
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:412038base::TimeTicks WebContentsImpl::GetLastActiveTime() {
[email protected]9a890452014-02-13 22:21:022039 return last_active_time_;
[email protected]3e324142012-06-25 18:26:332040}
2041
[email protected]9e2e4632012-07-27 16:38:412042void WebContentsImpl::WasShown() {
Alexander Timin5fdeff22020-09-08 09:20:372043 TRACE_EVENT0("content", "WebContentsImpl::WasShown");
Collin Baker989e0882019-11-01 01:27:172044 UpdateVisibilityAndNotifyPageAndView(Visibility::VISIBLE);
[email protected]be1f56ab2011-12-22 06:55:312045}
2046
[email protected]b172aee2012-04-10 17:05:262047void WebContentsImpl::WasHidden() {
Alexander Timin5fdeff22020-09-08 09:20:372048 TRACE_EVENT0("content", "WebContentsImpl::WasHidden");
Collin Baker989e0882019-11-01 01:27:172049 UpdateVisibilityAndNotifyPageAndView(Visibility::HIDDEN);
[email protected]375fa1b2012-05-22 22:05:372050}
2051
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:412052bool WebContentsImpl::HasRecentInteractiveInputEvent() {
Daniel Cheng90196c82018-04-25 21:49:142053 static constexpr base::TimeDelta kMaxInterval =
2054 base::TimeDelta::FromSeconds(5);
2055 base::TimeDelta delta =
2056 ui::EventTimeForNow() - last_interactive_input_event_time_;
2057 // Note: the expectation is that the caller is typically expecting an input
2058 // event, e.g. validating that a WebUI message that requires a gesture is
Daniel Chenge81030b32019-07-17 20:20:232059 // actually attached to a gesture.
Daniel Cheng90196c82018-04-25 21:49:142060 return delta <= kMaxInterval;
2061}
2062
Avi Drissman738ea192018-08-29 20:24:162063void WebContentsImpl::SetIgnoreInputEvents(bool ignore_input_events) {
Alexander Timin5fdeff22020-09-08 09:20:372064 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetIgnoreInputEvents",
2065 "ignore_input_events", ignore_input_events);
Avi Drissman738ea192018-08-29 20:24:162066 ignore_input_events_ = ignore_input_events;
2067}
2068
Bo Liu168c8642017-08-28 18:26:022069#if defined(OS_ANDROID)
Bo Liu16dd7b8322018-05-02 21:19:502070void WebContentsImpl::SetMainFrameImportance(
2071 ChildProcessImportance importance) {
Alexander Timin5fdeff22020-09-08 09:20:372072 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetMainFrameImportance",
2073 "importance", static_cast<int>(importance));
Bo Liu16dd7b8322018-05-02 21:19:502074 GetMainFrame()->GetRenderWidgetHost()->SetImportance(importance);
Bo Liu7c6779e92017-08-16 02:02:282075}
Bo Liu168c8642017-08-28 18:26:022076#endif
Bo Liu7c6779e92017-08-16 02:02:282077
ccameron8807c38f2015-01-17 00:29:192078void WebContentsImpl::WasOccluded() {
Alexander Timin5fdeff22020-09-08 09:20:372079 TRACE_EVENT0("content", "WebContentsImpl::WasOccluded");
Collin Baker989e0882019-11-01 01:27:172080 UpdateVisibilityAndNotifyPageAndView(Visibility::OCCLUDED);
ccameron8807c38f2015-01-17 00:29:192081}
2082
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:412083Visibility WebContentsImpl::GetVisibility() {
Francois Doraye6161152018-03-27 22:05:372084 return visibility_;
Francois Dorayfe4a1772018-02-17 04:17:092085}
2086
Rakina Zata Amni26e8d8a2020-08-05 06:06:062087bool WebContentsImpl::NeedToFireBeforeUnloadOrUnloadEvents() {
Alexander Timinc7bee322020-05-19 17:54:342088 if (!notify_disconnection_)
Alex Moshchuk6fcaca752018-07-14 02:13:592089 return false;
2090
2091 // Don't fire if the main frame's RenderViewHost indicates that beforeunload
2092 // and unload have already executed (e.g., after receiving a ClosePage ACK)
2093 // or should be ignored.
2094 if (GetRenderViewHost()->SuddenTerminationAllowed())
2095 return false;
2096
Alex Moshchukc78dbc722019-10-31 20:00:502097 // Check whether any frame in the frame tree needs to run beforeunload or
Rakina Zata Amni26e8d8a2020-08-05 06:06:062098 // unload-time event handlers.
Alex Moshchukc78dbc722019-10-31 20:00:502099 for (FrameTreeNode* node : frame_tree_.Nodes()) {
2100 RenderFrameHostImpl* rfh = node->current_frame_host();
2101
Rakina Zata Amni26e8d8a2020-08-05 06:06:062102 // No need to run beforeunload/unload-time events if the RenderFrame isn't
2103 // live.
Alex Moshchukc78dbc722019-10-31 20:00:502104 if (!rfh->IsRenderFrameLive())
2105 continue;
Rakina Zata Amni26e8d8a2020-08-05 06:06:062106 bool should_run_before_unload_handler =
Dave Tapuska97d22ab2019-12-03 17:56:362107 rfh->GetSuddenTerminationDisablerState(
Rakina Zata Amni26e8d8a2020-08-05 06:06:062108 blink::mojom::SuddenTerminationDisablerType::kBeforeUnloadHandler);
2109 bool should_run_unload_handler = rfh->GetSuddenTerminationDisablerState(
2110 blink::mojom::SuddenTerminationDisablerType::kUnloadHandler);
2111 bool should_run_page_hide_handler = rfh->GetSuddenTerminationDisablerState(
2112 blink::mojom::SuddenTerminationDisablerType::kPageHideHandler);
2113 auto* rvh = static_cast<RenderViewHostImpl*>(rfh->GetRenderViewHost());
2114 // If the tab is already hidden, we should not run visibilitychange
2115 // handlers.
2116 bool is_page_visible = rvh->GetPageLifecycleStateManager()
2117 ->CalculatePageLifecycleState()
2118 ->visibility == PageVisibilityState::kVisible;
2119
2120 bool should_run_visibility_change_handler =
2121 is_page_visible && rfh->GetSuddenTerminationDisablerState(
2122 blink::mojom::SuddenTerminationDisablerType::
2123 kVisibilityChangeHandler);
2124 if (should_run_before_unload_handler || should_run_unload_handler ||
2125 should_run_page_hide_handler || should_run_visibility_change_handler) {
Alex Moshchukc78dbc722019-10-31 20:00:502126 return true;
2127 }
Aditya Keerthi34f37e62019-03-08 15:54:532128 }
Alex Moshchuk6fcaca752018-07-14 02:13:592129
Alex Moshchukc78dbc722019-10-31 20:00:502130 return false;
[email protected]be1f56ab2011-12-22 06:55:312131}
2132
Chris Hamilton3b3e315d2018-09-19 13:16:212133void WebContentsImpl::DispatchBeforeUnload(bool auto_cancel) {
Alexander Timin5fdeff22020-09-08 09:20:372134 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DispatchBeforeUnload",
2135 "auto_cancel", auto_cancel);
Chris Hamilton3b3e315d2018-09-19 13:16:212136 auto before_unload_type =
2137 auto_cancel ? RenderFrameHostImpl::BeforeUnloadType::DISCARD
2138 : RenderFrameHostImpl::BeforeUnloadType::TAB_CLOSE;
2139 GetMainFrame()->DispatchBeforeUnload(before_unload_type, false);
[email protected]1c3f80bd2014-04-08 23:02:062140}
2141
W. James MacLean2539adb32019-12-13 00:40:442142bool WebContentsImpl::IsInnerWebContentsForGuest() {
2143 return !!browser_plugin_guest_;
2144}
2145
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502146void WebContentsImpl::AttachInnerWebContents(
2147 std::unique_ptr<WebContents> inner_web_contents,
W. James MacLean62883982019-11-12 20:39:002148 RenderFrameHost* render_frame_host,
2149 bool is_full_page) {
Alexander Timin5fdeff22020-09-08 09:20:372150 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::AttachInnerWebContents",
2151 "inner_web_contents", inner_web_contents.get(),
2152 "is_full_page", is_full_page);
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502153 WebContentsImpl* inner_web_contents_impl =
2154 static_cast<WebContentsImpl*>(inner_web_contents.get());
2155 DCHECK(!inner_web_contents_impl->node_.outer_web_contents());
2156 auto* render_frame_host_impl =
2157 static_cast<RenderFrameHostImpl*>(render_frame_host);
Fergal Daly445af932020-06-02 06:37:232158 DCHECK_EQ(&frame_tree_, render_frame_host_impl->frame_tree());
Lucas Furukawa Gadani105de1e812018-05-31 19:38:392159
Yuzu Saijo3f86fb22020-06-11 03:51:102160 // Mark |render_frame_host_impl| as outer delegate frame.
2161 render_frame_host_impl->SetIsOuterDelegateFrame(true);
2162
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502163 RenderFrameHostManager* inner_render_manager =
2164 inner_web_contents_impl->GetRenderManager();
2165 RenderFrameHostImpl* inner_main_frame =
2166 inner_render_manager->current_frame_host();
2167 RenderViewHostImpl* inner_render_view_host =
2168 inner_render_manager->current_host();
2169 auto* outer_render_manager =
2170 render_frame_host_impl->frame_tree_node()->render_manager();
lfg91a79e12016-04-01 23:52:192171
Lucas Furukawa Gadani105de1e812018-05-31 19:38:392172 // When attaching a WebContents as an inner WebContents, we need to replace
2173 // the Webcontents' view with a WebContentsViewChildFrame.
Fergal Daly55b6d722020-09-11 07:56:332174 inner_web_contents_impl->view_ = std::make_unique<WebContentsViewChildFrame>(
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502175 inner_web_contents_impl,
2176 GetContentClient()->browser()->GetWebContentsViewDelegate(
2177 inner_web_contents_impl),
Fergal Daly55b6d722020-09-11 07:56:332178 &inner_web_contents_impl->render_view_host_delegate_view_);
Lucas Furukawa Gadani105de1e812018-05-31 19:38:392179
lfg91a79e12016-04-01 23:52:192180 // When the WebContents being initialized has an opener, the browser side
2181 // Render{View,Frame}Host must be initialized and the RenderWidgetHostView
2182 // created. This is needed because the usual initialization happens during
2183 // the first navigation, but when attaching a new window we don't navigate
2184 // before attaching. If the browser side is already initialized, the calls
2185 // below will just early return.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502186 inner_render_manager->InitRenderView(inner_render_view_host, nullptr);
2187 inner_main_frame->Init();
2188 if (!inner_render_manager->GetRenderWidgetHostView()) {
2189 inner_web_contents_impl->CreateRenderWidgetHostViewForRenderManager(
2190 inner_render_view_host);
2191 }
lfg91a79e12016-04-01 23:52:192192
Adithya Srinivasane6e7f842019-12-16 18:41:362193 inner_web_contents_impl->RecursivelyUnregisterFrameSinkIds();
2194
lazyboy6ec48b2a2015-06-29 15:18:142195 // Create a link to our outer WebContents.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502196 node_.AttachInnerWebContents(std::move(inner_web_contents),
2197 render_frame_host_impl);
lazyboy6ec48b2a2015-06-29 15:18:142198
lazyboy6ec48b2a2015-06-29 15:18:142199 // Create a proxy in top-level RenderFrameHostManager, pointing to the
2200 // SiteInstance of the outer WebContents. The proxy will be used to send
2201 // postMessage to the inner WebContents.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502202 auto* proxy = inner_render_manager->CreateOuterDelegateProxy(
2203 render_frame_host_impl->GetSiteInstance());
lazyboy6ec48b2a2015-06-29 15:18:142204
Lucas Furukawa Gadani99125822019-01-03 15:41:492205 // When attaching a GuestView as an inner WebContents, there should already be
2206 // a live RenderFrame, which has to be swapped. When attaching a portal, there
2207 // will not be a live RenderFrame before creating the proxy.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502208 if (render_frame_host_impl->IsRenderFrameLive()) {
2209 inner_render_manager->SwapOuterDelegateFrame(render_frame_host_impl, proxy);
Lucas Furukawa Gadani99125822019-01-03 15:41:492210
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502211 inner_web_contents_impl->ReattachToOuterWebContentsFrame();
Lucas Furukawa Gadani99125822019-01-03 15:41:492212 }
ekaramadadd882292016-06-08 15:22:562213
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502214 if (frame_tree_.GetFocusedFrame() ==
2215 render_frame_host_impl->frame_tree_node()) {
2216 inner_web_contents_impl->SetFocusedFrame(
2217 inner_web_contents_impl->frame_tree_.root(),
2218 render_frame_host_impl->GetSiteInstance());
avallee7529b2a2017-04-26 11:37:512219 }
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502220 outer_render_manager->set_attach_complete();
W. James MacLean62883982019-11-12 20:39:002221
2222 // If the inner WebContents is full frame, give it focus.
2223 if (is_full_page) {
2224 // There should only ever be one inner WebContents when |is_full_page| is
2225 // true, and it is the one we just attached.
2226 DCHECK_EQ(1u, node_.GetInnerWebContents().size());
2227 inner_web_contents_impl->SetAsFocusedWebContentsIfNecessary();
2228 }
Chris Hamilton16b5d1d2020-06-04 00:08:122229
Alexander Timin90c20c32020-08-12 15:28:322230 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2231 observer->InnerWebContentsAttached(inner_web_contents_impl,
2232 render_frame_host, is_full_page);
2233 });
Mario Sanchez Prada989aeb7a2020-10-13 09:42:562234
2235 // Make sure that the inner web contents and its outer delegate get properly
2236 // linked via the embedding token now that inner web contents are attached.
2237 inner_main_frame->PropagateEmbeddingTokenToParentFrame();
lazyboy6ec48b2a2015-06-29 15:18:142238}
2239
Lucas Furukawa Gadani99125822019-01-03 15:41:492240std::unique_ptr<WebContents> WebContentsImpl::DetachFromOuterWebContents() {
Alexander Timin5fdeff22020-09-08 09:20:372241 OPTIONAL_TRACE_EVENT0("content",
2242 "WebContentsImpl::DetachFromOuterWebContents");
Chris Hamilton16b5d1d2020-06-04 00:08:122243 auto* outer_web_contents = GetOuterWebContents();
2244 DCHECK(outer_web_contents);
Yuzu Saijo3f86fb22020-06-11 03:51:102245 GetMainFrame()->ParentOrOuterDelegateFrame()->SetIsOuterDelegateFrame(false);
Chris Hamilton16b5d1d2020-06-04 00:08:122246
Adithya Srinivasane6e7f842019-12-16 18:41:362247 RecursivelyUnregisterFrameSinkIds();
Lucas Gadanid29952582020-06-09 21:24:002248
2249 // Each RenderViewHost has a RenderWidgetHost which can have a
2250 // RenderWidgetHostView, and it needs to be re-created with the appropriate
2251 // platform view. It is important to re-create all child views, not only the
2252 // current one, since the view can be swapped due to a cross-origin
2253 // navigation.
2254 std::set<RenderViewHostImpl*> render_view_hosts;
2255 for (auto& render_view_host : GetFrameTree()->render_view_hosts()) {
2256 if (render_view_host.second->GetWidget() &&
2257 render_view_host.second->GetWidget()->GetView()) {
2258 DCHECK(render_view_host.second->GetWidget()
2259 ->GetView()
2260 ->IsRenderWidgetHostViewChildFrame());
2261 render_view_hosts.insert(render_view_host.second);
Kevin McNee6471a702020-01-27 18:23:072262 }
2263 }
Lucas Gadanid29952582020-06-09 21:24:002264
2265 for (auto* render_view_host : render_view_hosts)
2266 render_view_host->GetWidget()->GetView()->Destroy();
2267
Lucas Furukawa Gadani99125822019-01-03 15:41:492268 GetRenderManager()->DeleteOuterDelegateProxy(
2269 node_.OuterContentsFrameTreeNode()
2270 ->current_frame_host()
2271 ->GetSiteInstance());
2272 view_.reset(CreateWebContentsView(
2273 this, GetContentClient()->browser()->GetWebContentsViewDelegate(this),
2274 &render_view_host_delegate_view_));
danakjfc5184932019-09-12 18:08:322275 view_->CreateView(nullptr);
Lucas Furukawa Gadani99125822019-01-03 15:41:492276 std::unique_ptr<WebContents> web_contents =
2277 node_.DisconnectFromOuterWebContents();
2278 DCHECK_EQ(web_contents.get(), this);
2279 node_.SetFocusedWebContents(this);
Lucas Gadanid29952582020-06-09 21:24:002280
2281 for (auto* render_view_host : render_view_hosts)
2282 CreateRenderWidgetHostViewForRenderManager(render_view_host);
2283
Adithya Srinivasane6e7f842019-12-16 18:41:362284 RecursivelyRegisterFrameSinkIds();
Adithya Srinivasan6f0f67b2019-12-19 01:26:462285 // TODO(adithyas): |browser_plugin_embedder_ax_tree_id| should either not be
2286 // used for portals, or it should get a different name.
2287 GetMainFrame()->set_browser_plugin_embedder_ax_tree_id(ui::AXTreeIDUnknown());
2288 GetMainFrame()->UpdateAXTreeData();
Chris Hamilton16b5d1d2020-06-04 00:08:122289
2290 // Invoke on the *outer* web contents observers for symmetry.
Alexander Timin90c20c32020-08-12 15:28:322291 outer_web_contents->observers_.ForEachObserver(
2292 [&](WebContentsObserver* observer) {
2293 observer->InnerWebContentsDetached(this);
2294 });
Chris Hamilton16b5d1d2020-06-04 00:08:122295
Lucas Furukawa Gadani99125822019-01-03 15:41:492296 return web_contents;
2297}
2298
W. James MacLean2dc75ed42019-03-06 14:31:092299void WebContentsImpl::RecursivelyRegisterFrameSinkIds() {
Alexander Timin5fdeff22020-09-08 09:20:372300 OPTIONAL_TRACE_EVENT0("content",
2301 "WebContentsImpl::RecursivelyRegisterFrameSinkIds");
Adithya Srinivasane6e7f842019-12-16 18:41:362302 for (auto* view : GetRenderWidgetHostViewsInWebContentsTree()) {
2303 auto* rwhvb = static_cast<RenderWidgetHostViewBase*>(view);
2304 if (rwhvb->IsRenderWidgetHostViewChildFrame())
2305 static_cast<RenderWidgetHostViewChildFrame*>(view)->RegisterFrameSinkId();
2306 }
2307}
W. James MacLean2dc75ed42019-03-06 14:31:092308
Adithya Srinivasane6e7f842019-12-16 18:41:362309void WebContentsImpl::RecursivelyUnregisterFrameSinkIds() {
Alexander Timin5fdeff22020-09-08 09:20:372310 OPTIONAL_TRACE_EVENT0("content",
2311 "WebContentsImpl::RecursivelyUnregisterFrameSinkIds");
Adithya Srinivasane6e7f842019-12-16 18:41:362312 for (auto* view : GetRenderWidgetHostViewsInWebContentsTree()) {
2313 auto* rwhvb = static_cast<RenderWidgetHostViewBase*>(view);
2314 if (rwhvb->IsRenderWidgetHostViewChildFrame()) {
2315 static_cast<RenderWidgetHostViewChildFrame*>(view)
2316 ->UnregisterFrameSinkId();
2317 }
W. James MacLean2dc75ed42019-03-06 14:31:092318 }
2319}
2320
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:142321void WebContentsImpl::ReattachToOuterWebContentsFrame() {
Alexander Timin5fdeff22020-09-08 09:20:372322 OPTIONAL_TRACE_EVENT0("content",
2323 "WebContentsImpl::ReattachToOuterWebContentsFrame");
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:142324 DCHECK(node_.outer_web_contents());
2325 auto* render_manager = GetRenderManager();
2326 auto* parent_frame =
2327 node_.OuterContentsFrameTreeNode()->current_frame_host()->GetParent();
2328 render_manager->SetRWHViewForInnerContents(
2329 render_manager->GetRenderWidgetHostView());
2330
W. James MacLean2dc75ed42019-03-06 14:31:092331 RecursivelyRegisterFrameSinkIds();
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:142332
2333 // Set up the the guest's AX tree to point back at the embedder's AX tree.
2334 GetMainFrame()->set_browser_plugin_embedder_ax_tree_id(
2335 parent_frame->GetAXTreeID());
2336 GetMainFrame()->UpdateAXTreeData();
2337}
2338
Lucas Gadani972985622020-05-28 20:52:512339void WebContentsImpl::DidActivatePortal(
2340 WebContentsImpl* predecessor_web_contents,
2341 base::TimeTicks activation_time) {
Alexander Timin5fdeff22020-09-08 09:20:372342 TRACE_EVENT2("content", "WebContentsImpl::DidActivatePortal", "predecessor",
2343 predecessor_web_contents, "activation_time", activation_time);
Lucas Gadani972985622020-05-28 20:52:512344 DCHECK(predecessor_web_contents);
Kevin McNeef8eb64c2020-04-21 21:36:062345 NotifyInsidePortal(false);
Alexander Timin90c20c32020-08-12 15:28:322346 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2347 observer->DidActivatePortal(predecessor_web_contents, activation_time);
2348 });
Lucas Gadani972985622020-05-28 20:52:512349 GetDelegate()->WebContentsBecamePortal(predecessor_web_contents);
Kevin McNeef8eb64c2020-04-21 21:36:062350}
2351
Adithya Srinivasan11af2c52019-12-16 22:52:552352void WebContentsImpl::NotifyInsidePortal(bool inside_portal) {
Alexander Timin5fdeff22020-09-08 09:20:372353 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::NotifyInsidePortal",
2354 "inside_portal", inside_portal);
Gyuyoung Kim1c029712020-07-22 09:21:062355 ExecutePageBroadcastMethod(base::BindRepeating(
2356 [](bool inside_portal, RenderViewHostImpl* rvh) {
2357 if (auto& broadcast = rvh->GetAssociatedPageBroadcast())
2358 broadcast->SetInsidePortal(inside_portal);
2359 },
2360 inside_portal));
Adithya Srinivasan11af2c52019-12-16 22:52:552361}
2362
dalecurtis6c58ed02016-10-28 23:02:372363void WebContentsImpl::DidChangeVisibleSecurityState() {
Alexander Timin5fdeff22020-09-08 09:20:372364 OPTIONAL_TRACE_EVENT0("content",
2365 "WebContentsImpl::DidChangeVisibleSecurityState");
Emily Starkc663b0242019-04-26 19:34:452366 if (delegate_)
dalecurtis6c58ed02016-10-28 23:02:372367 delegate_->VisibleSecurityStateChanged(this);
Alexander Timin90c20c32020-08-12 15:28:322368 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2369 observer->DidChangeVisibleSecurityState();
2370 });
dalecurtis6c58ed02016-10-28 23:02:372371}
2372
Gyuyoung Kim1ac4ca782020-09-11 03:32:512373const blink::web_pref::WebPreferences WebContentsImpl::ComputeWebPreferences() {
Alexander Timin5fdeff22020-09-08 09:20:372374 OPTIONAL_TRACE_EVENT0("browser", "WebContentsImpl::ComputeWebPreferences");
2375
Gyuyoung Kim1ac4ca782020-09-11 03:32:512376 blink::web_pref::WebPreferences prefs;
Rakina Zata Amni4029b6d2020-07-28 02:36:202377
2378 const base::CommandLine& command_line =
2379 *base::CommandLine::ForCurrentProcess();
2380
2381 SetSlowWebPreferences(command_line, &prefs);
2382
2383 prefs.web_security_enabled =
2384 !command_line.HasSwitch(switches::kDisableWebSecurity);
2385
2386 prefs.remote_fonts_enabled =
2387 !command_line.HasSwitch(switches::kDisableRemoteFonts);
2388 prefs.application_cache_enabled =
2389 base::FeatureList::IsEnabled(blink::features::kAppCache);
2390 prefs.local_storage_enabled =
2391 !command_line.HasSwitch(switches::kDisableLocalStorage);
2392 prefs.databases_enabled =
2393 !command_line.HasSwitch(switches::kDisableDatabases);
2394
2395 prefs.webgl1_enabled = !command_line.HasSwitch(switches::kDisable3DAPIs) &&
2396 !command_line.HasSwitch(switches::kDisableWebGL);
2397 prefs.webgl2_enabled = !command_line.HasSwitch(switches::kDisable3DAPIs) &&
2398 !command_line.HasSwitch(switches::kDisableWebGL) &&
2399 !command_line.HasSwitch(switches::kDisableWebGL2);
2400
2401 prefs.pepper_3d_enabled = !command_line.HasSwitch(switches::kDisablePepper3d);
2402
2403 prefs.flash_3d_enabled = !command_line.HasSwitch(switches::kDisableFlash3d);
2404 prefs.flash_stage3d_enabled =
2405 !command_line.HasSwitch(switches::kDisableFlashStage3d);
2406 prefs.flash_stage3d_baseline_enabled =
2407 !command_line.HasSwitch(switches::kDisableFlashStage3d);
2408
2409 prefs.allow_file_access_from_file_urls =
2410 command_line.HasSwitch(switches::kAllowFileAccessFromFiles);
2411
2412 prefs.accelerated_2d_canvas_enabled =
2413 !command_line.HasSwitch(switches::kDisableAccelerated2dCanvas);
2414 prefs.new_canvas_2d_api_enabled =
Rakina Zata Amniea8d0c22020-07-30 17:22:502415 command_line.HasSwitch(switches::kEnableNewCanvas2DAPI) ||
2416 base::FeatureList::IsEnabled(features::kEnableNewCanvas2DAPI);
Rakina Zata Amni4029b6d2020-07-28 02:36:202417 prefs.antialiased_2d_canvas_disabled =
2418 command_line.HasSwitch(switches::kDisable2dCanvasAntialiasing);
2419 prefs.antialiased_clips_2d_canvas_enabled =
2420 !command_line.HasSwitch(switches::kDisable2dCanvasClipAntialiasing);
2421
2422 prefs.disable_ipc_flooding_protection =
2423 command_line.HasSwitch(switches::kDisableIpcFloodingProtection) ||
2424 command_line.HasSwitch(switches::kDisablePushStateThrottle);
2425
2426 prefs.accelerated_video_decode_enabled =
2427 !command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode);
2428
2429 std::string autoplay_policy = media::GetEffectiveAutoplayPolicy(command_line);
2430 if (autoplay_policy == switches::autoplay::kNoUserGestureRequiredPolicy) {
Gyuyoung Kim1ac4ca782020-09-11 03:32:512431 prefs.autoplay_policy =
Gyuyoung Kimf6c02a262020-10-13 01:36:132432 blink::mojom::AutoplayPolicy::kNoUserGestureRequired;
Rakina Zata Amni4029b6d2020-07-28 02:36:202433 } else if (autoplay_policy ==
2434 switches::autoplay::kUserGestureRequiredPolicy) {
Gyuyoung Kimf6c02a262020-10-13 01:36:132435 prefs.autoplay_policy = blink::mojom::AutoplayPolicy::kUserGestureRequired;
Rakina Zata Amni4029b6d2020-07-28 02:36:202436 } else if (autoplay_policy ==
2437 switches::autoplay::kDocumentUserActivationRequiredPolicy) {
Gyuyoung Kim1ac4ca782020-09-11 03:32:512438 prefs.autoplay_policy =
Gyuyoung Kimf6c02a262020-10-13 01:36:132439 blink::mojom::AutoplayPolicy::kDocumentUserActivationRequired;
Rakina Zata Amni4029b6d2020-07-28 02:36:202440 } else {
2441 NOTREACHED();
2442 }
2443
2444 prefs.dont_send_key_events_to_javascript =
2445 base::FeatureList::IsEnabled(features::kDontSendKeyEventsToJavascript);
2446
2447// TODO(dtapuska): Enable barrel button selection drag support on Android.
2448// crbug.com/758042
2449#if defined(OS_WIN)
2450 prefs.barrel_button_for_drag_enabled =
2451 base::FeatureList::IsEnabled(features::kDirectManipulationStylus);
2452#endif // defined(OS_WIN)
2453
Rakina Zata Amni4029b6d2020-07-28 02:36:202454 prefs.enable_scroll_animator =
2455 command_line.HasSwitch(switches::kEnableSmoothScrolling) ||
2456 (!command_line.HasSwitch(switches::kDisableSmoothScrolling) &&
2457 gfx::Animation::ScrollAnimationsEnabledBySystem());
2458
2459 prefs.prefers_reduced_motion = gfx::Animation::PrefersReducedMotion();
2460
2461 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
2462 GetRenderViewHost()->GetProcess()->GetID())) {
2463 prefs.loads_images_automatically = true;
2464 prefs.javascript_enabled = true;
2465 }
2466
2467 prefs.viewport_enabled = command_line.HasSwitch(switches::kEnableViewport);
2468
2469 if (IsOverridingUserAgent())
2470 prefs.viewport_meta_enabled = false;
2471
2472 prefs.main_frame_resizes_are_orientation_changes =
2473 command_line.HasSwitch(switches::kMainFrameResizesAreOrientationChanges);
2474
2475 prefs.spatial_navigation_enabled =
2476 command_line.HasSwitch(switches::kEnableSpatialNavigation);
2477
2478 if (IsSpatialNavigationDisabled())
2479 prefs.spatial_navigation_enabled = false;
2480
Rakina Zata Amni4029b6d2020-07-28 02:36:202481 prefs.disable_reading_from_canvas =
2482 command_line.HasSwitch(switches::kDisableReadingFromCanvas);
2483
2484 prefs.strict_mixed_content_checking =
2485 command_line.HasSwitch(switches::kEnableStrictMixedContentChecking);
2486
2487 prefs.strict_powerful_feature_restrictions = command_line.HasSwitch(
2488 switches::kEnableStrictPowerfulFeatureRestrictions);
2489
2490 const std::string blockable_mixed_content_group =
2491 base::FieldTrialList::FindFullName("BlockableMixedContent");
2492 prefs.strictly_block_blockable_mixed_content =
2493 blockable_mixed_content_group == "StrictlyBlockBlockableMixedContent";
2494
2495 const std::string plugin_mixed_content_status =
2496 base::FieldTrialList::FindFullName("PluginMixedContentStatus");
2497 prefs.block_mixed_plugin_content =
2498 plugin_mixed_content_status == "BlockableMixedContent";
2499
2500 prefs.v8_cache_options = GetV8CacheOptions();
2501
2502 prefs.user_gesture_required_for_presentation = !command_line.HasSwitch(
2503 switches::kDisableGestureRequirementForPresentation);
2504
2505 if (HideDownloadUI())
2506 prefs.hide_download_ui = true;
2507
2508 // `media_controls_enabled` is `true` by default.
2509 if (HasPersistentVideo())
2510 prefs.media_controls_enabled = false;
2511
2512#if defined(OS_ANDROID)
2513 display::Display display = display::Screen::GetScreen()->GetPrimaryDisplay();
2514 gfx::Size size = display.GetSizeInPixel();
2515 int min_width = size.width() < size.height() ? size.width() : size.height();
2516 prefs.device_scale_adjustment = GetDeviceScaleAdjustment(
2517 static_cast<int>(min_width / display.device_scale_factor()));
2518#endif // OS_ANDROID
2519
2520 GetContentClient()->browser()->OverrideWebkitPrefs(GetRenderViewHost(),
2521 &prefs);
2522 return prefs;
2523}
2524
2525void WebContentsImpl::SetSlowWebPreferences(
2526 const base::CommandLine& command_line,
Gyuyoung Kim1ac4ca782020-09-11 03:32:512527 blink::web_pref::WebPreferences* prefs) {
Alexander Timin5fdeff22020-09-08 09:20:372528 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetSlowWebPreferences");
2529
Rakina Zata Amni4029b6d2020-07-28 02:36:202530 if (web_preferences_.get()) {
2531#define SET_FROM_CACHE(prefs, field) prefs->field = web_preferences_->field
2532
2533 SET_FROM_CACHE(prefs, touch_event_feature_detection_enabled);
2534 SET_FROM_CACHE(prefs, available_pointer_types);
2535 SET_FROM_CACHE(prefs, available_hover_types);
2536 SET_FROM_CACHE(prefs, primary_pointer_type);
2537 SET_FROM_CACHE(prefs, primary_hover_type);
2538 SET_FROM_CACHE(prefs, pointer_events_max_touch_points);
2539 SET_FROM_CACHE(prefs, number_of_cpu_cores);
2540
2541#if defined(OS_ANDROID)
2542 SET_FROM_CACHE(prefs, video_fullscreen_orientation_lock_enabled);
2543 SET_FROM_CACHE(prefs, video_rotate_to_fullscreen_enabled);
2544#endif
2545
2546#undef SET_FROM_CACHE
2547 } else {
2548 // Every prefs->field modified below should have a SET_FROM_CACHE entry
2549 // above.
2550
2551 // On Android, Touch event feature detection is enabled by default,
2552 // Otherwise default is disabled.
2553 std::string touch_enabled_default_switch =
2554 switches::kTouchEventFeatureDetectionDisabled;
2555#if defined(OS_ANDROID)
2556 touch_enabled_default_switch = switches::kTouchEventFeatureDetectionEnabled;
2557#endif // defined(OS_ANDROID)
2558 const std::string touch_enabled_switch =
2559 command_line.HasSwitch(switches::kTouchEventFeatureDetection)
2560 ? command_line.GetSwitchValueASCII(
2561 switches::kTouchEventFeatureDetection)
2562 : touch_enabled_default_switch;
2563
2564 prefs->touch_event_feature_detection_enabled =
2565 (touch_enabled_switch == switches::kTouchEventFeatureDetectionAuto)
2566 ? (ui::GetTouchScreensAvailability() ==
2567 ui::TouchScreensAvailability::ENABLED)
2568 : (touch_enabled_switch.empty() ||
2569 touch_enabled_switch ==
2570 switches::kTouchEventFeatureDetectionEnabled);
2571
2572 std::tie(prefs->available_pointer_types, prefs->available_hover_types) =
2573 ui::GetAvailablePointerAndHoverTypes();
2574 prefs->primary_pointer_type =
2575 ui::GetPrimaryPointerType(prefs->available_pointer_types);
2576 prefs->primary_hover_type =
2577 ui::GetPrimaryHoverType(prefs->available_hover_types);
2578
2579 prefs->pointer_events_max_touch_points = ui::MaxTouchPoints();
2580
2581 prefs->number_of_cpu_cores = base::SysInfo::NumberOfProcessors();
2582
2583#if defined(OS_ANDROID)
2584 const bool device_is_phone =
2585 ui::GetDeviceFormFactor() == ui::DEVICE_FORM_FACTOR_PHONE;
2586 prefs->video_fullscreen_orientation_lock_enabled = device_is_phone;
2587 prefs->video_rotate_to_fullscreen_enabled = device_is_phone;
2588#endif
2589 }
2590}
2591
2592void WebContentsImpl::OnWebPreferencesChanged() {
Alexander Timin5fdeff22020-09-08 09:20:372593 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnWebPreferencesChanged");
2594
Rakina Zata Amni4029b6d2020-07-28 02:36:202595 // This is defensive code to avoid infinite loops due to code run inside
2596 // SetWebPreferences() accidentally updating more preferences and thus
2597 // calling back into this code. See crbug.com/398751 for one past example.
2598 if (updating_web_preferences_)
2599 return;
2600 updating_web_preferences_ = true;
2601 SetWebPreferences(ComputeWebPreferences());
2602#if defined(OS_ANDROID)
2603 for (FrameTreeNode* node : frame_tree_.Nodes()) {
2604 RenderFrameHostImpl* rfh = node->current_frame_host();
2605 if (rfh->is_local_root()) {
2606 if (auto* rwh = rfh->GetRenderWidgetHost())
2607 rwh->SetForceEnableZoom(web_preferences_->force_enable_zoom);
2608 }
2609 }
2610#endif
2611 updating_web_preferences_ = false;
2612}
2613
Ahmed Fakhryd70bf37b2018-04-04 17:07:242614void WebContentsImpl::NotifyPreferencesChanged() {
Alexander Timin5fdeff22020-09-08 09:20:372615 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::NotifyPreferencesChanged");
2616
Rakina Zata Amni347b70902020-07-22 10:49:042617 // Recompute the WebPreferences based on the current state of the WebContents,
Rakina Zata Amni4029b6d2020-07-28 02:36:202618 // etc. Note that OnWebPreferencesChanged will also call SetWebPreferences and
2619 // send the updated WebPreferences to all RenderViews for this WebContents.
2620 OnWebPreferencesChanged();
Ahmed Fakhryd70bf37b2018-04-04 17:07:242621}
2622
Bruce Long1e3e1f542019-10-16 17:56:282623void WebContentsImpl::SyncRendererPrefs() {
Alexander Timin5fdeff22020-09-08 09:20:372624 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SyncRendererPrefs");
2625
Mario Sanchez Prada0bd8b8c2020-10-21 17:49:232626 blink::RendererPreferences renderer_preferences = GetRendererPrefs();
Bruce Long1e3e1f542019-10-16 17:56:282627 RenderViewHostImpl::GetPlatformSpecificPrefs(&renderer_preferences);
2628 SendPageMessage(
2629 new PageMsg_SetRendererPrefs(MSG_ROUTING_NONE, renderer_preferences));
2630}
2631
Alexander Timin1cc31f42020-05-12 16:26:012632void WebContentsImpl::OnCookiesAccessed(NavigationHandle* navigation,
2633 const CookieAccessDetails& details) {
Alexander Timin5fdeff22020-09-08 09:20:372634 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnCookiesAccessed",
2635 "navigation_handle", navigation);
Alexander Timin90c20c32020-08-12 15:28:322636 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2637 observer->OnCookiesAccessed(navigation, details);
2638 });
Alexander Timin1cc31f42020-05-12 16:26:012639}
2640
2641void WebContentsImpl::OnCookiesAccessed(RenderFrameHostImpl* rfh,
2642 const CookieAccessDetails& details) {
Alexander Timin5fdeff22020-09-08 09:20:372643 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnCookiesAccessed",
2644 "render_frame_host",
2645 base::trace_event::ToTracedValue(rfh));
Alexander Timin90c20c32020-08-12 15:28:322646 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2647 observer->OnCookiesAccessed(rfh, details);
2648 });
Josh Karlindaba39322019-07-17 23:24:332649}
2650
[email protected]b172aee2012-04-10 17:05:262651void WebContentsImpl::Stop() {
Alexander Timin5fdeff22020-09-08 09:20:372652 TRACE_EVENT0("content", "WebContentsImpl::Stop");
dcheng57e39e22016-01-21 00:25:382653 for (FrameTreeNode* node : frame_tree_.Nodes())
2654 node->StopLoading();
Alexander Timin90c20c32020-08-12 15:28:322655 observers_.ForEachObserver(
2656 [&](WebContentsObserver* observer) { observer->NavigationStopped(); });
[email protected]0bfbf882011-12-22 18:19:272657}
2658
Francois Doray47f759d2018-06-11 18:13:512659void WebContentsImpl::SetPageFrozen(bool frozen) {
Alexander Timin5fdeff22020-09-08 09:20:372660 TRACE_EVENT1("content", "WebContentsImpl::SetPageFrozen", "frozen", frozen);
2661
Francois Doray47f759d2018-06-11 18:13:512662 // A visible page is never frozen.
2663 DCHECK_NE(Visibility::VISIBLE, GetVisibility());
2664
Yuzu Saijo4fa1e9a2020-05-20 02:53:262665 for (auto& entry : frame_tree_.render_view_hosts()) {
2666 entry.second->SetIsFrozen(frozen);
2667 }
Fadi Meawada6573e02018-03-10 00:52:112668}
2669
erikchen6c7df7f7a2018-05-03 18:13:592670std::unique_ptr<WebContents> WebContentsImpl::Clone() {
Alexander Timin5fdeff22020-09-08 09:20:372671 TRACE_EVENT0("content", "WebContentsImpl::Clone");
2672
[email protected]14392a52012-05-02 20:28:442673 // We use our current SiteInstance since the cloned entry will use it anyway.
alexmose201c7cd2015-06-10 17:14:212674 // We pass our own opener so that the cloned page can access it if it was set
[email protected]ed245db2012-12-18 08:00:452675 // before.
[email protected]54944cde2012-12-09 09:24:592676 CreateParams create_params(GetBrowserContext(), GetSiteInstance());
Ian Clelland5cbaaf82017-11-27 22:00:032677 FrameTreeNode* opener = frame_tree_.root()->opener();
2678 RenderFrameHostImpl* opener_rfh = nullptr;
2679 if (opener)
2680 opener_rfh = opener->current_frame_host();
erikchen6c7df7f7a2018-05-03 18:13:592681 std::unique_ptr<WebContentsImpl> tc =
erikchen50735fd2018-05-05 15:08:332682 CreateWithOpener(create_params, opener_rfh);
Lucas Furukawa Gadani5553a152019-01-08 18:55:572683 tc->GetController().CopyStateFrom(&controller_, true);
Alexander Timin90c20c32020-08-12 15:28:322684 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2685 observer->DidCloneToNewWebContents(this, tc.get());
2686 });
[email protected]0bfbf882011-12-22 18:19:272687 return tc;
2688}
2689
[email protected]14392a52012-05-02 20:28:442690void WebContentsImpl::Observe(int type,
[email protected]8ff00d72012-10-23 19:12:212691 const NotificationSource& source,
2692 const NotificationDetails& details) {
Alexander Timin5fdeff22020-09-08 09:20:372693 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::Observe", "type", type);
[email protected]14392a52012-05-02 20:28:442694 switch (type) {
[email protected]8ff00d72012-10-23 19:12:212695 case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: {
2696 RenderWidgetHost* host = Source<RenderWidgetHost>(source).ptr();
Dave Tapuska406647a2020-10-21 00:55:572697 for (auto i = pending_widget_views_.begin();
2698 i != pending_widget_views_.end(); ++i) {
2699 if (host->GetView() == i->second) {
2700 pending_widget_views_.erase(i);
2701 break;
[email protected]bafe6cd2012-05-23 23:09:502702 }
2703 }
2704 break;
2705 }
[email protected]14392a52012-05-02 20:28:442706 default:
2707 NOTREACHED();
2708 }
2709}
2710
[email protected]ec6c05f2013-10-23 18:41:572711WebContents* WebContentsImpl::GetWebContents() {
2712 return this;
2713}
2714
[email protected]54944cde2012-12-09 09:24:592715void WebContentsImpl::Init(const WebContents::CreateParams& params) {
Alexander Timin5fdeff22020-09-08 09:20:372716 TRACE_EVENT0("content", "WebContentsImpl::Init");
2717
[email protected]fa944cb82013-11-15 17:51:212718 // This is set before initializing the render manager since
[email protected]b0936d22013-11-28 06:47:362719 // RenderFrameHostManager::Init calls back into us via its delegate to ask if
[email protected]fa944cb82013-11-15 17:51:212720 // it should be hidden.
Francois Doraye6161152018-03-27 22:05:372721 visibility_ =
2722 params.initially_hidden ? Visibility::HIDDEN : Visibility::VISIBLE;
[email protected]d6fa88f2013-10-18 16:00:432723
Sebastien Marchand28cf23182018-06-20 02:39:352724 if (!params.last_active_time.is_null())
2725 last_active_time_ = params.last_active_time;
2726
dcheng3ce04b62015-10-26 23:30:552727 scoped_refptr<SiteInstance> site_instance = params.site_instance;
2728 if (!site_instance)
2729 site_instance = SiteInstance::Create(params.browser_context);
Lukasz Anforowicz3caa8372018-06-05 17:22:072730 if (params.desired_renderer_state == CreateParams::kNoRendererProcess) {
2731 static_cast<SiteInstanceImpl*>(site_instance.get())
2732 ->PreventAssociationWithSpareProcess();
2733 }
dcheng3ce04b62015-10-26 23:30:552734
Fergal Dalycb0c1fdf2020-03-16 07:13:492735 GetRenderManager()->InitRoot(site_instance.get(),
2736 params.renderer_initiated_creation);
lukasza464d8692016-02-22 19:26:322737
lukasza5140a412016-09-15 21:12:302738 // blink::FrameTree::setName always keeps |unique_name| empty in case of a
2739 // main frame - let's do the same thing here.
2740 std::string unique_name;
lukasza464d8692016-02-22 19:26:322741 frame_tree_.root()->SetFrameName(params.main_frame_name, unique_name);
[email protected]d1198fd2012-08-13 22:50:192742
[email protected]fc2b46b2014-05-03 16:33:452743 WebContentsViewDelegate* delegate =
2744 GetContentClient()->browser()->GetWebContentsViewDelegate(this);
2745
W. James MacLean2539adb32019-12-13 00:40:442746 if (browser_plugin_guest_) {
Fergal Daly55b6d722020-09-11 07:56:332747 view_ = std::make_unique<WebContentsViewChildFrame>(
2748 this, delegate, &render_view_host_delegate_view_);
sky52a39e342016-12-17 17:23:222749 } else {
2750 view_.reset(CreateWebContentsView(this, delegate,
2751 &render_view_host_delegate_view_));
[email protected]d1198fd2012-08-13 22:50:192752 }
[email protected]fc2b46b2014-05-03 16:33:452753 CHECK(render_view_host_delegate_view_);
[email protected]d1198fd2012-08-13 22:50:192754 CHECK(view_.get());
2755
danakjfc5184932019-09-12 18:08:322756 view_->CreateView(params.context);
[email protected]d1198fd2012-08-13 22:50:192757
brettw4b461082016-11-19 18:55:162758#if BUILDFLAG(ENABLE_PLUGINS)
Fergal Daly55b6d722020-09-11 07:56:332759 plugin_content_origin_allowlist_ =
2760 std::make_unique<PluginContentOriginAllowlist>(this);
tommyclieb25b2a2014-11-03 19:45:092761#endif
2762
[email protected]d1198fd2012-08-13 22:50:192763 registrar_.Add(this,
[email protected]8ff00d72012-10-23 19:12:212764 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
2765 NotificationService::AllBrowserContextsAndSources());
[email protected]f28ef9a32014-05-12 16:36:102766
Fergal Daly55b6d722020-09-11 07:56:332767 screen_orientation_provider_ =
2768 std::make_unique<ScreenOrientationProvider>(this);
[email protected]01f83f92014-06-17 14:41:542769
mfomitchev2b8b066a2016-01-28 19:23:152770#if defined(OS_ANDROID)
Oksana Zhuravlova0b634332019-10-28 23:04:222771 DateTimeChooserAndroid::CreateForWebContents(this);
[email protected]583418cc2013-01-17 14:01:102772#endif
fsamuel7310a4262014-12-05 05:06:442773
2774 // BrowserPluginGuest::Init needs to be called after this WebContents has
W. James MacLean6e78da342019-12-13 15:13:232775 // a RenderWidgetHostViewChildFrame. That is, |view_->CreateView| above.
fsamuel7310a4262014-12-05 05:06:442776 if (browser_plugin_guest_)
2777 browser_plugin_guest_->Init();
nickf9acfbe2014-12-23 19:12:372778
Fergal Daly55b6d722020-09-11 07:56:332779 for (auto& i : g_created_callbacks.Get())
2780 i.Run(this);
naskob21fe4872015-02-24 14:15:562781
2782 // If the WebContents creation was renderer-initiated, it means that the
2783 // corresponding RenderView and main RenderFrame have already been created.
2784 // Ensure observers are notified about this.
2785 if (params.renderer_initiated_creation) {
Fergal Dalybb2d6592020-06-02 05:02:332786 GetRenderViewHost()->GetWidget()->set_renderer_initialized(true);
Alex Moshchuk27caae82017-09-11 23:11:182787 GetRenderViewHost()->DispatchRenderViewCreated();
naskob21fe4872015-02-24 14:15:562788 GetRenderManager()->current_frame_host()->SetRenderFrameCreated(true);
2789 }
naskof5940b9f2015-03-02 23:04:052790
lof84501da082016-05-23 21:22:542791 // Create the renderer process in advance if requested.
Lukasz Anforowicz3caa8372018-06-05 17:22:072792 if (params.desired_renderer_state ==
2793 CreateParams::kInitializeAndWarmupRendererProcess) {
lof84501da082016-05-23 21:22:542794 if (!GetRenderManager()->current_frame_host()->IsRenderFrameLive()) {
2795 GetRenderManager()->InitRenderView(GetRenderViewHost(), nullptr);
2796 }
2797 }
2798
naskof5940b9f2015-03-02 23:04:052799 // Ensure that observers are notified of the creation of this WebContents's
2800 // main RenderFrameHost. It must be done here for main frames, since the
2801 // NotifySwappedFromRenderManager expects view_ to already be created and that
2802 // happens after RenderFrameHostManager::Init.
2803 NotifySwappedFromRenderManager(
2804 nullptr, GetRenderManager()->current_frame_host(), true);
Albert J. Wonge76bf0b82019-09-27 07:47:062805
2806 // For WebContents that are never shown, do critical initialization here which
2807 // would normally only happen when the WebContents is shown.
2808 if (params.is_never_visible) {
2809 // This has just been created so there can only be one frame. Thus it is
2810 // safe to initialize the root.
2811 GetMainFrame()->Init();
2812 }
[email protected]d1198fd2012-08-13 22:50:192813}
2814
[email protected]7fff43e2013-05-21 20:21:102815void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl* web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:372816 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnWebContentsDestroyed");
2817
[email protected]7fff43e2013-05-21 20:21:102818 RemoveDestructionObserver(web_contents);
2819
[email protected]ceee8cd2013-03-08 04:59:512820 // Clear a pending contents that has been closed before being shown.
alexmosc2a8cec2016-05-23 22:19:532821 for (auto iter = pending_contents_.begin(); iter != pending_contents_.end();
[email protected]ceee8cd2013-03-08 04:59:512822 ++iter) {
Joel Hockey8c2011b22020-04-30 05:07:192823 if (iter->second.contents.get() != web_contents)
[email protected]ceee8cd2013-03-08 04:59:512824 continue;
erikchenbee5c9622018-04-27 19:30:252825
2826 // Someone else has deleted the WebContents. That should never happen!
2827 // TODO(erikchen): Fix semantics here. https://crbug.com/832879.
Joel Hockey8c2011b22020-04-30 05:07:192828 iter->second.contents.release();
[email protected]ceee8cd2013-03-08 04:59:512829 pending_contents_.erase(iter);
[email protected]ceee8cd2013-03-08 04:59:512830 return;
2831 }
2832 NOTREACHED();
[email protected]14392a52012-05-02 20:28:442833}
2834
[email protected]7fff43e2013-05-21 20:21:102835void WebContentsImpl::AddDestructionObserver(WebContentsImpl* web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:372836 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
2837 "WebContentsImpl::AddDestructionObserver");
2838
Jan Wilken Dörrie73c901e2019-06-12 09:02:322839 if (!base::Contains(destruction_observers_, web_contents)) {
[email protected]7fff43e2013-05-21 20:21:102840 destruction_observers_[web_contents] =
Jeremy Roman04f27c372017-10-27 15:20:552841 std::make_unique<DestructionObserver>(this, web_contents);
[email protected]7fff43e2013-05-21 20:21:102842 }
2843}
2844
2845void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl* web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:372846 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
2847 "WebContentsImpl::RemoveDestructionObserver");
avia8cf81982016-08-12 20:28:462848 destruction_observers_.erase(web_contents);
[email protected]7fff43e2013-05-21 20:21:102849}
2850
[email protected]b172aee2012-04-10 17:05:262851void WebContentsImpl::AddObserver(WebContentsObserver* observer) {
Alexander Timin5fdeff22020-09-08 09:20:372852 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
2853 "WebContentsImpl::AddObserver");
[email protected]be1f56ab2011-12-22 06:55:312854 observers_.AddObserver(observer);
2855}
2856
[email protected]b172aee2012-04-10 17:05:262857void WebContentsImpl::RemoveObserver(WebContentsObserver* observer) {
Alexander Timin5fdeff22020-09-08 09:20:372858 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
2859 "WebContentsImpl::RemoveObserver");
[email protected]be1f56ab2011-12-22 06:55:312860 observers_.RemoveObserver(observer);
2861}
2862
[email protected]948481d2014-06-11 18:32:222863std::set<RenderWidgetHostView*>
2864WebContentsImpl::GetRenderWidgetHostViewsInTree() {
2865 std::set<RenderWidgetHostView*> set;
Carlos IL07f282f2020-05-15 22:58:292866 for (RenderFrameHost* rfh : GetAllFrames()) {
2867 if (RenderWidgetHostView* rwhv = static_cast<RenderFrameHostImpl*>(rfh)
2868 ->frame_tree_node()
2869 ->render_manager()
2870 ->GetRenderWidgetHostView()) {
lfgf949e0e2017-05-10 22:18:112871 set.insert(rwhv);
dchengafb53e22016-02-04 08:11:082872 }
[email protected]948481d2014-06-11 18:32:222873 }
[email protected]de3c5d82014-05-28 22:12:592874 return set;
2875}
2876
Adithya Srinivasane6e7f842019-12-16 18:41:362877std::set<RenderWidgetHostView*>
2878WebContentsImpl::GetRenderWidgetHostViewsInWebContentsTree() {
2879 std::set<RenderWidgetHostView*> result;
2880 GetRenderWidgetHostViewsInWebContentsTree(result);
2881 return result;
2882}
2883
2884void WebContentsImpl::GetRenderWidgetHostViewsInWebContentsTree(
2885 std::set<RenderWidgetHostView*>& result) {
2886 std::set<RenderWidgetHostView*> views = GetRenderWidgetHostViewsInTree();
2887 result.insert(views.begin(), views.end());
2888 for (auto* inner_web_contents : GetInnerWebContents()) {
2889 static_cast<WebContentsImpl*>(inner_web_contents)
2890 ->GetRenderWidgetHostViewsInWebContentsTree(result);
2891 }
2892}
2893
[email protected]b172aee2012-04-10 17:05:262894void WebContentsImpl::Activate() {
Alexander Timin5fdeff22020-09-08 09:20:372895 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Activate");
[email protected]d5f942ba2008-09-26 19:30:342896 if (delegate_)
2897 delegate_->ActivateContents(this);
2898}
2899
avi3e4b8512015-11-11 01:55:492900void WebContentsImpl::LostCapture(RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:372901 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::LostCapture",
2902 "render_widget_host", render_widget_host);
avi3e4b8512015-11-11 01:55:492903 if (!RenderViewHostImpl::From(render_widget_host))
2904 return;
2905
[email protected]63954792011-07-11 04:17:482906 if (delegate_)
2907 delegate_->LostCapture();
2908}
2909
Yue Ru Sun979c4b162019-11-06 16:11:042910ukm::SourceId
2911WebContentsImpl::GetUkmSourceIdForLastCommittedSourceIncludingSameDocument()
2912 const {
2913 return last_committed_source_id_including_same_document_;
2914}
2915
Ahmed Fakhryfaa32d22018-10-05 15:56:162916void WebContentsImpl::SetTopControlsShownRatio(
2917 RenderWidgetHostImpl* render_widget_host,
2918 float ratio) {
Alexander Timin5fdeff22020-09-08 09:20:372919 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetTopControlsShownRatio",
2920 "render_widget_host", render_widget_host, "ratio",
2921 ratio);
Ahmed Fakhryfaa32d22018-10-05 15:56:162922 if (!delegate_)
2923 return;
2924
2925 RenderFrameHostImpl* rfh = GetMainFrame();
2926 if (!rfh || render_widget_host != rfh->GetRenderWidgetHost())
2927 return;
2928
2929 delegate_->SetTopControlsShownRatio(this, ratio);
Ahmed Fakhry58e6ef542018-09-04 18:05:382930}
2931
Ahmed Fakhry58e6ef542018-09-04 18:05:382932void WebContentsImpl::SetTopControlsGestureScrollInProgress(bool in_progress) {
Alexander Timin5fdeff22020-09-08 09:20:372933 OPTIONAL_TRACE_EVENT1(
2934 "content", "WebContentsImpl::SetTopControlsGestureScrollInProgress",
2935 "in_progress", in_progress);
Ahmed Fakhry58e6ef542018-09-04 18:05:382936 if (delegate_)
2937 delegate_->SetTopControlsGestureScrollInProgress(in_progress);
2938}
2939
lazyboy63f5b312015-11-23 20:19:522940void WebContentsImpl::RenderWidgetCreated(
2941 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:372942 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderWidgetCreated",
2943 "render_widget_host", render_widget_host);
lazyboy63f5b312015-11-23 20:19:522944 created_widgets_.insert(render_widget_host);
2945}
2946
[email protected]b24b68a2012-09-24 21:57:262947void WebContentsImpl::RenderWidgetDeleted(
2948 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:372949 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderWidgetDeleted",
2950 "render_widget_host", render_widget_host);
lazyboy63f5b312015-11-23 20:19:522951 // Note that |is_being_destroyed_| can be true at this point as
2952 // ~WebContentsImpl() calls RFHM::ClearRFHsPendingShutdown(), which might lead
2953 // us here.
2954 created_widgets_.erase(render_widget_host);
[email protected]b24b68a2012-09-24 21:57:262955
lazyboy63f5b312015-11-23 20:19:522956 if (is_being_destroyed_)
2957 return;
[email protected]44470a22013-01-24 01:21:542958
lfg7d4caad2017-03-22 09:01:452959 if (render_widget_host == mouse_lock_widget_)
lfgff8dfc8d2016-10-21 17:42:322960 LostMouseLock(mouse_lock_widget_);
Joe Downing192998b22018-03-22 15:51:362961
Joe Downingc1a57efe2018-05-09 18:23:542962 CancelKeyboardLock(render_widget_host);
[email protected]b24b68a2012-09-24 21:57:262963}
2964
estaded0a0c992015-01-21 14:12:062965void WebContentsImpl::RenderWidgetWasResized(
rouslan2f5993f2015-01-29 00:18:312966 RenderWidgetHostImpl* render_widget_host,
2967 bool width_changed) {
Alexander Timin5fdeff22020-09-08 09:20:372968 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RenderWidgetWasResized",
2969 "render_widget_host", render_widget_host,
2970 "width_changed", width_changed);
creisc014b402015-04-23 16:41:452971 RenderFrameHostImpl* rfh = GetMainFrame();
estadece344ec2015-01-23 00:12:292972 if (!rfh || render_widget_host != rfh->GetRenderWidgetHost())
estaded0a0c992015-01-21 14:12:062973 return;
estaded0a0c992015-01-21 14:12:062974
Alexander Timin90c20c32020-08-12 15:28:322975 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2976 observer->MainFrameWasResized(width_changed);
2977 });
estaded0a0c992015-01-21 14:12:062978}
2979
skyf65d9bb2017-03-24 02:26:392980KeyboardEventProcessingResult WebContentsImpl::PreHandleKeyboardEvent(
2981 const NativeWebKeyboardEvent& event) {
Alexander Timin5fdeff22020-09-08 09:20:372982 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
2983 "WebContentsImpl::PreHandleKeyboardEvent");
W. James MacLeane1187272019-11-12 03:42:482984 auto* outermost_contents = GetOutermostWebContents();
2985 // TODO(wjmaclean): Generalize this to forward all key events to the outermost
2986 // delegate's handler.
Avi Drissman97aef042020-06-30 21:04:482987 if (outermost_contents != this && IsFullscreen() &&
W. James MacLeane1187272019-11-12 03:42:482988 event.windows_key_code == ui::VKEY_ESCAPE) {
2989 // When an inner WebContents has focus and is fullscreen, redirect <esc>
2990 // key events to the outermost WebContents so it can be handled by that
2991 // WebContents' delegate.
2992 if (outermost_contents->PreHandleKeyboardEvent(event) ==
2993 KeyboardEventProcessingResult::HANDLED) {
2994 return KeyboardEventProcessingResult::HANDLED;
2995 }
2996 }
skyf65d9bb2017-03-24 02:26:392997 return delegate_ ? delegate_->PreHandleKeyboardEvent(this, event)
2998 : KeyboardEventProcessingResult::NOT_HANDLED;
[email protected]63954792011-07-11 04:17:482999}
3000
Dave Tapuska344399e2019-09-09 15:18:263001bool WebContentsImpl::HandleMouseEvent(const blink::WebMouseEvent& event) {
Alexander Timin5fdeff22020-09-08 09:20:373002 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
3003 "WebContentsImpl::HandleMouseEvent");
Dave Tapuska344399e2019-09-09 15:18:263004 // Handle mouse button back/forward in the browser process after the render
3005 // process is done with the event. This ensures all renderer-initiated history
3006 // navigations can be treated consistently.
3007 if (event.GetType() == blink::WebInputEvent::Type::kMouseUp) {
3008 WebContentsImpl* outermost = GetOutermostWebContents();
3009 if (event.button == blink::WebPointerProperties::Button::kBack &&
3010 outermost->controller_.CanGoBack()) {
3011 outermost->controller_.GoBack();
3012 return true;
3013 } else if (event.button == blink::WebPointerProperties::Button::kForward &&
3014 outermost->controller_.CanGoForward()) {
3015 outermost->controller_.GoForward();
3016 return true;
3017 }
3018 }
3019 return false;
3020}
3021
Scott Violetd5caa872018-10-16 22:00:513022bool WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
Alexander Timin5fdeff22020-09-08 09:20:373023 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
3024 "WebContentsImpl::HandleKeyboardEvent");
[email protected]0b094002014-08-20 18:28:103025 if (browser_plugin_embedder_ &&
3026 browser_plugin_embedder_->HandleKeyboardEvent(event)) {
Scott Violetd5caa872018-10-16 22:00:513027 return true;
[email protected]0b094002014-08-20 18:28:103028 }
Scott Violetd5caa872018-10-16 22:00:513029 return delegate_ && delegate_->HandleKeyboardEvent(this, event);
[email protected]63954792011-07-11 04:17:483030}
3031
Alexander Timin5fdeff22020-09-08 09:20:373032bool WebContentsImpl::HandleWheelEvent(const blink::WebMouseWheelEvent& event) {
3033 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
3034 "WebContentsImpl::HandleWheelEvent");
Avi Drissman7c57be72020-07-29 20:09:463035#if !defined(OS_MAC)
lanweia93644f2015-01-21 22:00:333036 // On platforms other than Mac, control+mousewheel may change zoom. On Mac,
3037 // this isn't done for two reasons:
[email protected]bccc4472013-04-18 16:37:193038 // -the OS already has a gesture to do this through pinch-zoom
3039 // -if a user starts an inertial scroll, let's go, and presses control
3040 // (i.e. control+tab) then the OS's buffered scroll events will come in
3041 // with control key set which isn't what the user wants
Blink Reformat1c4d759e2017-04-09 16:34:543042 if (delegate_ && event.wheel_ticks_y &&
Ehsan Karamad0f83cb112018-09-06 22:07:363043 event.event_action == blink::WebMouseWheelEvent::EventAction::kPageZoom) {
w.shackleton49bcd392016-01-06 17:38:223044 // Count only integer cumulative scrolls as zoom events; this handles
3045 // smooth scroll and regular scroll device behavior.
Blink Reformat1c4d759e2017-04-09 16:34:543046 zoom_scroll_remainder_ += event.wheel_ticks_y;
w.shackleton49bcd392016-01-06 17:38:223047 int whole_zoom_scroll_remainder_ = std::lround(zoom_scroll_remainder_);
3048 zoom_scroll_remainder_ -= whole_zoom_scroll_remainder_;
3049 if (whole_zoom_scroll_remainder_ != 0) {
3050 delegate_->ContentsZoomChange(whole_zoom_scroll_remainder_ > 0);
3051 }
[email protected]fb3f066e2013-02-12 19:12:523052 return true;
3053 }
[email protected]bccc4472013-04-18 16:37:193054#endif
[email protected]fb3f066e2013-02-12 19:12:523055 return false;
3056}
3057
[email protected]04bce562014-01-30 05:34:543058bool WebContentsImpl::PreHandleGestureEvent(
3059 const blink::WebGestureEvent& event) {
Alexander Timin5fdeff22020-09-08 09:20:373060 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
3061 "WebContentsImpl::PreHandleGestureEvent");
[email protected]28042d32014-02-03 14:10:033062 return delegate_ && delegate_->PreHandleGestureEvent(this, event);
[email protected]04bce562014-01-30 05:34:543063}
3064
kenrb2a565f82015-09-02 20:24:593065RenderWidgetHostInputEventRouter* WebContentsImpl::GetInputEventRouter() {
wjmacleane31234f2015-12-14 17:20:453066 if (!is_being_destroyed_ && GetOuterWebContents())
3067 return GetOuterWebContents()->GetInputEventRouter();
3068
3069 if (!rwh_input_event_router_.get() && !is_being_destroyed_)
Fergal Daly55b6d722020-09-11 07:56:333070 rwh_input_event_router_ =
3071 std::make_unique<RenderWidgetHostInputEventRouter>();
kenrb2a565f82015-09-02 20:24:593072 return rwh_input_event_router_.get();
3073}
3074
alexmos3fcd0ca2015-10-23 18:18:333075void WebContentsImpl::ReplicatePageFocus(bool is_focused) {
Alexander Timin5fdeff22020-09-08 09:20:373076 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ReplicatePageFocus",
3077 "is_focused", is_focused);
alexmos3fcd0ca2015-10-23 18:18:333078 // Focus loss may occur while this WebContents is being destroyed. Don't
3079 // send the message in this case, as the main frame's RenderFrameHost and
3080 // other state has already been cleared.
3081 if (is_being_destroyed_)
3082 return;
3083
3084 frame_tree_.ReplicatePageFocus(is_focused);
3085}
3086
alexmosc4cbacb2015-11-21 01:29:223087RenderWidgetHostImpl* WebContentsImpl::GetFocusedRenderWidgetHost(
3088 RenderWidgetHostImpl* receiving_widget) {
alexmosc4cbacb2015-11-21 01:29:223089 // Events for widgets other than the main frame (e.g., popup menus) should be
3090 // forwarded directly to the widget they arrived on.
3091 if (receiving_widget != GetMainFrame()->GetRenderWidgetHost())
3092 return receiving_widget;
alexmosc4d183e2015-11-06 00:46:523093
paulmeyerfeafc2d2017-04-25 21:46:403094 // If the focused WebContents is a guest WebContents, then get the focused
3095 // frame in the embedder WebContents instead.
W. James MacLean13d834d2019-12-04 16:06:453096 FrameTreeNode* focused_frame =
3097 GetFocusedWebContents()->frame_tree_.GetFocusedFrame();
lfg1453e412017-04-11 00:48:503098
alexmosc4d183e2015-11-06 00:46:523099 if (!focused_frame)
alexmosc4cbacb2015-11-21 01:29:223100 return receiving_widget;
alexmosc4d183e2015-11-06 00:46:523101
alexmos732ca3a2015-12-08 02:01:023102 // The view may be null if a subframe's renderer process has crashed while
3103 // the subframe has focus. Drop the event in that case. Do not give
3104 // it to the main frame, so that the user doesn't unexpectedly type into the
3105 // wrong frame if a focused subframe renderer crashes while they type.
3106 RenderWidgetHostView* view = focused_frame->current_frame_host()->GetView();
3107 if (!view)
3108 return nullptr;
3109
3110 return RenderWidgetHostImpl::From(view->GetRenderWidgetHost());
alexmosc4d183e2015-11-06 00:46:523111}
3112
avallee9993fca2016-11-17 06:16:503113RenderWidgetHostImpl* WebContentsImpl::GetRenderWidgetHostWithPageFocus() {
lfg1453e412017-04-11 00:48:503114 WebContentsImpl* focused_web_contents = GetFocusedWebContents();
3115
lfg1453e412017-04-11 00:48:503116 return focused_web_contents->GetMainFrame()->GetRenderWidgetHost();
avallee9993fca2016-11-17 06:16:503117}
3118
Avi Drissmand1d25652020-03-06 21:28:583119bool WebContentsImpl::CanEnterFullscreenMode() {
Avi Drissman33972942020-06-19 14:16:013120 // It's possible that this WebContents was spawned while blocking UI was on
3121 // the screen, or that it was downstream from a WebContents when UI was
3122 // blocked. Therefore, disqualify it from fullscreen if it or any upstream
3123 // WebContents has an active blocker.
3124 auto openers = GetAllOpeningWebContents(this);
3125 return std::all_of(openers.begin(), openers.end(), [](auto* opener) {
3126 return opener->fullscreen_blocker_count_ == 0;
3127 });
Avi Drissmand1d25652020-03-06 21:28:583128}
3129
Dave Tapuska3ed44192018-05-01 18:53:303130void WebContentsImpl::EnterFullscreenMode(
Mike Wasserman4ca09792020-05-29 17:44:433131 RenderFrameHost* requesting_frame,
Dave Tapuskaa4189512019-10-15 20:27:343132 const blink::mojom::FullscreenOptions& options) {
Alexander Timin5fdeff22020-09-08 09:20:373133 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::EnterFullscreenMode");
Avi Drissmand1d25652020-03-06 21:28:583134 DCHECK(CanEnterFullscreenMode());
3135
Joe Downing13dd76b2018-04-09 18:32:153136 if (delegate_) {
Mike Wasserman4ca09792020-05-29 17:44:433137 delegate_->EnterFullscreenModeForTab(requesting_frame, options);
mlamouri7a78d6fd2015-01-17 13:23:533138
Joe Downing13dd76b2018-04-09 18:32:153139 if (keyboard_lock_widget_)
3140 delegate_->RequestKeyboardLock(this, esc_key_locked_);
3141 }
3142
Alexander Timin90c20c32020-08-12 15:28:323143 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3144 observer->DidToggleFullscreenModeForTab(IsFullscreen(), false);
3145 });
Avi Drissman33972942020-06-19 14:16:013146 FullscreenContentsSet(GetBrowserContext())->insert(this);
mlamouri7a78d6fd2015-01-17 13:23:533147}
3148
bokanece34a82016-01-28 19:49:463149void WebContentsImpl::ExitFullscreenMode(bool will_cause_resize) {
Alexander Timin5fdeff22020-09-08 09:20:373150 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ExitFullscreenMode",
3151 "will_cause_resize", will_cause_resize);
Joe Downing13dd76b2018-04-09 18:32:153152 if (delegate_) {
mlamouri7a78d6fd2015-01-17 13:23:533153 delegate_->ExitFullscreenModeForTab(this);
[email protected]657c8e02014-03-19 19:18:373154
Joe Downing13dd76b2018-04-09 18:32:153155 if (keyboard_lock_widget_)
3156 delegate_->CancelKeyboardLockRequest(this);
3157 }
3158
bokanece34a82016-01-28 19:49:463159 // The fullscreen state is communicated to the renderer through a resize
3160 // message. If the change in fullscreen state doesn't cause a view resize
3161 // then we must ensure web contents exit the fullscreen state by explicitly
3162 // sending a resize message. This is required for the situation of the browser
3163 // moving the view into a "browser fullscreen" state and then the contents
3164 // entering "tab fullscreen". Exiting the contents "tab fullscreen" then won't
3165 // have the side effect of the view resizing, hence the explicit call here is
3166 // required.
3167 if (!will_cause_resize) {
3168 if (RenderWidgetHostView* rwhv = GetRenderWidgetHostView()) {
3169 if (RenderWidgetHost* render_widget_host = rwhv->GetRenderWidgetHost())
Fady Samuel0b911822018-04-25 13:22:163170 render_widget_host->SynchronizeVisualProperties();
bokanece34a82016-01-28 19:49:463171 }
scheib3dcb6c932015-02-23 10:55:583172 }
3173
Arthur Sonzogni929d29f2018-09-17 14:19:443174 current_fullscreen_frame_ = nullptr;
Becca Hughese9e27952018-06-25 17:08:273175
Alexander Timin90c20c32020-08-12 15:28:323176 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3177 observer->DidToggleFullscreenModeForTab(IsFullscreen(), will_cause_resize);
3178 });
Becca Hughesd11d6502018-07-31 17:01:283179
3180 if (display_cutout_host_impl_)
3181 display_cutout_host_impl_->DidExitFullscreen();
Avi Drissman33972942020-06-19 14:16:013182
3183 FullscreenContentsSet(GetBrowserContext())->erase(this);
[email protected]8a5e0ca2011-08-25 06:30:473184}
3185
Becca Hughesfd5d8f892018-06-14 18:23:363186void WebContentsImpl::FullscreenStateChanged(RenderFrameHost* rfh,
3187 bool is_fullscreen) {
Alexander Timin5fdeff22020-09-08 09:20:373188 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::FullscreenStateChanged",
3189 "render_frame_host", rfh, "is_fullscreen",
3190 is_fullscreen);
Arthur Sonzogni929d29f2018-09-17 14:19:443191 RenderFrameHostImpl* frame = static_cast<RenderFrameHostImpl*>(rfh);
Becca Hughesfd5d8f892018-06-14 18:23:363192
3193 if (is_fullscreen) {
Jan Wilken Dörrie531be7ca2019-06-07 10:05:573194 if (!base::Contains(fullscreen_frames_, frame)) {
Arthur Sonzogni929d29f2018-09-17 14:19:443195 fullscreen_frames_.insert(frame);
3196 FullscreenFrameSetUpdated();
Becca Hughesfd5d8f892018-06-14 18:23:363197 }
Arthur Sonzogni929d29f2018-09-17 14:19:443198 return;
3199 }
Becca Hughesfd5d8f892018-06-14 18:23:363200
Arthur Sonzogni929d29f2018-09-17 14:19:443201 // If |frame| is no longer in fullscreen, remove it and any descendants.
3202 // See https://fullscreen.spec.whatwg.org.
Arthur Sonzogni969a794e2018-10-11 08:56:093203 size_t size_before_deletion = fullscreen_frames_.size();
3204 base::EraseIf(fullscreen_frames_, [&](RenderFrameHostImpl* current) {
3205 return (current == frame || current->IsDescendantOf(frame));
Arthur Sonzogni929d29f2018-09-17 14:19:443206 });
3207
Arthur Sonzogni969a794e2018-10-11 08:56:093208 if (size_before_deletion != fullscreen_frames_.size())
Arthur Sonzogni929d29f2018-09-17 14:19:443209 FullscreenFrameSetUpdated();
3210}
3211
3212void WebContentsImpl::FullscreenFrameSetUpdated() {
Alexander Timin5fdeff22020-09-08 09:20:373213 OPTIONAL_TRACE_EVENT0("content",
3214 "WebContentsImpl::FullscreenFrameSetUpdated");
Arthur Sonzogni929d29f2018-09-17 14:19:443215 if (fullscreen_frames_.empty()) {
3216 current_fullscreen_frame_ = nullptr;
3217 return;
Becca Hughesfd5d8f892018-06-14 18:23:363218 }
3219
Arthur Sonzogni929d29f2018-09-17 14:19:443220 // Find the current fullscreen frame and call the observers.
3221 // If frame A is fullscreen, then frame B goes into inner fullscreen, then B
3222 // exits fullscreen - that will result in A being fullscreen.
3223 RenderFrameHostImpl* new_fullscreen_frame = *std::max_element(
3224 fullscreen_frames_.begin(), fullscreen_frames_.end(), FrameCompareDepth);
Becca Hughesfd5d8f892018-06-14 18:23:363225
Arthur Sonzogni929d29f2018-09-17 14:19:443226 // If we have already notified observers about this frame then we should not
3227 // fire the observers again.
3228 if (new_fullscreen_frame == current_fullscreen_frame_)
3229 return;
3230 current_fullscreen_frame_ = new_fullscreen_frame;
Becca Hughesfd5d8f892018-06-14 18:23:363231
Alexander Timin90c20c32020-08-12 15:28:323232 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3233 observer->DidAcquireFullscreen(new_fullscreen_frame);
3234 });
Arthur Sonzogni929d29f2018-09-17 14:19:443235 if (display_cutout_host_impl_)
3236 display_cutout_host_impl_->DidAcquireFullscreen(new_fullscreen_frame);
Becca Hughesfd5d8f892018-06-14 18:23:363237}
3238
Collin Baker989e0882019-11-01 01:27:173239void WebContentsImpl::UpdateVisibilityAndNotifyPageAndView(
3240 Visibility new_visibility) {
Alexander Timin5fdeff22020-09-08 09:20:373241 OPTIONAL_TRACE_EVENT1("content",
3242 "WebContentsImpl::UpdateVisibilityAndNotifyPageAndView",
3243 "new_visibility", static_cast<int>(new_visibility));
Collin Baker989e0882019-11-01 01:27:173244 // Only hide the page if there are no entities capturing screenshots
Collin Bakerc5259962019-11-14 17:51:583245 // or video (e.g. mirroring). If there are, apply the correct state of
3246 // kHidden or kHiddenButPainting.
3247 PageVisibilityState page_visibility;
3248 if (new_visibility == Visibility::VISIBLE || visible_capturer_count_ > 0)
3249 page_visibility = PageVisibilityState::kVisible;
3250 else if (hidden_capturer_count_ > 0)
3251 page_visibility = PageVisibilityState::kHiddenButPainting;
3252 else
3253 page_visibility = PageVisibilityState::kHidden;
Fergal Daly6de62f52020-10-14 01:56:443254 // If there are entities in Picture-in-Picture mode, don't activate the
3255 // "disable rendering" optimization. A crashed frame might be covered by a sad
3256 // tab. See docs on SadTabHelper exactly when it is or isn't. Either way,
3257 // don't make it visible.
Collin Bakerc5259962019-11-14 17:51:583258 const bool view_is_visible =
Fergal Daly6de62f52020-10-14 01:56:443259 !IsCrashed() && (page_visibility != PageVisibilityState::kHidden ||
3260 HasPictureInPictureVideo());
Collin Baker989e0882019-11-01 01:27:173261
Collin Bakerc5259962019-11-14 17:51:583262 if (page_visibility != PageVisibilityState::kHidden) {
Dana Friedcf3bc8e2019-11-13 20:00:243263 // We cannot show a page or capture video unless there is a valid renderer
3264 // associated with this web contents. The navigation controller for this
3265 // page must be set to active (allowing navigation to complete, a renderer
3266 // and its associated views to be created, etc.) if any of these conditions
3267 // holds.
3268 //
3269 // Previously, it was possible for browser-side code to try to capture video
3270 // from a restored tab (for a variety of reasons, including the browser
3271 // creating preview thumbnails) and the tab would never actually load. By
Collin Bakerc5259962019-11-14 17:51:583272 // keying this behavior off of |page_visibility| instead of just
Dana Friedcf3bc8e2019-11-13 20:00:243273 // |new_visibility| we avoid this case. See crbug.com/1020782 for more
3274 // context.
3275 controller_.SetActive(true);
3276
3277 // This shows the Page before showing the individual RenderWidgets, as
3278 // RenderWidgets will work to produce compositor frames and handle input
3279 // as soon as they are shown. But the Page and other classes do not expect
3280 // to be producing frames when the Page is hidden. So we make sure the Page
3281 // is shown first.
Yuzu Saijo232076f2020-05-29 07:14:023282 for (auto* rvh : GetRenderViewHostsIncludingBackForwardCached()) {
3283 rvh->SetVisibility(page_visibility);
Yuzu Saijobe024af02020-05-11 07:35:563284 }
Collin Baker98457b52019-11-06 21:34:293285 }
Collin Baker989e0882019-11-01 01:27:173286
3287 // |GetRenderWidgetHostView()| can be null if the user middle clicks a link to
3288 // open a tab in the background, then closes the tab before selecting it.
3289 // This is because closing the tab calls WebContentsImpl::Destroy(), which
3290 // removes the |GetRenderViewHost()|; then when we actually destroy the
3291 // window, OnWindowPosChanged() notices and calls WasHidden() (which
3292 // calls us).
3293 if (auto* view = GetRenderWidgetHostView()) {
3294 if (view_is_visible) {
3295 view->Show();
Collin Baker989e0882019-11-01 01:27:173296 } else if (new_visibility == Visibility::HIDDEN) {
3297 view->Hide();
3298 } else {
3299 view->WasOccluded();
3300 }
3301 }
3302
Carlos IL07f282f2020-05-15 22:58:293303 SetVisibilityForChildViews(view_is_visible);
Collin Baker989e0882019-11-01 01:27:173304
3305 // Make sure to call SetVisibilityAndNotifyObservers(VISIBLE) before notifying
3306 // the CrossProcessFrameConnector.
3307 if (new_visibility == Visibility::VISIBLE) {
3308 last_active_time_ = base::TimeTicks::Now();
3309 SetVisibilityAndNotifyObservers(new_visibility);
3310 }
3311
Collin Bakerc5259962019-11-14 17:51:583312 if (page_visibility == PageVisibilityState::kHidden) {
Collin Baker989e0882019-11-01 01:27:173313 // Similar to when showing the page, we only hide the page after
3314 // hiding the individual RenderWidgets.
Yuzu Saijo232076f2020-05-29 07:14:023315 for (auto* rvh : GetRenderViewHostsIncludingBackForwardCached()) {
3316 rvh->SetVisibility(page_visibility);
Yuzu Saijobe024af02020-05-11 07:35:563317 }
3318
Collin Baker989e0882019-11-01 01:27:173319 } else {
3320 for (FrameTreeNode* node : frame_tree_.Nodes()) {
3321 RenderFrameProxyHost* parent = node->render_manager()->GetProxyToParent();
3322 if (!parent)
3323 continue;
3324
3325 parent->cross_process_frame_connector()->DelegateWasShown();
3326 }
3327 }
3328
3329 if (new_visibility != Visibility::VISIBLE)
3330 SetVisibilityAndNotifyObservers(new_visibility);
3331}
3332
Clark DuValla0e42992018-09-17 17:00:113333#if defined(OS_ANDROID)
3334void WebContentsImpl::UpdateUserGestureCarryoverInfo() {
Alexander Timin5fdeff22020-09-08 09:20:373335 OPTIONAL_TRACE_EVENT0("content",
3336 "WebContentsImpl::UpdateUserGestureCarryoverInfo");
Clark DuValla0e42992018-09-17 17:00:113337 if (delegate_)
3338 delegate_->UpdateUserGestureCarryoverInfo(this);
3339}
3340#endif
3341
Avi Drissman97aef042020-06-30 21:04:483342bool WebContentsImpl::IsFullscreen() {
[email protected]199bba6e2012-04-04 16:19:383343 return delegate_ ? delegate_->IsFullscreenForTabOrPending(this) : false;
[email protected]5d5f7af2011-10-01 01:38:123344}
3345
Malay Keshav87c42c02019-01-15 08:37:473346bool WebContentsImpl::ShouldShowStaleContentOnEviction() {
3347 return GetDelegate() && GetDelegate()->ShouldShowStaleContentOnEviction(this);
3348}
3349
danakj45d42452020-04-08 17:24:183350blink::mojom::DisplayMode WebContentsImpl::GetDisplayMode() const {
mikhail.pozdnyakovc0e251b2015-04-15 06:51:123351 return delegate_ ? delegate_->GetDisplayMode(this)
Eric Willigers052f0432019-10-04 04:06:573352 : blink::mojom::DisplayMode::kBrowser;
mikhail.pozdnyakovc0e251b2015-04-15 06:51:123353}
3354
avic3aa8422015-11-09 20:57:223355void WebContentsImpl::RequestToLockMouse(
3356 RenderWidgetHostImpl* render_widget_host,
3357 bool user_gesture,
lfgad8244352016-07-13 16:55:513358 bool last_unlocked_by_target,
3359 bool privileged) {
Alexander Timin5fdeff22020-09-08 09:20:373360 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RequestToLockMouse",
3361 "render_widget_host", render_widget_host, "privileged",
3362 privileged);
lfgf0cd46e2017-01-04 00:05:233363 for (WebContentsImpl* current = this; current;
3364 current = current->GetOuterWebContents()) {
3365 if (current->mouse_lock_widget_) {
James Hollyerd5c9de462020-03-10 19:02:453366 render_widget_host->GotResponseToLockMouseRequest(
3367 blink::mojom::PointerLockResult::kAlreadyLocked);
lfgf0cd46e2017-01-04 00:05:233368 return;
3369 }
[email protected]e9621112011-10-17 05:38:373370 }
avic3aa8422015-11-09 20:57:223371
lfgad8244352016-07-13 16:55:513372 if (privileged) {
lfgf0cd46e2017-01-04 00:05:233373 DCHECK(!GetOuterWebContents());
lfgad8244352016-07-13 16:55:513374 mouse_lock_widget_ = render_widget_host;
James Hollyerd5c9de462020-03-10 19:02:453375 render_widget_host->GotResponseToLockMouseRequest(
3376 blink::mojom::PointerLockResult::kSuccess);
lfgad8244352016-07-13 16:55:513377 return;
3378 }
3379
lfgbee1e0a2016-06-08 21:24:213380 bool widget_in_frame_tree = false;
3381 for (FrameTreeNode* node : frame_tree_.Nodes()) {
3382 if (node->current_frame_host()->GetRenderWidgetHost() ==
3383 render_widget_host) {
3384 widget_in_frame_tree = true;
3385 break;
3386 }
3387 }
3388
3389 if (widget_in_frame_tree && delegate_) {
lfgf0cd46e2017-01-04 00:05:233390 for (WebContentsImpl* current = this; current;
3391 current = current->GetOuterWebContents()) {
3392 current->mouse_lock_widget_ = render_widget_host;
3393 }
3394
avic3aa8422015-11-09 20:57:223395 delegate_->RequestToLockMouse(this, user_gesture, last_unlocked_by_target);
lfgbee1e0a2016-06-08 21:24:213396 } else {
James Hollyerd5c9de462020-03-10 19:02:453397 render_widget_host->GotResponseToLockMouseRequest(
3398 blink::mojom::PointerLockResult::kWrongDocument);
lfgbee1e0a2016-06-08 21:24:213399 }
[email protected]e9621112011-10-17 05:38:373400}
3401
avi3e4b8512015-11-11 01:55:493402void WebContentsImpl::LostMouseLock(RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:373403 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::LostMouseLock",
3404 "render_widget_host", render_widget_host);
lfgbee1e0a2016-06-08 21:24:213405 CHECK(mouse_lock_widget_);
lfgf0cd46e2017-01-04 00:05:233406
3407 if (mouse_lock_widget_->delegate()->GetAsWebContents() != this)
3408 return mouse_lock_widget_->delegate()->LostMouseLock(render_widget_host);
3409
lfgbee1e0a2016-06-08 21:24:213410 mouse_lock_widget_->SendMouseLockLost();
lfgf0cd46e2017-01-04 00:05:233411 for (WebContentsImpl* current = this; current;
3412 current = current->GetOuterWebContents()) {
3413 current->mouse_lock_widget_ = nullptr;
3414 }
avi3e4b8512015-11-11 01:55:493415
[email protected]e9621112011-10-17 05:38:373416 if (delegate_)
3417 delegate_->LostMouseLock();
3418}
3419
lfgad8244352016-07-13 16:55:513420bool WebContentsImpl::HasMouseLock(RenderWidgetHostImpl* render_widget_host) {
3421 // To verify if the mouse is locked, the mouse_lock_widget_ needs to be
3422 // assigned to the widget that requested the mouse lock, and the top-level
3423 // platform RenderWidgetHostView needs to hold the mouse lock from the OS.
Lucas Gadania0ea0172018-09-20 18:31:373424 auto* widget_host = GetTopLevelRenderWidgetHostView();
3425 return mouse_lock_widget_ == render_widget_host && widget_host &&
3426 widget_host->IsMouseLocked();
lfgad8244352016-07-13 16:55:513427}
3428
lfg84763c92017-02-16 18:55:153429RenderWidgetHostImpl* WebContentsImpl::GetMouseLockWidget() {
Lucas Gadania0ea0172018-09-20 18:31:373430 auto* widget_host = GetTopLevelRenderWidgetHostView();
Dave Tapuska406647a2020-10-21 00:55:573431 if (widget_host && widget_host->IsMouseLocked()) {
lfg84763c92017-02-16 18:55:153432 return mouse_lock_widget_;
Lucas Gadania0ea0172018-09-20 18:31:373433 }
lfg84763c92017-02-16 18:55:153434
3435 return nullptr;
3436}
3437
Joe Downing192998b22018-03-22 15:51:363438bool WebContentsImpl::RequestKeyboardLock(
Joe Downing13dd76b2018-04-09 18:32:153439 RenderWidgetHostImpl* render_widget_host,
3440 bool esc_key_locked) {
Alexander Timin5fdeff22020-09-08 09:20:373441 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RequestKeyboardLock",
3442 "render_widget_host", render_widget_host,
3443 "esc_key_locked", esc_key_locked);
Joe Downing192998b22018-03-22 15:51:363444 DCHECK(render_widget_host);
Joe Downing192998b22018-03-22 15:51:363445 if (render_widget_host->delegate()->GetAsWebContents() != this) {
3446 NOTREACHED();
3447 return false;
3448 }
3449
3450 // KeyboardLock is only supported when called by the top-level browsing
3451 // context and is not supported in embedded content scenarios.
3452 if (GetOuterWebContents())
3453 return false;
3454
Joe Downing13dd76b2018-04-09 18:32:153455 esc_key_locked_ = esc_key_locked;
Joe Downing192998b22018-03-22 15:51:363456 keyboard_lock_widget_ = render_widget_host;
3457
Joe Downing13dd76b2018-04-09 18:32:153458 if (delegate_)
3459 delegate_->RequestKeyboardLock(this, esc_key_locked_);
Joe Downing192998b22018-03-22 15:51:363460 return true;
3461}
3462
3463void WebContentsImpl::CancelKeyboardLock(
3464 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:373465 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::CancelKeyboardLockRequest",
3466 "render_widget_host", render_widget_host);
Joe Downing192998b22018-03-22 15:51:363467 if (!keyboard_lock_widget_ || render_widget_host != keyboard_lock_widget_)
3468 return;
3469
3470 RenderWidgetHostImpl* old_keyboard_lock_widget = keyboard_lock_widget_;
3471 keyboard_lock_widget_ = nullptr;
3472
Joe Downing13dd76b2018-04-09 18:32:153473 if (delegate_)
3474 delegate_->CancelKeyboardLockRequest(this);
3475
Joe Downing192998b22018-03-22 15:51:363476 old_keyboard_lock_widget->CancelKeyboardLock();
3477}
3478
3479RenderWidgetHostImpl* WebContentsImpl::GetKeyboardLockWidget() {
3480 return keyboard_lock_widget_;
3481}
3482
Dave Tapuskac3344362019-02-20 17:54:283483void WebContentsImpl::OnRenderFrameProxyVisibilityChanged(
3484 blink::mojom::FrameVisibility visibility) {
Alexander Timin5fdeff22020-09-08 09:20:373485 OPTIONAL_TRACE_EVENT1("content",
3486 "WebContentsImpl::OnRenderFrameProxyVisibilityChanged",
3487 "visibility", static_cast<int>(visibility));
Dave Tapuskac3344362019-02-20 17:54:283488 switch (visibility) {
3489 case blink::mojom::FrameVisibility::kRenderedInViewport:
3490 WasShown();
3491 break;
3492 case blink::mojom::FrameVisibility::kNotRendered:
3493 WasHidden();
3494 break;
3495 case blink::mojom::FrameVisibility::kRenderedOutOfViewport:
3496 WasOccluded();
3497 break;
3498 }
ekaramada4f42692016-02-11 19:48:373499}
3500
Albert J. Wong65fe64d2019-09-20 02:48:143501RenderFrameHostDelegate* WebContentsImpl::CreateNewWindow(
csharrison95f01e922017-04-24 18:52:353502 RenderFrameHost* opener,
rockot5c478a72016-09-28 23:14:183503 const mojom::CreateNewWindowParams& params,
Albert J. Wong65fe64d2019-09-20 02:48:143504 bool is_new_browsing_instance,
Sergey Kuznetsov32257a22019-02-11 20:26:503505 bool has_user_gesture,
[email protected]97714c82012-06-06 10:15:133506 SessionStorageNamespace* session_storage_namespace) {
Alexander Timin5fdeff22020-09-08 09:20:373507 TRACE_EVENT2("browser,content,navigation", "WebContentsImpl::CreateNewWindow",
3508 "opener", base::trace_event::ToTracedValue(opener), "params",
3509 base::trace_event::ToTracedValue(params));
csharrison95f01e922017-04-24 18:52:353510 DCHECK(opener);
nick5ae4d2d2017-01-06 01:18:353511
csharrison95f01e922017-04-24 18:52:353512 int render_process_id = opener->GetProcess()->GetID();
csharrison95f01e922017-04-24 18:52:353513
Albert J. Wong65fe64d2019-09-20 02:48:143514 SiteInstance* source_site_instance = opener->GetSiteInstance();
nick5ae4d2d2017-01-06 01:18:353515
Aaron Colwelleb219982020-01-16 02:17:273516 const GURL source_site_url = source_site_instance->GetSiteURL();
[email protected]fdac6ade2013-07-20 01:06:303517 const std::string& partition_id =
Aaron Colwelleb219982020-01-16 02:17:273518 GetContentClient()->browser()->GetStoragePartitionIdForSite(
3519 GetBrowserContext(), source_site_url);
3520 {
3521 StoragePartition* partition = BrowserContext::GetStoragePartitionForSite(
3522 GetBrowserContext(), source_site_url);
3523 DOMStorageContextWrapper* dom_storage_context =
3524 static_cast<DOMStorageContextWrapper*>(
3525 partition->GetDOMStorageContext());
3526 SessionStorageNamespaceImpl* session_storage_namespace_impl =
3527 static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace);
3528 CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context));
3529 }
[email protected]dd6730412013-08-14 15:03:373530
Albert J. Wong1ceccef92019-10-08 08:25:203531 if (delegate_ && delegate_->IsWebContentsCreationOverridden(
3532 source_site_instance, params.window_container_type,
3533 opener->GetLastCommittedURL(), params.frame_name,
3534 params.target_url)) {
3535 return static_cast<WebContentsImpl*>(delegate_->CreateCustomWebContents(
3536 opener, source_site_instance, is_new_browsing_instance,
3537 opener->GetLastCommittedURL(), params.frame_name, params.target_url,
3538 partition_id, session_storage_namespace));
[email protected]dd6730412013-08-14 15:03:373539 }
3540
danakj22b4e8b2019-08-01 23:14:393541 bool renderer_started_hidden =
3542 params.disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB;
3543
Aaron Colwelleb219982020-01-16 02:17:273544 // We usually create the new window in the same BrowsingInstance (group of
3545 // script-related windows), by passing in the current SiteInstance. However,
3546 // if the opener is being suppressed (in a non-guest), we do not provide
3547 // a SiteInstance which causes a new one to get created in its own
3548 // BrowsingInstance.
3549 bool is_guest = BrowserPluginGuest::IsGuest(this);
3550 scoped_refptr<SiteInstance> site_instance =
3551 params.opener_suppressed && !is_guest ? nullptr : source_site_instance;
3552
[email protected]dd6730412013-08-14 15:03:373553 // Create the new web contents. This will automatically create the new
3554 // WebContentsView. In the future, we may want to create the view separately.
[email protected]fc72bb12013-06-02 21:13:463555 CreateParams create_params(GetBrowserContext(), site_instance.get());
nasko48321ca32015-07-02 20:44:123556 create_params.main_frame_name = params.frame_name;
alexmos4cf2aa32015-07-15 23:40:433557 create_params.opener_render_process_id = render_process_id;
csharrison95f01e922017-04-24 18:52:353558 create_params.opener_render_frame_id = opener->GetRoutingID();
[email protected]50d326e2014-05-20 17:59:063559 create_params.opener_suppressed = params.opener_suppressed;
danakj22b4e8b2019-08-01 23:14:393560 create_params.initially_hidden = renderer_started_hidden;
arthursonzogni034bb9c2020-10-01 08:29:563561 create_params.initial_popup_url = params.target_url;
[email protected]50d326e2014-05-20 17:59:063562
Albert J. Wong65fe64d2019-09-20 02:48:143563 // Even though all codepaths leading here are in response to a renderer
3564 // tryng to open a new window, if the new window ends up in a different
3565 // browsing instance, then the RenderViewHost, RenderWidgetHost,
3566 // RenderFrameHost constellation is effectively browser initiated
3567 // the opener's process will not given the routing IDs for the new
3568 // objects.
3569 create_params.renderer_initiated_creation = !is_new_browsing_instance;
Albert J. Wong1ceccef92019-10-08 08:25:203570
Albert J. Wong65fe64d2019-09-20 02:48:143571 std::unique_ptr<WebContentsImpl> new_contents;
[email protected]c4538072013-03-18 02:17:553572 if (!is_guest) {
3573 create_params.context = view_->GetNativeView();
Albert J. Wong65fe64d2019-09-20 02:48:143574 new_contents = WebContentsImpl::Create(create_params);
3575 } else {
3576 new_contents = base::WrapUnique(static_cast<WebContentsImpl*>(
3577 GetBrowserPluginGuest()->CreateNewGuestWindow(create_params)));
[email protected]c4538072013-03-18 02:17:553578 }
Albert J. Wong65fe64d2019-09-20 02:48:143579 auto* new_contents_impl = new_contents.get();
danakje6c01622018-10-05 19:39:263580
3581 new_contents_impl->GetController().SetSessionStorageNamespace(
erikchenbee5c9622018-04-27 19:30:253582 partition_id, session_storage_namespace);
[email protected]d1198fd2012-08-13 22:50:193583
alexmos646fec02015-07-25 00:11:493584 // If the new frame has a name, make sure any SiteInstances that can find
3585 // this named frame have proxies for it. Must be called after
3586 // SetSessionStorageNamespace, since this calls CreateRenderView, which uses
3587 // GetSessionStorageNamespace.
3588 if (!params.frame_name.empty())
danakje6c01622018-10-05 19:39:263589 new_contents_impl->GetRenderManager()->CreateProxiesForNewNamedFrame();
alexmos646fec02015-07-25 00:11:493590
[email protected]c4538072013-03-18 02:17:553591 // Save the window for later if we're not suppressing the opener (since it
[email protected]d70bea92013-04-05 04:23:343592 // will be shown immediately).
3593 if (!params.opener_suppressed) {
3594 if (!is_guest) {
danakje6c01622018-10-05 19:39:263595 WebContentsView* new_view = new_contents_impl->view_.get();
[email protected]bafe6cd2012-05-23 23:09:503596
[email protected]d70bea92013-04-05 04:23:343597 // TODO(brettw): It seems bogus that we have to call this function on the
3598 // newly created object and give it one of its own member variables.
danakj22b4e8b2019-08-01 23:14:393599 RenderWidgetHostView* widget_view = new_view->CreateViewForWidget(
W. James MacLean13d834d2019-12-04 16:06:453600 new_contents_impl->GetRenderViewHost()->GetWidget());
danakj22b4e8b2019-08-01 23:14:393601 if (!renderer_started_hidden) {
3602 // RenderWidgets for frames always initialize as hidden. If the renderer
3603 // created this window as visible, then we show it here.
3604 widget_view->Show();
3605 }
[email protected]d70bea92013-04-05 04:23:343606 }
[email protected]bafe6cd2012-05-23 23:09:503607 // Save the created window associated with the route so we can show it
3608 // later.
Albert J. Wongcb004632018-07-10 22:58:253609 //
3610 // TODO(ajwong): This should be keyed off the RenderFrame routing id or the
3611 // FrameTreeNode id instead of the routing id of the Widget for the main
3612 // frame. https://crbug.com/545684
Fergal Daly052873a82020-03-11 14:45:493613 int32_t main_frame_routing_id = new_contents_impl->GetMainFrame()
3614 ->GetRenderWidgetHost()
3615 ->GetRoutingID();
3616 GlobalRoutingID id(render_process_id, main_frame_routing_id);
Joel Hockey8c2011b22020-04-30 05:07:193617 pending_contents_[id] =
3618 CreatedWindow(std::move(new_contents), params.target_url);
danakje6c01622018-10-05 19:39:263619 AddDestructionObserver(new_contents_impl);
[email protected]bafe6cd2012-05-23 23:09:503620 }
3621
3622 if (delegate_) {
Bryan McQuaded2b93c02017-07-14 22:26:313623 delegate_->WebContentsCreated(this, render_process_id,
3624 opener->GetRoutingID(), params.frame_name,
danakje6c01622018-10-05 19:39:263625 params.target_url, new_contents_impl);
[email protected]bafe6cd2012-05-23 23:09:503626 }
3627
Alexander Timin90c20c32020-08-12 15:28:323628 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3629 observer->DidOpenRequestedURL(new_contents_impl, opener, params.target_url,
3630 params.referrer.To<Referrer>(),
3631 params.disposition, ui::PAGE_TRANSITION_LINK,
3632 false, // started_from_context_menu
3633 true); // renderer_initiated
3634 });
pnolandaae574e2017-03-06 21:04:213635
[email protected]bafe6cd2012-05-23 23:09:503636 if (params.opener_suppressed) {
3637 // When the opener is suppressed, the original renderer cannot access the
3638 // new window. As a result, we need to show and navigate the window here.
[email protected]eda238a12012-09-07 23:44:003639 bool was_blocked = false;
erikchenbee5c9622018-04-27 19:30:253640
[email protected]eda238a12012-09-07 23:44:003641 if (delegate_) {
danakje6c01622018-10-05 19:39:263642 base::WeakPtr<WebContentsImpl> weak_new_contents =
3643 new_contents_impl->weak_factory_.GetWeakPtr();
nick0d558482017-02-13 22:27:223644
danakje6c01622018-10-05 19:39:263645 gfx::Rect initial_rect; // Report an empty initial rect.
Albert J. Wong65fe64d2019-09-20 02:48:143646 delegate_->AddNewContents(this, std::move(new_contents),
Joel Hockey891e88062020-04-30 05:38:443647 params.target_url, params.disposition,
3648 initial_rect, has_user_gesture, &was_blocked);
danakje6c01622018-10-05 19:39:263649 // The delegate may delete |new_contents_impl| during AddNewContents().
nick0d558482017-02-13 22:27:223650 if (!weak_new_contents)
Albert J. Wong65fe64d2019-09-20 02:48:143651 return nullptr;
[email protected]eda238a12012-09-07 23:44:003652 }
erikchenbee5c9622018-04-27 19:30:253653
[email protected]eda238a12012-09-07 23:44:003654 if (!was_blocked) {
Nasko Oskov83a8cf92018-10-19 14:58:563655 std::unique_ptr<NavigationController::LoadURLParams> load_params =
3656 std::make_unique<NavigationController::LoadURLParams>(
3657 params.target_url);
Nasko Oskov93e7c55c2018-12-19 01:59:293658 load_params->initiator_origin = opener->GetLastCommittedOrigin();
Lukasz Anforowiczd2629b42020-08-11 16:07:313659 // Avoiding setting |load_params->source_site_instance| when
3660 // |opener_suppressed| is true, because in that case we do not want to use
3661 // the old SiteInstance and/or BrowsingInstance. See also the test here:
3662 // NewPopupCOOP_SameOriginPolicyAndCrossOriginIframeSetsNoopener.
Leon Han963dc182018-11-06 05:41:483663 load_params->referrer = params.referrer.To<Referrer>();
Nasko Oskov83a8cf92018-10-19 14:58:563664 load_params->transition_type = ui::PAGE_TRANSITION_LINK;
3665 load_params->is_renderer_initiated = true;
Sergey Kuznetsov32257a22019-02-11 20:26:503666 load_params->has_user_gesture = has_user_gesture;
mariakhomenkoa4971c12015-07-21 19:04:373667
3668 if (delegate_ && !is_guest &&
3669 !delegate_->ShouldResumeRequestsForCreatedWindow()) {
Nasko Oskov83a8cf92018-10-19 14:58:563670 // We are in asynchronous add new contents path, delay navigation.
3671 DCHECK(!new_contents_impl->delayed_open_url_params_);
3672 new_contents_impl->delayed_load_url_params_ = std::move(load_params);
mariakhomenkoa4971c12015-07-21 19:04:373673 } else {
Nasko Oskov83a8cf92018-10-19 14:58:563674 new_contents_impl->controller_.LoadURLWithParams(*load_params.get());
Nasko Oskov28ebd5b2018-12-07 22:29:333675 if (!is_guest)
3676 new_contents_impl->Focus();
mariakhomenkoa4971c12015-07-21 19:04:373677 }
[email protected]eda238a12012-09-07 23:44:003678 }
[email protected]bafe6cd2012-05-23 23:09:503679 }
Albert J. Wong65fe64d2019-09-20 02:48:143680 return new_contents_impl;
[email protected]bafe6cd2012-05-23 23:09:503681}
3682
Dave Tapuska04ccda062020-10-21 21:58:123683void WebContentsImpl::CreateNewPopupWidget(
Tal Pressman5dcd2382020-08-26 07:13:053684 AgentSchedulingGroupHost& agent_scheduling_group,
3685 int32_t route_id,
Dave Tapuska04ccda062020-10-21 21:58:123686 mojo::PendingAssociatedReceiver<blink::mojom::PopupWidgetHost>
3687 blink_popup_widget_host,
Dave Tapuska8499eec2020-03-16 17:54:303688 mojo::PendingAssociatedReceiver<blink::mojom::WidgetHost> blink_widget_host,
3689 mojo::PendingAssociatedRemote<blink::mojom::Widget> blink_widget) {
Alexander Timin5fdeff22020-09-08 09:20:373690 OPTIONAL_TRACE_EVENT1(
3691 "content", "WebContentsImpl::CreateNewWidget", "params",
Dave Tapuska04b305f92020-10-19 18:20:283692 base::trace_event::TracedValue::Build({{"route_id", route_id}}));
Tal Pressman5dcd2382020-08-26 07:13:053693 RenderProcessHost* process = agent_scheduling_group.GetProcess();
kenrbb46f86a2015-12-07 07:53:233694 // A message to create a new widget can only come from an active process for
[email protected]a8504022013-12-04 20:23:513695 // this WebContentsImpl instance. If any other process sends the request,
3696 // it is invalid and the process must be terminated.
Tal Pressman5dcd2382020-08-26 07:13:053697 if (!HasMatchingProcess(&frame_tree_, process->GetID())) {
Lukasz Anforowicz6f746282018-01-04 23:24:513698 ReceivedBadMessage(process, bad_message::WCI_NEW_WIDGET_PROCESS_MISMATCH);
[email protected]a8504022013-12-04 20:23:513699 return;
3700 }
3701
Tal Pressman5dcd2382020-08-26 07:13:053702 RenderWidgetHostImpl* widget_host = new RenderWidgetHostImpl(
3703 this, agent_scheduling_group, route_id, IsHidden(),
3704 std::make_unique<FrameTokenMessageQueue>());
Dave Tapuska8499eec2020-03-16 17:54:303705
3706 widget_host->BindWidgetInterfaces(std::move(blink_widget_host),
3707 std::move(blink_widget));
Dave Tapuska04ccda062020-10-21 21:58:123708 widget_host->BindPopupWidgetInterface(std::move(blink_popup_widget_host));
[email protected]cfd80b02014-05-01 17:46:483709 RenderWidgetHostViewBase* widget_view =
3710 static_cast<RenderWidgetHostViewBase*>(
danakj0b246942018-09-17 21:30:273711 view_->CreateViewForChildWidget(widget_host));
[email protected]83918ec2013-01-10 15:37:193712 if (!widget_view)
3713 return;
Dave Tapuska04b305f92020-10-19 18:20:283714 widget_view->SetWidgetType(WidgetType::kPopup);
[email protected]bafe6cd2012-05-23 23:09:503715 // Save the created widget associated with the route so we can show it later.
Tal Pressman5dcd2382020-08-26 07:13:053716 pending_widget_views_[GlobalRoutingID(process->GetID(), route_id)] =
alexmosc2a8cec2016-05-23 22:19:533717 widget_view;
[email protected]bafe6cd2012-05-23 23:09:503718}
3719
Mike Wassermandabad612020-08-13 04:26:273720void WebContentsImpl::ShowCreatedWindow(RenderFrameHost* opener,
nick5ae4d2d2017-01-06 01:18:353721 int main_frame_widget_route_id,
[email protected]bafe6cd2012-05-23 23:09:503722 WindowOpenDisposition disposition,
bokan107a47f2015-02-03 23:23:393723 const gfx::Rect& initial_rect,
[email protected]bafe6cd2012-05-23 23:09:503724 bool user_gesture) {
Alexander Timin5fdeff22020-09-08 09:20:373725 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::ShowCreatedWindow",
3726 "opener", base::trace_event::ToTracedValue(opener),
3727 "main_frame_widget_route_id",
3728 main_frame_widget_route_id);
danakje6c01622018-10-05 19:39:263729 // This method is the renderer requesting an existing top level window to
3730 // show a new top level window that the renderer created. Each top level
3731 // window is associated with a WebContents. In this case it was created
3732 // earlier but showing it was deferred until the renderer requested for it
3733 // to be shown. We find that previously created WebContents here.
3734 // TODO(danakj): Why do we defer this show step until the renderer asks for it
3735 // when it will always do so. What needs to happen in the renderer before we
3736 // reach here?
Mike Wassermandabad612020-08-13 04:26:273737 base::Optional<CreatedWindow> owned_created = GetCreatedWindow(
3738 opener->GetProcess()->GetID(), main_frame_widget_route_id);
Joel Hockey8c2011b22020-04-30 05:07:193739
danakje6c01622018-10-05 19:39:263740 // The browser may have rejected the request to make a new window, or the
3741 // renderer could be sending an invalid route id. Ignore the request then.
Joel Hockey8c2011b22020-04-30 05:07:193742 if (!owned_created || !owned_created->contents)
danakje6c01622018-10-05 19:39:263743 return;
mariakhomenko44bdc4732015-04-29 01:55:383744
Joel Hockey8c2011b22020-04-30 05:07:193745 WebContentsImpl* created = owned_created->contents.get();
3746
danakje6c01622018-10-05 19:39:263747 // This uses the delegate for the WebContents where the window was created
3748 // from, to control how to show the newly created window.
3749 WebContentsDelegate* delegate = GetDelegate();
nick5ae4d2d2017-01-06 01:18:353750
Mike Wassermanb6bc0152020-08-25 22:46:203751 // Individual members of |initial_rect| may be 0 to indicate that the
3752 // window.open() feature string did not specify a value. This code does not
3753 // have the ability to distinguish between an unspecified value and 0.
3754 // Assume that if any single value is non-zero, all values should be used.
3755 // TODO(crbug.com/897300): Plumb values as specified; set defaults here?
3756 gfx::Rect adjusted_rect = initial_rect;
3757 int64_t display_id = display::kInvalidDisplayId;
3758 if (adjusted_rect != gfx::Rect())
3759 display_id = AdjustRequestedWindowBounds(&adjusted_rect, opener);
3760
3761 // Drop fullscreen when opening a WebContents to prohibit deceptive behavior.
3762 // Only drop fullscreen on the specific destination display, if it is known.
3763 // This supports sites using cross-screen window placement capabilities to
3764 // retain fullscreen and open a window on another screen.
3765 ForSecurityDropFullscreen(display_id).RunAndReset();
3766
danakje6c01622018-10-05 19:39:263767 // The delegate can be null in tests, so we must check for it :(.
3768 if (delegate) {
3769 // Mark the web contents as pending resume, then immediately do
3770 // the resume if the delegate wants it.
3771 created->is_resume_pending_ = true;
3772 if (delegate->ShouldResumeRequestsForCreatedWindow())
3773 created->ResumeLoadingCreatedWebContents();
3774
3775 base::WeakPtr<WebContentsImpl> weak_created =
3776 created->weak_factory_.GetWeakPtr();
Joel Hockey8c2011b22020-04-30 05:07:193777 delegate->AddNewContents(this, std::move(owned_created->contents),
Joel Hockey891e88062020-04-30 05:38:443778 std::move(owned_created->target_url), disposition,
Mike Wassermandabad612020-08-13 04:26:273779 adjusted_rect, user_gesture, nullptr);
danakje6c01622018-10-05 19:39:263780 // The delegate may delete |created| during AddNewContents().
3781 if (!weak_created)
3782 return;
[email protected]eda238a12012-09-07 23:44:003783 }
danakje6c01622018-10-05 19:39:263784
3785 RenderWidgetHostImpl* rwh = created->GetMainFrame()->GetRenderWidgetHost();
3786 DCHECK_EQ(main_frame_widget_route_id, rwh->GetRoutingID());
3787 rwh->Send(new WidgetMsg_SetBounds_ACK(rwh->GetRoutingID()));
[email protected]bafe6cd2012-05-23 23:09:503788}
3789
alexmosc2a8cec2016-05-23 22:19:533790void WebContentsImpl::ShowCreatedWidget(int process_id,
Albert J. Wongf6e13ed2018-09-18 15:25:473791 int widget_route_id,
bokan107a47f2015-02-03 23:23:393792 const gfx::Rect& initial_rect) {
Alexander Timin5fdeff22020-09-08 09:20:373793 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::ShowCreatedWidget",
3794 "process_id", process_id, "widget_route_id",
3795 widget_route_id);
[email protected]cfd80b02014-05-01 17:46:483796 RenderWidgetHostViewBase* widget_host_view =
alexmosc2a8cec2016-05-23 22:19:533797 static_cast<RenderWidgetHostViewBase*>(
Dave Tapuska22cafa32020-10-06 11:56:053798 GetCreatedWidget(process_id, widget_route_id));
[email protected]bafe6cd2012-05-23 23:09:503799 if (!widget_host_view)
3800 return;
[email protected]cfd80b02014-05-01 17:46:483801
W. James MacLeanec4125c2019-09-27 18:56:003802 // GetOutermostWebContents() returns |this| if there are no outer WebContents.
W. James MacLean3c5f50462019-10-28 16:24:213803 auto* outer_web_contents = GetOuterWebContents();
3804 auto* outermost_web_contents = GetOutermostWebContents();
W. James MacLeanec4125c2019-09-27 18:56:003805 RenderWidgetHostView* view =
W. James MacLean3c5f50462019-10-28 16:24:213806 outermost_web_contents->GetRenderWidgetHostView();
3807 // It's not entirely obvious why we need the transform only in the case where
3808 // the outer webcontents is not the same as the outermost webcontents. It may
3809 // be due to the fact that oopifs that are children of the mainframe get
3810 // correct values for their screenrects, but deeper cross-process frames do
3811 // not. Hopefully this can be resolved with https://crbug.com/928825.
3812 // Handling these cases separately is needed for http://crbug.com/1015298.
3813 bool needs_transform = this != outermost_web_contents &&
3814 outermost_web_contents != outer_web_contents;
W. James MacLeanec4125c2019-09-27 18:56:003815
3816 gfx::Rect transformed_rect(initial_rect);
3817 RenderWidgetHostView* this_view = GetRenderWidgetHostView();
W. James MacLean3c5f50462019-10-28 16:24:213818 if (needs_transform) {
W. James MacLeanec4125c2019-09-27 18:56:003819 // We need to transform the coordinates of initial_rect.
3820 gfx::Point origin =
3821 this_view->TransformPointToRootCoordSpace(initial_rect.origin());
3822 gfx::Point bottom_right =
3823 this_view->TransformPointToRootCoordSpace(initial_rect.bottom_right());
3824 transformed_rect =
3825 gfx::Rect(origin.x(), origin.y(), bottom_right.x() - origin.x(),
3826 bottom_right.y() - origin.y());
[email protected]cfd80b02014-05-01 17:46:483827 }
3828
Dave Tapuska22cafa32020-10-06 11:56:053829 widget_host_view->InitAsPopup(view, transformed_rect);
[email protected]89054502012-06-03 10:29:243830
yiyixcb1fbc4f2018-03-16 19:54:083831 RenderWidgetHostImpl* render_widget_host_impl = widget_host_view->host();
[email protected]89054502012-06-03 10:29:243832 render_widget_host_impl->Init();
[email protected]bafe6cd2012-05-23 23:09:503833}
3834
Joel Hockey8c2011b22020-04-30 05:07:193835base::Optional<CreatedWindow> WebContentsImpl::GetCreatedWindow(
nick5ae4d2d2017-01-06 01:18:353836 int process_id,
3837 int main_frame_widget_route_id) {
Alexander Timin5fdeff22020-09-08 09:20:373838 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::GetCreatedWindow",
3839 "process_id", process_id, "main_frame_widget_route_id",
3840 main_frame_widget_route_id);
3841
Lukasz Anforowicz09060bdf72018-08-23 15:53:173842 auto key = GlobalRoutingID(process_id, main_frame_widget_route_id);
nick5ae4d2d2017-01-06 01:18:353843 auto iter = pending_contents_.find(key);
[email protected]bafe6cd2012-05-23 23:09:503844
3845 // Certain systems can block the creation of new windows. If we didn't succeed
3846 // in creating one, just return NULL.
alexmosc2a8cec2016-05-23 22:19:533847 if (iter == pending_contents_.end())
Joel Hockey8c2011b22020-04-30 05:07:193848 return base::nullopt;
[email protected]bafe6cd2012-05-23 23:09:503849
Joel Hockey8c2011b22020-04-30 05:07:193850 CreatedWindow result = std::move(iter->second);
3851 WebContentsImpl* new_contents = result.contents.get();
nick5ae4d2d2017-01-06 01:18:353852 pending_contents_.erase(key);
Joel Hockey8c2011b22020-04-30 05:07:193853 RemoveDestructionObserver(new_contents);
[email protected]bafe6cd2012-05-23 23:09:503854
[email protected]d70bea92013-04-05 04:23:343855 // Don't initialize the guest WebContents immediately.
Joel Hockey8c2011b22020-04-30 05:07:193856 if (BrowserPluginGuest::IsGuest(new_contents))
3857 return result;
[email protected]d70bea92013-04-05 04:23:343858
Lukasz Anforowicz5510ed652018-06-06 16:16:193859 if (!new_contents->GetMainFrame()->GetProcess()->IsInitializedAndNotDead() ||
nick5ae4d2d2017-01-06 01:18:353860 !new_contents->GetMainFrame()->GetView()) {
Joel Hockey8c2011b22020-04-30 05:07:193861 return base::nullopt;
nick5ae4d2d2017-01-06 01:18:353862 }
[email protected]bafe6cd2012-05-23 23:09:503863
Joel Hockey8c2011b22020-04-30 05:07:193864 return result;
[email protected]bafe6cd2012-05-23 23:09:503865}
3866
alexmosc2a8cec2016-05-23 22:19:533867RenderWidgetHostView* WebContentsImpl::GetCreatedWidget(int process_id,
3868 int route_id) {
Alexander Timin5fdeff22020-09-08 09:20:373869 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::GetCreatedWidget",
3870 "process_id", process_id, "route_id", route_id);
3871
Lukasz Anforowicz09060bdf72018-08-23 15:53:173872 auto iter = pending_widget_views_.find(GlobalRoutingID(process_id, route_id));
[email protected]bafe6cd2012-05-23 23:09:503873 if (iter == pending_widget_views_.end()) {
3874 DCHECK(false);
alexmosc2a8cec2016-05-23 22:19:533875 return nullptr;
[email protected]bafe6cd2012-05-23 23:09:503876 }
3877
3878 RenderWidgetHostView* widget_host_view = iter->second;
Lukasz Anforowicz09060bdf72018-08-23 15:53:173879 pending_widget_views_.erase(GlobalRoutingID(process_id, route_id));
[email protected]bafe6cd2012-05-23 23:09:503880
3881 RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
Lukasz Anforowicz5510ed652018-06-06 16:16:193882 if (!widget_host->GetProcess()->IsInitializedAndNotDead()) {
[email protected]bafe6cd2012-05-23 23:09:503883 // The view has gone away or the renderer crashed. Nothing to do.
alexmosc2a8cec2016-05-23 22:19:533884 return nullptr;
[email protected]bafe6cd2012-05-23 23:09:503885 }
3886
3887 return widget_host_view;
3888}
3889
[email protected]f13b4202012-06-12 23:53:233890void WebContentsImpl::RequestMediaAccessPermission(
[email protected]33662e52013-01-07 21:31:093891 const MediaStreamRequest& request,
Mark Pilgrim57499082018-06-12 12:38:303892 MediaResponseCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:373893 OPTIONAL_TRACE_EVENT2("content",
3894 "WebContentsImpl::RequestMediaAccessPermission",
3895 "render_process_id", request.render_process_id,
3896 "render_frame_id", request.render_frame_id);
3897
[email protected]d19b84b2014-03-14 11:52:373898 if (delegate_) {
Mark Pilgrim57499082018-06-12 12:38:303899 delegate_->RequestMediaAccessPermission(this, request, std::move(callback));
[email protected]d19b84b2014-03-14 11:52:373900 } else {
Antonio Gomes0d42960a2019-06-05 12:35:513901 std::move(callback).Run(
3902 blink::MediaStreamDevices(),
3903 blink::mojom::MediaStreamRequestResult::FAILED_DUE_TO_SHUTDOWN,
3904 std::unique_ptr<MediaStreamUI>());
[email protected]d19b84b2014-03-14 11:52:373905 }
[email protected]f13b4202012-06-12 23:53:233906}
3907
Chandan Padhia4b8bcb72017-09-12 16:41:043908bool WebContentsImpl::CheckMediaAccessPermission(
Raymes Khouryad7c24a12018-03-05 23:22:583909 RenderFrameHost* render_frame_host,
Chandan Padhia4b8bcb72017-09-12 16:41:043910 const url::Origin& security_origin,
Antonio Gomesc8b734b2019-06-05 18:22:163911 blink::mojom::MediaStreamType type) {
Alexander Timin5fdeff22020-09-08 09:20:373912 OPTIONAL_TRACE_EVENT2("content",
3913 "WebContentsImpl::CheckMediaAccessPermission",
3914 "render_frame_host", render_frame_host,
3915 "security_origin", security_origin.Serialize());
3916
Antonio Gomesc8b734b2019-06-05 18:22:163917 DCHECK(type == blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE ||
3918 type == blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE);
Chandan Padhia4b8bcb72017-09-12 16:41:043919 return delegate_ && delegate_->CheckMediaAccessPermission(
Raymes Khouryad7c24a12018-03-05 23:22:583920 render_frame_host, security_origin.GetURL(), type);
grunell657d4d82014-09-18 00:09:433921}
3922
Guido Urdaneta73fa6632019-01-14 18:46:263923std::string WebContentsImpl::GetDefaultMediaDeviceID(
Antonio Gomesc8b734b2019-06-05 18:22:163924 blink::mojom::MediaStreamType type) {
Alexander Timin5fdeff22020-09-08 09:20:373925 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::GetDefaultMediaDeviceID",
3926 "type", static_cast<int>(type));
3927
guidou8a440b842017-01-30 13:58:433928 if (!delegate_)
3929 return std::string();
3930 return delegate_->GetDefaultMediaDeviceID(this, type);
3931}
3932
[email protected]cc9200432013-07-23 23:02:403933SessionStorageNamespace* WebContentsImpl::GetSessionStorageNamespace(
3934 SiteInstance* instance) {
3935 return controller_.GetSessionStorageNamespace(instance);
3936}
3937
[email protected]6de7fc482014-06-06 10:46:443938SessionStorageNamespaceMap WebContentsImpl::GetSessionStorageNamespaceMap() {
3939 return controller_.GetSessionStorageNamespaceMap();
3940}
3941
[email protected]9b159a52013-10-03 17:24:553942FrameTree* WebContentsImpl::GetFrameTree() {
3943 return &frame_tree_;
3944}
3945
aelias5252baa2016-04-10 01:18:023946bool WebContentsImpl::IsOverridingUserAgent() {
3947 return GetController().GetVisibleEntry() &&
3948 GetController().GetVisibleEntry()->GetIsOverridingUserAgent();
3949}
3950
avi85ee8362016-10-08 02:09:083951bool WebContentsImpl::IsJavaScriptDialogShowing() const {
3952 return is_showing_javascript_dialog_;
3953}
3954
avic031d392017-03-03 03:09:423955bool WebContentsImpl::ShouldIgnoreUnresponsiveRenderer() {
Dominique Fauteux-Chapleau99244382020-07-08 20:37:003956 if (suppress_unresponsive_renderer_count_ > 0)
3957 return true;
3958
avic031d392017-03-03 03:09:423959 // Ignore unresponsive renderers if the debugger is attached to them since the
3960 // unresponsiveness might be a result of the renderer sitting on a breakpoint.
3961 //
David Bienvenu525f8a02019-02-15 02:02:423962#ifdef OS_WIN
3963 // Check if a windows debugger is attached to the renderer process.
3964 base::ProcessHandle process_handle =
3965 GetMainFrame()->GetProcess()->GetProcess().Handle();
3966 BOOL debugger_present = FALSE;
3967 if (CheckRemoteDebuggerPresent(process_handle, &debugger_present) &&
3968 debugger_present)
3969 return true;
3970#endif // OS_WIN
3971
avic031d392017-03-03 03:09:423972 // TODO(pfeldman): Fix this to only return true if the renderer is *actually*
3973 // sitting on a breakpoint. https://crbug.com/684202
3974 return DevToolsAgentHost::IsDebuggerAttached(this);
3975}
3976
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:413977ui::AXMode WebContentsImpl::GetAccessibilityMode() {
[email protected]95640212014-07-26 18:14:303978 return accessibility_mode_;
3979}
3980
Mario Sanchez Prada5d7f1ac2020-07-16 17:18:403981void WebContentsImpl::AXTreeIDForMainFrameHasChanged() {
Alexander Timin5fdeff22020-09-08 09:20:373982 OPTIONAL_TRACE_EVENT0("content",
3983 "WebContentsImpl::AXTreeIDForMainFrameHasChanged");
3984
Mario Sanchez Prada5d7f1ac2020-07-16 17:18:403985 RenderWidgetHostViewBase* rwhv =
3986 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
3987 if (rwhv)
3988 rwhv->SetMainFrameAXTreeID(GetMainFrame()->GetAXTreeID());
3989
Alexander Timin90c20c32020-08-12 15:28:323990 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3991 observer->AXTreeIDForMainFrameHasChanged();
3992 });
Mario Sanchez Prada5d7f1ac2020-07-16 17:18:403993}
3994
Dominic Mazzonia7b0edb22017-08-09 16:32:513995void WebContentsImpl::AccessibilityEventReceived(
Dominic Mazzoniccbaa9b2018-06-06 07:44:233996 const AXEventNotificationDetails& details) {
Alexander Timin5fdeff22020-09-08 09:20:373997 OPTIONAL_TRACE_EVENT0("content",
3998 "WebContentsImpl::AccessibilityEventReceived");
Alexander Timin90c20c32020-08-12 15:28:323999 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4000 observer->AccessibilityEventReceived(details);
4001 });
[email protected]31a71eaf2014-03-13 01:47:364002}
4003
dmazzoni2400c462016-08-23 15:07:134004void WebContentsImpl::AccessibilityLocationChangesReceived(
4005 const std::vector<AXLocationChangeNotificationDetails>& details) {
Alexander Timin5fdeff22020-09-08 09:20:374006 OPTIONAL_TRACE_EVENT0(
4007 "content", "WebContentsImpl::AccessibilityLocationChangesReceived");
Alexander Timin90c20c32020-08-12 15:28:324008 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4009 observer->AccessibilityLocationChangesReceived(details);
4010 });
dmazzoni2400c462016-08-23 15:07:134011}
4012
Alexander Surkov2ab51622020-09-02 12:01:424013std::string WebContentsImpl::DumpAccessibilityTree(
Abigail Kleinabb428332019-09-13 18:26:214014 bool internal,
Alexander Surkov90482882020-10-12 16:30:384015 std::vector<ui::AXPropertyFilter> property_filters) {
Alexander Timin5fdeff22020-09-08 09:20:374016 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DumpAccessibilityTree");
James Wallace-Leeeafc94cb92018-07-23 21:35:094017 auto* ax_mgr = GetOrCreateRootBrowserAccessibilityManager();
4018 DCHECK(ax_mgr);
Lei Zhangc98caa3822019-11-07 19:17:274019 return AccessibilityTreeFormatterBase::DumpAccessibilityTreeFromManager(
Abigail Kleinabb428332019-09-13 18:26:214020 ax_mgr, internal, property_filters);
James Wallace-Leeeafc94cb92018-07-23 21:35:094021}
4022
Abigail Kleinaa898742019-11-01 02:31:254023void WebContentsImpl::RecordAccessibilityEvents(
Abigail Kleinbb8304bd2020-05-18 21:44:184024 bool start_recording,
4025 base::Optional<AccessibilityEventCallback> callback) {
Alexander Timin5fdeff22020-09-08 09:20:374026 OPTIONAL_TRACE_EVENT0("content",
4027 "WebContentsImpl::RecordAccessibilityEvents");
Abigail Kleinbb8304bd2020-05-18 21:44:184028 // Only pass a callback to RecordAccessibilityEvents when starting to record.
4029 DCHECK_EQ(start_recording, callback.has_value());
4030 if (start_recording) {
Abigail Kleinaa898742019-11-01 02:31:254031 SetAccessibilityMode(ui::AXMode::kWebContents);
4032 auto* ax_mgr = GetOrCreateRootBrowserAccessibilityManager();
4033 DCHECK(ax_mgr);
4034 base::ProcessId pid = base::Process::Current().Pid();
Alexander Surkov97e969632020-09-29 02:30:054035 event_recorder_ = content::AccessibilityEventRecorder::Create(ax_mgr, pid);
Abigail Kleinbb8304bd2020-05-18 21:44:184036 event_recorder_->ListenToEvents(*callback);
Abigail Kleinaa898742019-11-01 02:31:254037 } else {
Abigail Kleinbb8304bd2020-05-18 21:44:184038 if (event_recorder_) {
4039 event_recorder_->FlushAsyncEvents();
4040 event_recorder_.reset(nullptr);
4041 }
Abigail Kleinaa898742019-11-01 02:31:254042 }
4043}
4044
Ke He7319dbe2017-11-09 05:54:444045device::mojom::GeolocationContext* WebContentsImpl::GetGeolocationContext() {
Alexander Timin5fdeff22020-09-08 09:20:374046 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GetGeolocationContext");
Ella Ge3e375b702020-06-05 15:57:164047 if (delegate_) {
4048 auto* installed_webapp_context =
4049 delegate_->GetInstalledWebappGeolocationContext();
4050 if (installed_webapp_context)
4051 return installed_webapp_context;
4052 }
4053
Ken Rockotce010f02019-12-12 23:32:324054 if (!geolocation_context_) {
4055 GetDeviceService().BindGeolocationContext(
4056 geolocation_context_.BindNewPipeAndPassReceiver());
4057 }
Conley Owens6894c4f2017-07-10 19:29:134058 return geolocation_context_.get();
blundellc57b93f2014-10-29 13:19:574059}
4060
ke.he98b761e2017-05-09 05:59:174061device::mojom::WakeLockContext* WebContentsImpl::GetWakeLockContext() {
blundelld8cd72b2017-03-28 07:18:384062 if (!wake_lock_context_host_)
Fergal Daly55b6d722020-09-11 07:56:334063 wake_lock_context_host_ = std::make_unique<WakeLockContextHost>(this);
blundelle75a8f92017-03-27 08:11:174064 return wake_lock_context_host_->GetWakeLockContext();
alogvinovf50445a2015-10-30 13:00:124065}
4066
blundellf5316fc2017-05-15 11:49:034067#if defined(OS_ANDROID)
Miyoung Shin59f39ff2019-09-17 07:23:204068void WebContentsImpl::GetNFC(
Reilly Grantafbe2242020-02-20 21:14:554069 RenderFrameHost* render_frame_host,
Miyoung Shin59f39ff2019-09-17 07:23:204070 mojo::PendingReceiver<device::mojom::NFC> receiver) {
Reilly Grantafbe2242020-02-20 21:14:554071 if (!nfc_host_)
4072 nfc_host_ = std::make_unique<NFCHost>(this);
4073 nfc_host_->GetNFC(render_frame_host, std::move(receiver));
blundellf5316fc2017-05-15 11:49:034074}
4075#endif
4076
Evan Stade5e750ad02017-08-07 21:59:274077void WebContentsImpl::SetNotWaitingForResponse() {
Alexander Timin5fdeff22020-09-08 09:20:374078 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetNotWaitingForResponse",
4079 "was_waiting_for_response", waiting_for_response_);
Evan Stade5e750ad02017-08-07 21:59:274080 if (waiting_for_response_ == false)
4081 return;
4082
4083 waiting_for_response_ = false;
Alexander Timin90c20c32020-08-12 15:28:324084 observers_.ForEachObserver(
4085 [&](WebContentsObserver* observer) { observer->DidReceiveResponse(); });
Bruce Dawsone1c5c842020-09-15 02:09:144086
4087 // LoadingStateChanged must be called last in case it triggers deletion of
4088 // |this| due to recursive message pumps.
4089 if (delegate_)
4090 delegate_->LoadingStateChanged(this, is_load_to_different_document_);
Evan Stade5e750ad02017-08-07 21:59:274091}
4092
lfgbb9c28a2016-03-01 03:19:494093void WebContentsImpl::SendScreenRects() {
Alexander Timin5fdeff22020-09-08 09:20:374094 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SendScreenRects");
kenrbc52e1b4e2016-03-20 01:03:374095 for (FrameTreeNode* node : frame_tree_.Nodes()) {
kenrb0e8dc202016-05-30 19:51:404096 if (node->current_frame_host()->is_local_root())
kenrbc52e1b4e2016-03-20 01:03:374097 node->current_frame_host()->GetRenderWidgetHost()->SendScreenRects();
4098 }
[email protected]32deec62013-05-15 23:55:044099}
4100
ekaramadadd882292016-06-08 15:22:564101TextInputManager* WebContentsImpl::GetTextInputManager() {
4102 if (GetOuterWebContents())
4103 return GetOuterWebContents()->GetTextInputManager();
4104
Ehsan Karamadc179dc02018-12-15 03:09:294105 if (!text_input_manager_ && !browser_plugin_guest_) {
Fergal Daly55b6d722020-09-11 07:56:334106 text_input_manager_ = std::make_unique<TextInputManager>(
Darren Shenca53d5f2018-05-15 04:56:014107 GetBrowserContext() &&
Fergal Daly55b6d722020-09-11 07:56:334108 !GetBrowserContext()->IsOffTheRecord() /* should_do_learning */);
Darren Shenca53d5f2018-05-15 04:56:014109 }
ekaramadadd882292016-06-08 15:22:564110
4111 return text_input_manager_.get();
4112}
4113
paulmeyer7f6f1d4f2016-11-15 00:00:274114bool WebContentsImpl::OnUpdateDragCursor() {
Alexander Timin5fdeff22020-09-08 09:20:374115 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnUpdateDragCursor");
Lei Zhang6410ec1a2019-01-31 21:38:584116 return browser_plugin_embedder_ &&
4117 browser_plugin_embedder_->OnUpdateDragCursor();
paulmeyer7f6f1d4f2016-11-15 00:00:274118}
4119
kenrb11f213a2017-03-24 18:12:064120bool WebContentsImpl::IsWidgetForMainFrame(
4121 RenderWidgetHostImpl* render_widget_host) {
4122 return render_widget_host == GetMainFrame()->GetRenderWidgetHost();
4123}
4124
[email protected]95640212014-07-26 18:14:304125BrowserAccessibilityManager*
Alexander Timin5fdeff22020-09-08 09:20:374126WebContentsImpl::GetRootBrowserAccessibilityManager() {
Carlos ILd51e7702020-05-07 18:51:394127 RenderFrameHostImpl* rfh = static_cast<RenderFrameHostImpl*>(GetMainFrame());
creisc014b402015-04-23 16:41:454128 return rfh ? rfh->browser_accessibility_manager() : nullptr;
[email protected]95640212014-07-26 18:14:304129}
4130
4131BrowserAccessibilityManager*
Alexander Timin5fdeff22020-09-08 09:20:374132WebContentsImpl::GetOrCreateRootBrowserAccessibilityManager() {
Carlos ILd51e7702020-05-07 18:51:394133 RenderFrameHostImpl* rfh = static_cast<RenderFrameHostImpl*>(GetMainFrame());
creisc014b402015-04-23 16:41:454134 return rfh ? rfh->GetOrCreateBrowserAccessibilityManager() : nullptr;
[email protected]95640212014-07-26 18:14:304135}
4136
Dave Tapuskab336b922017-07-06 19:24:054137void WebContentsImpl::ExecuteEditCommand(
4138 const std::string& command,
4139 const base::Optional<base::string16>& value) {
Alexander Timin5fdeff22020-09-08 09:20:374140 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ExecuteEditCommand");
Dave Tapuska58a099e2020-06-08 21:48:404141 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514142 if (!input_handler)
Dave Tapuskab336b922017-07-06 19:24:054143 return;
4144
Dave Tapuskae782bea2019-07-09 16:21:514145 input_handler->ExecuteEditCommand(command, value);
Dave Tapuskab336b922017-07-06 19:24:054146}
4147
mohsen7ab1ec16ec2015-07-02 18:26:234148void WebContentsImpl::MoveRangeSelectionExtent(const gfx::Point& extent) {
Alexander Timin5fdeff22020-09-08 09:20:374149 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MoveRangeSelectionExtent");
Dave Tapuska58a099e2020-06-08 21:48:404150 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514151 if (!input_handler)
mohsen7ab1ec16ec2015-07-02 18:26:234152 return;
4153
Dave Tapuskae782bea2019-07-09 16:21:514154 input_handler->MoveRangeSelectionExtent(extent);
mohsen7ab1ec16ec2015-07-02 18:26:234155}
4156
4157void WebContentsImpl::SelectRange(const gfx::Point& base,
4158 const gfx::Point& extent) {
Alexander Timin5fdeff22020-09-08 09:20:374159 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SelectRange");
Dave Tapuska58a099e2020-06-08 21:48:404160 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514161 if (!input_handler)
mohsen7ab1ec16ec2015-07-02 18:26:234162 return;
4163
Dave Tapuskae782bea2019-07-09 16:21:514164 input_handler->SelectRange(base, extent);
mohsen7ab1ec16ec2015-07-02 18:26:234165}
4166
Dave Tapuskab336b922017-07-06 19:24:054167void WebContentsImpl::MoveCaret(const gfx::Point& extent) {
Alexander Timin5fdeff22020-09-08 09:20:374168 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
4169 "WebContentsImpl::MoveCaret");
Dave Tapuska58a099e2020-06-08 21:48:404170 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514171 if (!input_handler)
Dave Tapuskab336b922017-07-06 19:24:054172 return;
4173
Dave Tapuskae782bea2019-07-09 16:21:514174 input_handler->MoveCaret(extent);
Dave Tapuskab336b922017-07-06 19:24:054175}
4176
Shimi Zhang37deeb22017-09-28 00:59:014177void WebContentsImpl::AdjustSelectionByCharacterOffset(
4178 int start_adjust,
4179 int end_adjust,
4180 bool show_selection_menu) {
Alexander Timin5fdeff22020-09-08 09:20:374181 OPTIONAL_TRACE_EVENT0("content",
4182 "WebContentsImpl::AdjustSelectionByCharacterOffset");
Dave Tapuska58a099e2020-06-08 21:48:404183 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514184 if (!input_handler)
aurimasab0319022015-07-10 21:57:384185 return;
4186
Shimi Zhang37deeb22017-09-28 00:59:014187 using blink::mojom::SelectionMenuBehavior;
Dave Tapuskae782bea2019-07-09 16:21:514188 input_handler->AdjustSelectionByCharacterOffset(
Shimi Zhang37deeb22017-09-28 00:59:014189 start_adjust, end_adjust,
4190 show_selection_menu ? SelectionMenuBehavior::kShow
4191 : SelectionMenuBehavior::kHide);
aurimasab0319022015-07-10 21:57:384192}
4193
[email protected]b172aee2012-04-10 17:05:264194void WebContentsImpl::UpdatePreferredSize(const gfx::Size& pref_size) {
Alexander Timin5fdeff22020-09-08 09:20:374195 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::UpdatePreferredSize");
[email protected]222f5822014-02-05 23:40:494196 const gfx::Size old_size = GetPreferredSize();
[email protected]bcd2815602012-01-14 18:17:234197 preferred_size_ = pref_size;
[email protected]222f5822014-02-05 23:40:494198 OnPreferredSizeChanged(old_size);
[email protected]0548c5352011-09-07 00:33:334199}
4200
avic3aa8422015-11-09 20:57:224201void WebContentsImpl::ResizeDueToAutoResize(
4202 RenderWidgetHostImpl* render_widget_host,
Fady Samuel97947112018-05-05 16:24:544203 const gfx::Size& new_size) {
Alexander Timin5fdeff22020-09-08 09:20:374204 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ResizeDueToAutoResize",
4205 "render_widget_host", render_widget_host);
avic3aa8422015-11-09 20:57:224206 if (render_widget_host != GetRenderViewHost()->GetWidget())
4207 return;
4208
[email protected]61e2b3cc2012-03-02 16:13:344209 if (delegate_)
4210 delegate_->ResizeDueToAutoResize(this, new_size);
4211}
4212
[email protected]b172aee2012-04-10 17:05:264213WebContents* WebContentsImpl::OpenURL(const OpenURLParams& params) {
Alexander Timin5fdeff22020-09-08 09:20:374214 TRACE_EVENT1("content", "WebContentsImpl::OpenURL", "url",
4215 base::trace_event::ValueToString(params.url));
Aaron Colwell9dab1652019-12-09 18:29:494216#if DCHECK_IS_ON()
4217 DCHECK(params.Valid());
4218#endif
4219
Bo Liu300c6052018-06-12 04:46:074220 if (!delegate_) {
4221 // Embedder can delay setting a delegate on new WebContents with
4222 // WebContentsDelegate::ShouldResumeRequestsForCreatedWindow. In the mean
4223 // time, navigations, including the initial one, that goes through OpenURL
4224 // should be delayed until embedder is ready to resume loading.
4225 delayed_open_url_params_ = std::make_unique<OpenURLParams>(params);
Nasko Oskov83a8cf92018-10-19 14:58:564226
4227 // If there was a navigation deferred when creating the window through
4228 // CreateNewWindow, drop it in favor of this navigation.
4229 delayed_load_url_params_.reset();
4230
Ivan Kotenkov2c0d2bb32017-11-01 15:41:284231 return nullptr;
Bo Liu300c6052018-06-12 04:46:074232 }
[email protected]00c37fc2011-08-02 00:22:504233
[email protected]e5d549d2011-12-28 01:29:204234 WebContents* new_contents = delegate_->OpenURLFromTab(this, params);
pnoland488944652017-02-22 18:58:544235
4236 RenderFrameHost* source_render_frame_host = RenderFrameHost::FromID(
4237 params.source_render_process_id, params.source_render_frame_id);
4238
4239 if (source_render_frame_host && params.source_site_instance) {
4240 CHECK_EQ(source_render_frame_host->GetSiteInstance(),
4241 params.source_site_instance.get());
4242 }
4243
4244 if (new_contents && source_render_frame_host && new_contents != this) {
Alexander Timin90c20c32020-08-12 15:28:324245 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4246 observer->DidOpenRequestedURL(
Lukasz Anforowicz48c9f872018-08-01 00:58:414247 new_contents, source_render_frame_host, params.url, params.referrer,
4248 params.disposition, params.transition,
4249 params.started_from_context_menu, params.is_renderer_initiated);
Alexander Timin90c20c32020-08-12 15:28:324250 });
pnoland488944652017-02-22 18:58:544251 }
4252
[email protected]e5d549d2011-12-28 01:29:204253 return new_contents;
[email protected]d5f942ba2008-09-26 19:30:344254}
4255
avi2b177592014-12-10 02:08:024256void WebContentsImpl::SetHistoryOffsetAndLength(int history_offset,
4257 int history_length) {
Alexander Timin5fdeff22020-09-08 09:20:374258 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetHistoryOffsetAndLength",
4259 "history_offset", history_offset, "history_length",
4260 history_length);
alexmos136fd6e62016-08-15 20:58:414261 SendPageMessage(new PageMsg_SetHistoryOffsetAndLength(
4262 MSG_ROUTING_NONE, history_offset, history_length));
avi2b177592014-12-10 02:08:024263}
4264
4265void WebContentsImpl::SetHistoryOffsetAndLengthForView(
4266 RenderViewHost* render_view_host,
4267 int history_offset,
4268 int history_length) {
Alexander Timin5fdeff22020-09-08 09:20:374269 OPTIONAL_TRACE_EVENT2(
4270 "content", "WebContentsImpl::SetHistoryOffsetAndLengthForView",
4271 "history_offset", history_offset, "history_length", history_length);
alexmos136fd6e62016-08-15 20:58:414272 render_view_host->Send(new PageMsg_SetHistoryOffsetAndLength(
avi2b177592014-12-10 02:08:024273 render_view_host->GetRoutingID(), history_offset, history_length));
[email protected]796931a92011-08-10 01:32:144274}
4275
arthursonzogni818c2642019-09-27 12:18:104276void WebContentsImpl::ReloadFocusedFrame() {
Alexander Timin5fdeff22020-09-08 09:20:374277 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ReloadFocusedFrame");
[email protected]1f3fc1d2014-04-03 14:50:174278 RenderFrameHost* focused_frame = GetFocusedFrame();
4279 if (!focused_frame)
4280 return;
4281
yilkal921048bd2019-10-09 23:51:044282 focused_frame->Reload();
[email protected]959be4c2014-04-08 15:01:334283}
4284
4285void WebContentsImpl::Undo() {
Alexander Timin5fdeff22020-09-08 09:20:374286 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Undo");
Dave Tapuska58a099e2020-06-08 21:48:404287 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514288 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334289 return;
4290
Dave Tapuskae782bea2019-07-09 16:21:514291 input_handler->Undo();
[email protected]959be4c2014-04-08 15:01:334292 RecordAction(base::UserMetricsAction("Undo"));
4293}
4294
4295void WebContentsImpl::Redo() {
Alexander Timin5fdeff22020-09-08 09:20:374296 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Redo");
Dave Tapuska58a099e2020-06-08 21:48:404297 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514298 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334299 return;
Dave Tapuskae782bea2019-07-09 16:21:514300
4301 input_handler->Redo();
[email protected]959be4c2014-04-08 15:01:334302 RecordAction(base::UserMetricsAction("Redo"));
4303}
4304
4305void WebContentsImpl::Cut() {
Alexander Timin5fdeff22020-09-08 09:20:374306 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Cut");
Dave Tapuska58a099e2020-06-08 21:48:404307 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514308 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334309 return;
4310
Dave Tapuskae782bea2019-07-09 16:21:514311 input_handler->Cut();
[email protected]959be4c2014-04-08 15:01:334312 RecordAction(base::UserMetricsAction("Cut"));
4313}
4314
4315void WebContentsImpl::Copy() {
Alexander Timin5fdeff22020-09-08 09:20:374316 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Copy");
Dave Tapuska58a099e2020-06-08 21:48:404317 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514318 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334319 return;
4320
Dave Tapuskae782bea2019-07-09 16:21:514321 input_handler->Copy();
[email protected]959be4c2014-04-08 15:01:334322 RecordAction(base::UserMetricsAction("Copy"));
4323}
4324
4325void WebContentsImpl::CopyToFindPboard() {
Alexander Timin5fdeff22020-09-08 09:20:374326 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::CopyToFindPboard");
Avi Drissman7c57be72020-07-29 20:09:464327#if defined(OS_MAC)
Dave Tapuska58a099e2020-06-08 21:48:404328 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514329 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334330 return;
4331
4332 // Windows/Linux don't have the concept of a find pasteboard.
Dave Tapuskae782bea2019-07-09 16:21:514333 input_handler->CopyToFindPboard();
[email protected]959be4c2014-04-08 15:01:334334 RecordAction(base::UserMetricsAction("CopyToFindPboard"));
4335#endif
4336}
4337
4338void WebContentsImpl::Paste() {
Alexander Timin5fdeff22020-09-08 09:20:374339 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Paste");
Dave Tapuska58a099e2020-06-08 21:48:404340 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514341 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334342 return;
4343
Dave Tapuskae782bea2019-07-09 16:21:514344 input_handler->Paste();
Alexander Timin90c20c32020-08-12 15:28:324345 observers_.ForEachObserver(
4346 [&](WebContentsObserver* observer) { observer->OnPaste(); });
[email protected]959be4c2014-04-08 15:01:334347 RecordAction(base::UserMetricsAction("Paste"));
4348}
4349
4350void WebContentsImpl::PasteAndMatchStyle() {
Alexander Timin5fdeff22020-09-08 09:20:374351 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::PasteAndMatchStyle");
Dave Tapuska58a099e2020-06-08 21:48:404352 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514353 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334354 return;
4355
Dave Tapuskae782bea2019-07-09 16:21:514356 input_handler->PasteAndMatchStyle();
Alexander Timin90c20c32020-08-12 15:28:324357 observers_.ForEachObserver(
4358 [&](WebContentsObserver* observer) { observer->OnPaste(); });
[email protected]959be4c2014-04-08 15:01:334359 RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
4360}
4361
4362void WebContentsImpl::Delete() {
Alexander Timin5fdeff22020-09-08 09:20:374363 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Delete");
Dave Tapuska58a099e2020-06-08 21:48:404364 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514365 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334366 return;
4367
Dave Tapuskae782bea2019-07-09 16:21:514368 input_handler->Delete();
[email protected]959be4c2014-04-08 15:01:334369 RecordAction(base::UserMetricsAction("DeleteSelection"));
4370}
4371
4372void WebContentsImpl::SelectAll() {
Alexander Timin5fdeff22020-09-08 09:20:374373 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SelectAll");
Dave Tapuska58a099e2020-06-08 21:48:404374 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514375 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334376 return;
4377
Dave Tapuskae782bea2019-07-09 16:21:514378 input_handler->SelectAll();
[email protected]959be4c2014-04-08 15:01:334379 RecordAction(base::UserMetricsAction("SelectAll"));
4380}
4381
yabinh351e7ec2017-03-10 02:43:244382void WebContentsImpl::CollapseSelection() {
Alexander Timin5fdeff22020-09-08 09:20:374383 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::CollapseSelection");
Dave Tapuska58a099e2020-06-08 21:48:404384 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514385 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334386 return;
4387
Dave Tapuskae782bea2019-07-09 16:21:514388 input_handler->CollapseSelection();
[email protected]1f3fc1d2014-04-03 14:50:174389}
4390
4391void WebContentsImpl::Replace(const base::string16& word) {
Alexander Timin5fdeff22020-09-08 09:20:374392 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Replace");
Dave Tapuska58a099e2020-06-08 21:48:404393 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514394 if (!input_handler)
[email protected]1f3fc1d2014-04-03 14:50:174395 return;
4396
Dave Tapuskae782bea2019-07-09 16:21:514397 input_handler->Replace(word);
[email protected]1f3fc1d2014-04-03 14:50:174398}
4399
4400void WebContentsImpl::ReplaceMisspelling(const base::string16& word) {
Alexander Timin5fdeff22020-09-08 09:20:374401 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ReplaceMisspelling");
Dave Tapuska58a099e2020-06-08 21:48:404402 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514403 if (!input_handler)
[email protected]1f3fc1d2014-04-03 14:50:174404 return;
4405
Dave Tapuskae782bea2019-07-09 16:21:514406 input_handler->ReplaceMisspelling(word);
[email protected]959be4c2014-04-08 15:01:334407}
4408
4409void WebContentsImpl::NotifyContextMenuClosed(
4410 const CustomContextMenuContext& context) {
Alexander Timin5fdeff22020-09-08 09:20:374411 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::NotifyContextMenuClosed");
[email protected]959be4c2014-04-08 15:01:334412 RenderFrameHost* focused_frame = GetFocusedFrame();
4413 if (!focused_frame)
4414 return;
4415
4416 focused_frame->Send(new FrameMsg_ContextMenuClosed(
4417 focused_frame->GetRoutingID(), context));
4418}
4419
4420void WebContentsImpl::ExecuteCustomContextMenuCommand(
4421 int action, const CustomContextMenuContext& context) {
Alexander Timin5fdeff22020-09-08 09:20:374422 OPTIONAL_TRACE_EVENT1("content",
4423 "WebContentsImpl::ExecuteCustomContextMenuCommand",
4424 "action", action);
[email protected]959be4c2014-04-08 15:01:334425 RenderFrameHost* focused_frame = GetFocusedFrame();
4426 if (!focused_frame)
4427 return;
4428
4429 focused_frame->Send(new FrameMsg_CustomContextMenuAction(
4430 focused_frame->GetRoutingID(), context, action));
[email protected]4fed3702014-04-01 09:08:004431}
4432
[email protected]fc2b46b2014-05-03 16:33:454433gfx::NativeView WebContentsImpl::GetNativeView() {
4434 return view_->GetNativeView();
4435}
4436
4437gfx::NativeView WebContentsImpl::GetContentNativeView() {
4438 return view_->GetContentNativeView();
4439}
4440
4441gfx::NativeWindow WebContentsImpl::GetTopLevelNativeWindow() {
4442 return view_->GetTopLevelNativeWindow();
4443}
4444
4445gfx::Rect WebContentsImpl::GetViewBounds() {
4446 return view_->GetViewBounds();
4447}
4448
4449gfx::Rect WebContentsImpl::GetContainerBounds() {
Jeremy Roman352239c2020-05-21 16:31:324450 return view_->GetContainerBounds();
[email protected]fc2b46b2014-05-03 16:33:454451}
4452
4453DropData* WebContentsImpl::GetDropData() {
4454 return view_->GetDropData();
4455}
4456
4457void WebContentsImpl::Focus() {
Alexander Timin5fdeff22020-09-08 09:20:374458 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Focus");
miu9e14e492014-10-25 02:39:044459 view_->Focus();
[email protected]fc2b46b2014-05-03 16:33:454460}
4461
4462void WebContentsImpl::SetInitialFocus() {
Alexander Timin5fdeff22020-09-08 09:20:374463 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetInitialFocus");
miu9e14e492014-10-25 02:39:044464 view_->SetInitialFocus();
[email protected]fc2b46b2014-05-03 16:33:454465}
4466
4467void WebContentsImpl::StoreFocus() {
Alexander Timin5fdeff22020-09-08 09:20:374468 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::StoreFocus");
miu9e14e492014-10-25 02:39:044469 view_->StoreFocus();
[email protected]fc2b46b2014-05-03 16:33:454470}
4471
4472void WebContentsImpl::RestoreFocus() {
Alexander Timin5fdeff22020-09-08 09:20:374473 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::RestoreFocus");
miu9e14e492014-10-25 02:39:044474 view_->RestoreFocus();
[email protected]fc2b46b2014-05-03 16:33:454475}
4476
[email protected]b172aee2012-04-10 17:05:264477void WebContentsImpl::FocusThroughTabTraversal(bool reverse) {
Alexander Timin5fdeff22020-09-08 09:20:374478 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::FocusThroughTabTraversal",
4479 "reverse", reverse);
Maxim Podgorodskiya926c4ff2017-11-20 02:06:394480 view_->FocusThroughTabTraversal(reverse);
[email protected]96d185d2009-04-24 03:28:544481}
4482
[email protected]b172aee2012-04-10 17:05:264483bool WebContentsImpl::IsSavable() {
[email protected]a53209b2012-01-20 16:48:164484 // WebKit creates Document object when MIME type is application/xhtml+xml,
4485 // so we also support this MIME type.
Yuzu Saijoc23e9b72020-06-25 07:21:274486 std::string mime_type = GetContentsMimeType();
4487 return mime_type == "text/html" || mime_type == "text/xml" ||
4488 mime_type == "application/xhtml+xml" || mime_type == "text/plain" ||
4489 mime_type == "text/css" ||
4490 blink::IsSupportedJavascriptMimeType(mime_type);
[email protected]a53209b2012-01-20 16:48:164491}
4492
[email protected]b172aee2012-04-10 17:05:264493void WebContentsImpl::OnSavePage() {
Alexander Timin5fdeff22020-09-08 09:20:374494 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnSavePage");
[email protected]c7dd2f62011-07-18 15:57:594495 // If we can not save the page, try to download it.
[email protected]a53209b2012-01-20 16:48:164496 if (!IsSavable()) {
Min Qinda0ed2062018-02-23 22:00:534497 download::RecordSavePackageEvent(
4498 download::SAVE_PACKAGE_DOWNLOAD_ON_NON_HTML);
nasko89ad7742015-03-05 22:14:194499 SaveFrame(GetLastCommittedURL(), Referrer());
[email protected]27678b2a2012-02-04 22:09:144500 return;
[email protected]c7dd2f62011-07-18 15:57:594501 }
4502
4503 Stop();
4504
4505 // Create the save package and possibly prompt the user for the name to save
4506 // the page as. The user prompt is an asynchronous operation that runs on
4507 // another thread.
4508 save_package_ = new SavePackage(this);
4509 save_package_->GetSaveInfo();
4510}
4511
4512// Used in automated testing to bypass prompting the user for file names.
4513// Instead, the names and paths are hard coded rather than running them through
4514// file name sanitation and extension / mime checking.
[email protected]2dec8ec2013-02-07 19:20:344515bool WebContentsImpl::SavePage(const base::FilePath& main_file,
4516 const base::FilePath& dir_path,
[email protected]8ff00d72012-10-23 19:12:214517 SavePageType save_type) {
Alexander Timin5fdeff22020-09-08 09:20:374518 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SavePage", "main_file",
4519 base::trace_event::ValueToString(main_file), "dir_path",
4520 base::trace_event::ValueToString(dir_path));
[email protected]c7dd2f62011-07-18 15:57:594521 // Stop the page from navigating.
4522 Stop();
4523
4524 save_package_ = new SavePackage(this, save_type, main_file, dir_path);
[email protected]8ff00d72012-10-23 19:12:214525 return save_package_->Init(SavePackageDownloadCreatedCallback());
[email protected]c7dd2f62011-07-18 15:57:594526}
4527
Alexander Timin5fdeff22020-09-08 09:20:374528void WebContentsImpl::SaveFrame(const GURL& url, const Referrer& referrer) {
4529 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SaveFrame");
Xing Liu10329bf2018-03-20 19:22:144530 SaveFrameWithHeaders(url, referrer, std::string(), base::string16());
kundaji6c7f9692015-03-09 18:00:374531}
4532
Xing Liu10329bf2018-03-20 19:22:144533void WebContentsImpl::SaveFrameWithHeaders(
4534 const GURL& url,
4535 const Referrer& referrer,
4536 const std::string& headers,
4537 const base::string16& suggested_filename) {
Alexander Timin5fdeff22020-09-08 09:20:374538 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SaveFrameWithHeaders",
4539 "url", base::trace_event::ValueToString(url), "headers",
4540 headers);
Lei Zhang13a42e42019-02-19 23:28:114541 // Check and see if the guest can handle this.
4542 if (delegate_) {
4543 WebContents* guest_web_contents = nullptr;
4544 if (browser_plugin_embedder_) {
4545 BrowserPluginGuest* guest = browser_plugin_embedder_->GetFullPageGuest();
4546 if (guest)
4547 guest_web_contents = guest->GetWebContents();
4548 } else if (browser_plugin_guest_) {
4549 guest_web_contents = this;
4550 }
4551
4552 if (guest_web_contents && delegate_->GuestSaveFrame(guest_web_contents))
4553 return;
4554 }
4555
nasko89ad7742015-03-05 22:14:194556 if (!GetLastCommittedURL().is_valid())
[email protected]3c71576ce2013-07-23 02:00:014557 return;
sammc92af61552014-11-19 23:27:404558 if (delegate_ && delegate_->SaveFrame(url, referrer))
4559 return;
4560
nasko89ad7742015-03-05 22:14:194561 // TODO(nasko): This check for main frame is incorrect and should be fixed
brettw760f7442016-05-23 21:19:224562 // by explicitly passing in which frame this method should target. This would
4563 // indicate whether it's the main frame, and also tell us the frame pointer
4564 // to use for routing.
nasko89ad7742015-03-05 22:14:194565 bool is_main_frame = (url == GetLastCommittedURL());
brettw760f7442016-05-23 21:19:224566 RenderFrameHost* frame_host = GetMainFrame();
[email protected]3c71576ce2013-07-23 02:00:014567
avib7348942015-12-25 20:57:104568 int64_t post_id = -1;
[email protected]3c71576ce2013-07-23 02:00:014569 if (is_main_frame) {
Lucas Furukawa Gadani5553a152019-01-08 18:55:574570 NavigationEntry* entry = controller_.GetLastCommittedEntry();
[email protected]3c71576ce2013-07-23 02:00:014571 if (entry)
4572 post_id = entry->GetPostID();
4573 }
Ramin Halavati24e21012017-07-10 12:56:064574 net::NetworkTrafficAnnotationTag traffic_annotation =
4575 net::DefineNetworkTrafficAnnotation("download_web_contents_frame", R"(
4576 semantics {
4577 sender: "Save Page Action"
4578 description:
4579 "Saves the given frame's URL to the local file system."
4580 trigger:
4581 "The user has triggered a save operation on the frame through a "
4582 "context menu or other mechanism."
4583 data: "None."
4584 destination: WEBSITE
4585 }
4586 policy {
Ramin Halavati3b979782017-07-21 11:40:264587 cookies_allowed: YES
Ramin Halavati24e21012017-07-10 12:56:064588 cookies_store: "user"
4589 setting:
4590 "This feature cannot be disabled by settings, but it's is only "
4591 "triggered by user request."
4592 policy_exception_justification: "Not implemented."
4593 })");
Min Qina904f3302018-02-13 23:33:344594 auto params = std::make_unique<download::DownloadUrlParameters>(
brettw760f7442016-05-23 21:19:224595 url, frame_host->GetProcess()->GetID(),
4596 frame_host->GetRenderViewHost()->GetRoutingID(),
Matt Menke0dcaebc32020-03-06 17:00:104597 frame_host->GetRoutingID(), traffic_annotation);
Min Qina904f3302018-02-13 23:33:344598 params->set_referrer(referrer.url);
4599 params->set_referrer_policy(
4600 Referrer::ReferrerPolicyForUrlRequest(referrer.policy));
[email protected]3c71576ce2013-07-23 02:00:014601 params->set_post_id(post_id);
[email protected]3c71576ce2013-07-23 02:00:014602 if (post_id >= 0)
4603 params->set_method("POST");
4604 params->set_prompt(true);
kundaji6c7f9692015-03-09 18:00:374605
4606 if (headers.empty()) {
4607 params->set_prefer_cache(true);
4608 } else {
Min Qina904f3302018-02-13 23:33:344609 for (download::DownloadUrlParameters::RequestHeadersNameValuePair
4610 key_value : ParseDownloadHeaders(headers)) {
Megan Jablonski2f6a4c52017-07-10 23:01:254611 params->add_request_header(key_value.first, key_value.second);
kundaji6c7f9692015-03-09 18:00:374612 }
4613 }
Xing Liu10329bf2018-03-20 19:22:144614 params->set_suggested_name(suggested_filename);
Min Qin0ca8e1ee2018-01-31 00:49:354615 params->set_download_source(download::DownloadSource::WEB_CONTENTS_API);
thestig859c78892017-05-15 21:17:064616 BrowserContext::GetDownloadManager(GetBrowserContext())
Ramin Halavati03efa732017-06-12 09:28:204617 ->DownloadUrl(std::move(params));
[email protected]3c71576ce2013-07-23 02:00:014618}
4619
[email protected]b172aee2012-04-10 17:05:264620void WebContentsImpl::GenerateMHTML(
dewittj6dc5747a2016-05-17 01:48:474621 const MHTMLGenerationParams& params,
Avi Drissman149b7832018-03-23 14:31:494622 base::OnceCallback<void(int64_t)> callback) {
Alexander Timin5fdeff22020-09-08 09:20:374623 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GenerateMHTML");
Angel Alvarez902496682019-08-27 22:58:424624 base::OnceCallback<void(const MHTMLGenerationResult&)> wrapper_callback =
4625 base::BindOnce(
4626 [](base::OnceCallback<void(int64_t)> size_callback,
4627 const MHTMLGenerationResult& result) {
4628 std::move(size_callback).Run(result.file_size);
4629 },
4630 std::move(callback));
4631 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, params,
4632 std::move(wrapper_callback));
4633}
4634
4635void WebContentsImpl::GenerateMHTMLWithResult(
4636 const MHTMLGenerationParams& params,
4637 MHTMLGenerationResult::GenerateMHTMLCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:374638 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GenerateMHTMLWithResult");
Avi Drissman149b7832018-03-23 14:31:494639 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, params,
4640 std::move(callback));
[email protected]aa4f3972012-03-01 18:12:124641}
4642
Tsuyoshi Horob0d8d902020-03-12 00:09:394643void WebContentsImpl::GenerateWebBundle(
4644 const base::FilePath& file_path,
4645 base::OnceCallback<void(uint64_t /* file_size */,
4646 data_decoder::mojom::WebBundlerError)> callback) {
Alexander Timin5fdeff22020-09-08 09:20:374647 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::GenerateWebBundle",
4648 "file_path",
4649 base::trace_event::ValueToString(file_path));
Tsuyoshi Horob0d8d902020-03-12 00:09:394650 SaveAsWebBundleJob::Start(this, file_path, std::move(callback));
4651}
4652
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414653const std::string& WebContentsImpl::GetContentsMimeType() {
Yuzu Saijoc23e9b72020-06-25 07:21:274654 return GetRenderViewHost()->contents_mime_type();
[email protected]0bfbf882011-12-22 18:19:274655}
4656
Mario Sanchez Prada0bd8b8c2020-10-21 17:49:234657blink::RendererPreferences* WebContentsImpl::GetMutableRendererPrefs() {
[email protected]0bfbf882011-12-22 18:19:274658 return &renderer_preferences_;
4659}
4660
[email protected]e35ccd52012-05-23 16:22:474661void WebContentsImpl::Close() {
Alexander Timin5fdeff22020-09-08 09:20:374662 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Close");
[email protected]e35ccd52012-05-23 16:22:474663 Close(GetRenderViewHost());
4664}
4665
Ella Ge80a52dce2017-11-15 18:01:524666void WebContentsImpl::DragSourceEndedAt(float client_x,
4667 float client_y,
4668 float screen_x,
4669 float screen_y,
Gyuyoung Kimbad7da7c7d2020-09-25 16:26:594670 blink::DragOperation operation,
Paul Meyer0c58c3712016-11-17 22:59:514671 RenderWidgetHost* source_rwh) {
Alexander Timin5fdeff22020-09-08 09:20:374672 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
4673 "WebContentsImpl::DragSourceEndedAt");
Lei Zhang6410ec1a2019-01-31 21:38:584674 if (browser_plugin_embedder_) {
W. James MacLean9437b5bf2019-12-06 17:33:444675 browser_plugin_embedder_->DragSourceEndedAt(client_x, client_y, screen_x,
4676 screen_y, operation);
Lei Zhang6410ec1a2019-01-31 21:38:584677 }
Paul Meyer0c58c3712016-11-17 22:59:514678 if (source_rwh) {
Ella Ge80a52dce2017-11-15 18:01:524679 source_rwh->DragSourceEndedAt(gfx::PointF(client_x, client_y),
4680 gfx::PointF(screen_x, screen_y), operation);
Paul Meyer0c58c3712016-11-17 22:59:514681 }
[email protected]cf200a562013-05-03 16:24:294682}
4683
jam73f892642016-09-11 06:04:064684void WebContentsImpl::LoadStateChanged(
Charles Harrison911fa062018-03-06 21:01:464685 const std::string& host,
jam73f892642016-09-11 06:04:064686 const net::LoadStateWithParam& load_state,
4687 uint64_t upload_position,
4688 uint64_t upload_size) {
Alexander Timin5fdeff22020-09-08 09:20:374689 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::LoadStateChanged", "host",
4690 host, "load_state", static_cast<int>(load_state.state));
Charles Harrison911fa062018-03-06 21:01:464691 base::string16 host16 = url_formatter::IDNToUnicode(host);
Elly Fong-Jonescad9c3d12018-01-31 17:26:104692 // Drop no-op updates.
4693 if (load_state_.state == load_state.state &&
4694 load_state_.param == load_state.param &&
4695 upload_position_ == upload_position && upload_size_ == upload_size &&
Charles Harrison911fa062018-03-06 21:01:464696 load_state_host_ == host16) {
Elly Fong-Jonescad9c3d12018-01-31 17:26:104697 return;
4698 }
jam73f892642016-09-11 06:04:064699 load_state_ = load_state;
4700 upload_position_ = upload_position;
4701 upload_size_ = upload_size;
Charles Harrison911fa062018-03-06 21:01:464702 load_state_host_ = host16;
jam73f892642016-09-11 06:04:064703 if (load_state_.state == net::LOAD_STATE_READING_RESPONSE)
4704 SetNotWaitingForResponse();
jam73f892642016-09-11 06:04:064705}
4706
Collin Baker989e0882019-11-01 01:27:174707void WebContentsImpl::SetVisibilityAndNotifyObservers(Visibility visibility) {
Alexander Timin5fdeff22020-09-08 09:20:374708 OPTIONAL_TRACE_EVENT1("content",
4709 "WebContentsImpl::SetVisibilityAndNotifyObservers",
4710 "visibility", static_cast<int>(visibility));
Francois Doraye6161152018-03-27 22:05:374711 const Visibility previous_visibility = visibility_;
4712 visibility_ = visibility;
4713
Francois Dorayfe4a1772018-02-17 04:17:094714 // Notify observers if the visibility changed or if WasShown() is being called
4715 // for the first time.
Francois Dorayfe4a1772018-02-17 04:17:094716 if (visibility != previous_visibility ||
4717 (visibility == Visibility::VISIBLE && !did_first_set_visible_)) {
Alexander Timin90c20c32020-08-12 15:28:324718 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4719 observer->OnVisibilityChanged(visibility);
4720 });
Francois Dorayfe4a1772018-02-17 04:17:094721 }
4722}
4723
Michael Thiessen896405db2017-07-20 17:52:324724void WebContentsImpl::NotifyWebContentsFocused(
4725 RenderWidgetHost* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:374726 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::NotifyWebContentsFocused",
4727 "render_widget_host", render_widget_host);
Alexander Timin90c20c32020-08-12 15:28:324728 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4729 observer->OnWebContentsFocused(render_widget_host);
4730 });
calamity7fe55ce2015-04-10 03:59:374731}
4732
Michael Thiessen896405db2017-07-20 17:52:324733void WebContentsImpl::NotifyWebContentsLostFocus(
4734 RenderWidgetHost* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:374735 OPTIONAL_TRACE_EVENT1("content",
4736 "WebContentsImpl::NotifyWebContentsLostFocus",
4737 "render_widget_host", render_widget_host);
Alexander Timin90c20c32020-08-12 15:28:324738 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4739 observer->OnWebContentsLostFocus(render_widget_host);
4740 });
zijiehe3bee08e22017-05-17 04:14:464741}
4742
Paul Meyer0c58c3712016-11-17 22:59:514743void WebContentsImpl::SystemDragEnded(RenderWidgetHost* source_rwh) {
Alexander Timin5fdeff22020-09-08 09:20:374744 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SystemDragEnded",
4745 "render_widget_host", source_rwh);
Paul Meyer0c58c3712016-11-17 22:59:514746 if (source_rwh)
4747 source_rwh->DragSourceSystemDragEnded();
Lei Zhang6410ec1a2019-01-31 21:38:584748 if (browser_plugin_embedder_)
[email protected]cf200a562013-05-03 16:24:294749 browser_plugin_embedder_->SystemDragEnded();
[email protected]7813bd72011-02-05 02:19:344750}
4751
[email protected]b172aee2012-04-10 17:05:264752void WebContentsImpl::SetClosedByUserGesture(bool value) {
Alexander Timin5fdeff22020-09-08 09:20:374753 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetClosedByUserGesture",
4754 "value", value);
[email protected]0bfbf882011-12-22 18:19:274755 closed_by_user_gesture_ = value;
4756}
4757
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414758bool WebContentsImpl::GetClosedByUserGesture() {
[email protected]0bfbf882011-12-22 18:19:274759 return closed_by_user_gesture_;
4760}
4761
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414762int WebContentsImpl::GetMinimumZoomPercent() {
[email protected]0bfbf882011-12-22 18:19:274763 return minimum_zoom_percent_;
4764}
4765
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414766int WebContentsImpl::GetMaximumZoomPercent() {
[email protected]0bfbf882011-12-22 18:19:274767 return maximum_zoom_percent_;
4768}
4769
Dave Tapuska8f7c3872020-02-07 01:16:384770void WebContentsImpl::SetPageScale(float scale_factor) {
Alexander Timin5fdeff22020-09-08 09:20:374771 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetPageScale",
4772 "scale_factor", scale_factor);
Dave Tapuska8f7c3872020-02-07 01:16:384773 GetMainFrame()->GetAssociatedLocalMainFrame()->SetScaleFactor(scale_factor);
ccameronb7c1d6c2015-03-09 17:08:244774}
4775
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414776gfx::Size WebContentsImpl::GetPreferredSize() {
Francois Doray24fc62c2017-12-11 17:27:334777 return IsBeingCaptured() ? preferred_size_for_capture_ : preferred_size_;
[email protected]bcd2815602012-01-14 18:17:234778}
4779
James Hollyerd5c9de462020-03-10 19:02:454780bool WebContentsImpl::GotResponseToLockMouseRequest(
4781 blink::mojom::PointerLockResult result) {
Alexander Timin5fdeff22020-09-08 09:20:374782 OPTIONAL_TRACE_EVENT0("content",
4783 "WebContentsImpl::GotResponseToLockMouseRequest");
lfgf0cd46e2017-01-04 00:05:234784 if (mouse_lock_widget_) {
4785 if (mouse_lock_widget_->delegate()->GetAsWebContents() != this) {
4786 return mouse_lock_widget_->delegate()
4787 ->GetAsWebContents()
James Hollyerd5c9de462020-03-10 19:02:454788 ->GotResponseToLockMouseRequest(result);
lfgf0cd46e2017-01-04 00:05:234789 }
lfgad8244352016-07-13 16:55:514790
James Hollyerd5c9de462020-03-10 19:02:454791 if (mouse_lock_widget_->GotResponseToLockMouseRequest(result))
lfgf0cd46e2017-01-04 00:05:234792 return true;
4793 }
4794
4795 for (WebContentsImpl* current = this; current;
4796 current = current->GetOuterWebContents()) {
4797 current->mouse_lock_widget_ = nullptr;
4798 }
4799
lfgbee1e0a2016-06-08 21:24:214800 return false;
[email protected]0bfbf882011-12-22 18:19:274801}
4802
James Hollyerd5c9de462020-03-10 19:02:454803void WebContentsImpl::GotLockMousePermissionResponse(bool allowed) {
4804 GotResponseToLockMouseRequest(
4805 allowed ? blink::mojom::PointerLockResult::kSuccess
4806 : blink::mojom::PointerLockResult::kPermissionDenied);
4807}
4808
Dave Tapuskab4998782020-10-08 17:22:474809void WebContentsImpl::DropMouseLockForTesting() {
4810 if (mouse_lock_widget_) {
4811 mouse_lock_widget_->RejectMouseLockOrUnlockIfNecessary(
4812 blink::mojom::PointerLockResult::kUnknownError);
4813 for (WebContentsImpl* current = this; current;
4814 current = current->GetOuterWebContents()) {
4815 current->mouse_lock_widget_ = nullptr;
4816 }
4817 }
4818}
4819
Joe Downing13dd76b2018-04-09 18:32:154820bool WebContentsImpl::GotResponseToKeyboardLockRequest(bool allowed) {
Alexander Timin5fdeff22020-09-08 09:20:374821 OPTIONAL_TRACE_EVENT1("content",
4822 "WebContentsImpl::GotResponseToKeyboardLockRequest",
4823 "allowed", allowed);
4824
Joe Downing13dd76b2018-04-09 18:32:154825 if (!keyboard_lock_widget_)
4826 return false;
4827
4828 if (keyboard_lock_widget_->delegate()->GetAsWebContents() != this) {
4829 NOTREACHED();
4830 return false;
4831 }
4832
4833 // KeyboardLock is only supported when called by the top-level browsing
4834 // context and is not supported in embedded content scenarios.
4835 if (GetOuterWebContents())
4836 return false;
4837
4838 keyboard_lock_widget_->GotResponseToKeyboardLockRequest(allowed);
4839 return true;
4840}
4841
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414842bool WebContentsImpl::HasOpener() {
Ivan Kotenkov2c0d2bb32017-11-01 15:41:284843 return GetOpener() != nullptr;
[email protected]a0358d72012-03-09 14:06:504844}
4845
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414846RenderFrameHostImpl* WebContentsImpl::GetOpener() {
alexmose201c7cd2015-06-10 17:14:214847 FrameTreeNode* opener_ftn = frame_tree_.root()->opener();
lukasza6f8ac622017-06-06 03:10:204848 return opener_ftn ? opener_ftn->current_frame_host() : nullptr;
jochen55ff3502014-12-18 20:52:574849}
4850
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414851bool WebContentsImpl::HasOriginalOpener() {
Ivan Kotenkov2c0d2bb32017-11-01 15:41:284852 return GetOriginalOpener() != nullptr;
jochen6004a362017-02-04 00:11:404853}
4854
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414855RenderFrameHostImpl* WebContentsImpl::GetOriginalOpener() {
jochen6004a362017-02-04 00:11:404856 FrameTreeNode* opener_ftn = frame_tree_.root()->original_opener();
lukasza6f8ac622017-06-06 03:10:204857 return opener_ftn ? opener_ftn->current_frame_host() : nullptr;
jochen6004a362017-02-04 00:11:404858}
4859
[email protected]cb805452013-05-22 15:16:214860void WebContentsImpl::DidChooseColorInColorChooser(SkColor color) {
Alexander Timin5fdeff22020-09-08 09:20:374861 OPTIONAL_TRACE_EVENT1("content",
4862 "WebContentsImpl::DidChooseColorInColorChooser",
4863 "color", color);
Joel Hockey85b379d2017-12-11 10:42:134864 color_chooser_->DidChooseColorInColorChooser(color);
[email protected]da8543762012-03-20 08:52:204865}
4866
[email protected]cb805452013-05-22 15:16:214867void WebContentsImpl::DidEndColorChooser() {
Alexander Timin5fdeff22020-09-08 09:20:374868 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidEndColorChooser");
Joel Hockey85b379d2017-12-11 10:42:134869 color_chooser_.reset();
[email protected]da8543762012-03-20 08:52:204870}
4871
halton.huoca2eabd2015-07-06 08:17:404872int WebContentsImpl::DownloadImage(
4873 const GURL& url,
4874 bool is_favicon,
Fredrik Söderquistb2b39eb92019-11-18 16:16:504875 uint32_t preferred_size,
halton.huoca2eabd2015-07-06 08:17:404876 uint32_t max_bitmap_size,
4877 bool bypass_cache,
Avi Drissmana5a52dd2018-03-27 03:39:024878 WebContents::ImageDownloadCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:374879 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DownloadImage", "url",
4880 base::trace_event::ValueToString(url));
Danyao Wanga78f3dd22020-03-05 05:31:274881 return DownloadImageInFrame(GlobalFrameRoutingId(), url, is_favicon,
4882 preferred_size, max_bitmap_size, bypass_cache,
4883 std::move(callback));
4884}
4885
4886int WebContentsImpl::DownloadImageInFrame(
4887 const GlobalFrameRoutingId& initiator_frame_routing_id,
4888 const GURL& url,
4889 bool is_favicon,
4890 uint32_t preferred_size,
4891 uint32_t max_bitmap_size,
4892 bool bypass_cache,
4893 WebContents::ImageDownloadCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:374894 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DownloadImageInFrame");
amistry9f01b772015-07-29 01:54:554895 DCHECK_CURRENTLY_ON(BrowserThread::UI);
halton.huoca2eabd2015-07-06 08:17:404896 static int next_image_download_id = 0;
Danyao Wanga78f3dd22020-03-05 05:31:274897
4898 RenderFrameHostImpl* initiator_frame =
4899 initiator_frame_routing_id.child_id
4900 ? RenderFrameHostImpl::FromID(initiator_frame_routing_id)
4901 : GetMainFrame();
Julie Jeongeun Kimb1473572019-08-15 05:59:134902 const mojo::Remote<blink::mojom::ImageDownloader>& mojo_image_downloader =
Danyao Wanga78f3dd22020-03-05 05:31:274903 initiator_frame->GetMojoImageDownloader();
amistry9f01b772015-07-29 01:54:554904 const int download_id = ++next_image_download_id;
4905 if (!mojo_image_downloader) {
4906 // If the renderer process is dead (i.e. crash, or memory pressure on
4907 // Android), the downloader service will be invalid. Pre-Mojo, this would
Avi Drissmana5a52dd2018-03-27 03:39:024908 // hang the callback indefinitely since the IPC would be dropped. Now,
amistry9f01b772015-07-29 01:54:554909 // respond with a 400 HTTP error code to indicate that something went wrong.
Gabriel Charettee7cdc5cd2020-05-27 23:35:054910 GetUIThreadTaskRunner({})->PostTask(
4911 FROM_HERE,
tzike2aca992017-09-05 08:50:544912 base::BindOnce(&WebContentsImpl::OnDidDownloadImage,
Avi Drissmana5a52dd2018-03-27 03:39:024913 weak_factory_.GetWeakPtr(), std::move(callback),
4914 download_id, url, 400, std::vector<SkBitmap>(),
4915 std::vector<gfx::Size>()));
amistry9f01b772015-07-29 01:54:554916 return download_id;
4917 }
4918
halton.huoca2eabd2015-07-06 08:17:404919 mojo_image_downloader->DownloadImage(
Fredrik Söderquistb2b39eb92019-11-18 16:16:504920 url, is_favicon, preferred_size, max_bitmap_size, bypass_cache,
tzike2aca992017-09-05 08:50:544921 base::BindOnce(&WebContentsImpl::OnDidDownloadImage,
Avi Drissmana5a52dd2018-03-27 03:39:024922 weak_factory_.GetWeakPtr(), std::move(callback),
4923 download_id, url));
amistry9f01b772015-07-29 01:54:554924 return download_id;
[email protected]795c28972012-12-06 06:13:394925}
4926
[email protected]36ec24f2014-01-09 00:32:084927void WebContentsImpl::Find(int request_id,
4928 const base::string16& search_text,
Rakina Zata Amni3f77dff2018-09-08 16:19:434929 blink::mojom::FindOptionsPtr options) {
Alexander Timin5fdeff22020-09-08 09:20:374930 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Find");
thestig6057a6b22015-11-12 23:01:334931 // Cowardly refuse to search for no text.
4932 if (search_text.empty()) {
4933 NOTREACHED();
4934 return;
4935 }
4936
Rakina Zata Amni3f77dff2018-09-08 16:19:434937 GetOrCreateFindRequestManager()->Find(request_id, search_text,
4938 std::move(options));
[email protected]36ec24f2014-01-09 00:32:084939}
4940
4941void WebContentsImpl::StopFinding(StopFindAction action) {
Alexander Timin5fdeff22020-09-08 09:20:374942 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::StopFinding");
paulmeyerfeafc2d2017-04-25 21:46:404943 if (FindRequestManager* manager = GetFindRequestManager())
4944 manager->StopFinding(action);
[email protected]36ec24f2014-01-09 00:32:084945}
4946
Tommy Steimel18360512017-11-01 00:38:194947bool WebContentsImpl::WasEverAudible() {
4948 return was_ever_audible_;
4949}
4950
Avi Drissmana5a52dd2018-03-27 03:39:024951void WebContentsImpl::GetManifest(GetManifestCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:374952 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GetManifest");
Yuzu Saijofce18322020-05-14 05:02:094953 // TODO(yuzus, 1061899): Move this function to RenderFrameHostImpl.
4954 ManifestManagerHost* manifest_manager_host =
4955 ManifestManagerHost::GetOrCreateForCurrentDocument(GetMainFrame());
4956 manifest_manager_host->GetManifest(std::move(callback));
mlamouriefdca9d2014-09-16 16:55:404957}
4958
bokanece34a82016-01-28 19:49:464959void WebContentsImpl::ExitFullscreen(bool will_cause_resize) {
Alexander Timin5fdeff22020-09-08 09:20:374960 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ExitFullscreen");
mlamouri7a78d6fd2015-01-17 13:23:534961 // Clean up related state and initiate the fullscreen exit.
James Hollyerd5c9de462020-03-10 19:02:454962 GetRenderViewHost()->GetWidget()->RejectMouseLockOrUnlockIfNecessary(
4963 blink::mojom::PointerLockResult::kUserRejected);
bokanece34a82016-01-28 19:49:464964 ExitFullscreenMode(will_cause_resize);
mlamouri7a78d6fd2015-01-17 13:23:534965}
4966
Mike Wassermanb6bc0152020-08-25 22:46:204967base::ScopedClosureRunner WebContentsImpl::ForSecurityDropFullscreen(
4968 int64_t display_id) {
Alexander Timin5fdeff22020-09-08 09:20:374969 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ForSecurityDropFullscreen",
4970 "display_id", display_id);
Avi Drissman33972942020-06-19 14:16:014971 // Kick WebContentses that are "related" to this WebContents out of
4972 // fullscreen. This needs to be done with two passes, because it is simple to
4973 // walk _up_ the chain of openers and outer contents, but it not simple to
4974 // walk _down_ the chain.
4975
4976 // First, determine if any WebContents that is in fullscreen has this
4977 // WebContents as an upstream contents. Drop that WebContents out of
4978 // fullscreen if it does. This is theoretically quadratic-ish (fullscreen
4979 // contentses x each one's opener length) but neither of those is expected to
4980 // ever be a large number.
4981
Mike Wassermanb6bc0152020-08-25 22:46:204982 auto* screen = display::Screen::GetScreen();
4983
Avi Drissman33972942020-06-19 14:16:014984 auto fullscreen_set_copy = *FullscreenContentsSet(GetBrowserContext());
4985 for (auto* fullscreen_contents : fullscreen_set_copy) {
Avi Drissman97aef042020-06-30 21:04:484986 // Checking IsFullscreen() for tabs in the fullscreen set may seem
4987 // redundant, but teeeeechnically fullscreen is run by the delegate, and
4988 // it's possible that the delegate's notion of fullscreen may have changed
4989 // outside of WebContents's notice.
Mike Wassermanb6bc0152020-08-25 22:46:204990 if (fullscreen_contents->IsFullscreen() &&
4991 (display_id == display::kInvalidDisplayId || !screen ||
4992 display_id ==
4993 screen->GetDisplayNearestView(fullscreen_contents->GetNativeView())
4994 .id())) {
Avi Drissman33972942020-06-19 14:16:014995 auto opener_contentses = GetAllOpeningWebContents(fullscreen_contents);
4996 if (opener_contentses.count(this))
4997 fullscreen_contents->ExitFullscreen(true);
4998 }
4999 }
5000
5001 // Second, walk upstream from this WebContents, and drop the fullscreen of
5002 // all WebContentses that are in fullscreen. Block all the WebContentses in
5003 // the chain from entering fullscreen while the returned closure runner is
5004 // alive. It's OK that this set doesn't contain downstream WebContentses, as
5005 // any request to enter fullscreen will have the upstream of the WebContents
5006 // checked. (See CanEnterFullscreenMode().)
Avi Drissmanced52b62019-08-14 21:25:465007
Avi Drissman1a55a9d62020-03-10 18:56:455008 std::vector<base::WeakPtr<WebContentsImpl>> blocked_contentses;
5009
Avi Drissman33972942020-06-19 14:16:015010 for (auto* opener : GetAllOpeningWebContents(this)) {
Avi Drissman1a55a9d62020-03-10 18:56:455011 // Drop fullscreen if the WebContents is in it, and...
Mike Wassermanb6bc0152020-08-25 22:46:205012 if (opener->IsFullscreen() &&
5013 (display_id == display::kInvalidDisplayId || !screen ||
5014 display_id ==
5015 screen->GetDisplayNearestView(opener->GetNativeView()).id()))
Avi Drissman33972942020-06-19 14:16:015016 opener->ExitFullscreen(true);
Avi Drissmanced52b62019-08-14 21:25:465017
Avi Drissman1a55a9d62020-03-10 18:56:455018 // ...block the WebContents from entering fullscreen until further notice.
Avi Drissman33972942020-06-19 14:16:015019 ++opener->fullscreen_blocker_count_;
5020 blocked_contentses.push_back(opener->weak_factory_.GetWeakPtr());
Avi Drissmanced52b62019-08-14 21:25:465021 }
Avi Drissman1a55a9d62020-03-10 18:56:455022
5023 return base::ScopedClosureRunner(base::BindOnce(
5024 [](std::vector<base::WeakPtr<WebContentsImpl>> blocked_contentses) {
5025 for (base::WeakPtr<WebContentsImpl>& web_contents :
5026 blocked_contentses) {
5027 if (web_contents) {
5028 DCHECK_GT(web_contents->fullscreen_blocker_count_, 0);
5029 --web_contents->fullscreen_blocker_count_;
5030 }
5031 }
5032 },
5033 std::move(blocked_contentses)));
Avi Drissmanced52b62019-08-14 21:25:465034}
5035
mariakhomenko44bdc4732015-04-29 01:55:385036void WebContentsImpl::ResumeLoadingCreatedWebContents() {
Alexander Timin5fdeff22020-09-08 09:20:375037 OPTIONAL_TRACE_EVENT0("content",
5038 "WebContentsImpl::ResumeLoadingCreatedWebContents");
Nasko Oskov83a8cf92018-10-19 14:58:565039 if (delayed_load_url_params_.get()) {
5040 DCHECK(!delayed_open_url_params_);
5041 controller_.LoadURLWithParams(*delayed_load_url_params_.get());
5042 delayed_load_url_params_.reset(nullptr);
5043 return;
5044 }
5045
mariakhomenkoa4971c12015-07-21 19:04:375046 if (delayed_open_url_params_.get()) {
5047 OpenURL(*delayed_open_url_params_.get());
5048 delayed_open_url_params_.reset(nullptr);
5049 return;
5050 }
5051
mariakhomenko44bdc4732015-04-29 01:55:385052 // Resume blocked requests for both the RenderViewHost and RenderFrameHost.
5053 // TODO(brettw): It seems bogus to reach into here and initialize the host.
dfalcantarae6b7b46752015-07-10 18:14:165054 if (is_resume_pending_) {
5055 is_resume_pending_ = false;
avi0f1bbc9712015-11-17 02:58:135056 GetRenderViewHost()->GetWidget()->Init();
dfalcantarae6b7b46752015-07-10 18:14:165057 GetMainFrame()->Init();
5058 }
mariakhomenko44bdc4732015-04-29 01:55:385059}
5060
[email protected]b172aee2012-04-10 17:05:265061bool WebContentsImpl::FocusLocationBarByDefault() {
Alexander Timin5fdeff22020-09-08 09:20:375062 OPTIONAL_TRACE_EVENT0("content",
5063 "WebContentsImpl::FocusLocationBarByDefault");
Xiyuan Xia2a66b112018-12-06 15:52:165064 if (should_focus_location_bar_by_default_)
[email protected]0c9406632013-02-08 01:13:335065 return true;
Xiyuan Xia2a66b112018-12-06 15:52:165066
[email protected]0c9406632013-02-08 01:13:335067 return delegate_ && delegate_->ShouldFocusLocationBarByDefault(this);
[email protected]0bfbf882011-12-22 18:19:275068}
5069
clamy0e119882015-07-31 16:12:335070void WebContentsImpl::DidStartNavigation(NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:485071 TRACE_EVENT1("navigation", "WebContentsImpl::DidStartNavigation",
5072 "navigation_handle", navigation_handle);
Alan Cutterab48fc02020-02-24 12:26:425073 if (navigation_handle->IsInMainFrame())
5074 favicon_urls_.clear();
Mounir Lamouri7b4a1f232019-12-23 16:32:105075
Alexander Timin90c20c32020-08-12 15:28:325076 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5077 observer->DidStartNavigation(navigation_handle);
5078 });
Xiyuan Xia2a66b112018-12-06 15:52:165079 if (navigation_handle->IsInMainFrame()) {
5080 // When the browser is started with about:blank as the startup URL, focus
5081 // the location bar (which will also select its contents) so people can
5082 // simply begin typing to navigate elsewhere.
5083 //
5084 // We need to be careful not to trigger this for anything other than the
5085 // startup navigation. In particular, if we allow an attacker to open a
5086 // popup to about:blank, then navigate, focusing the Omnibox will cause the
5087 // end of the new URL to be scrolled into view instead of the start,
5088 // allowing the attacker to spoof other URLs. The conditions checked here
5089 // are all aimed at ensuring no such attacker-controlled navigation can
5090 // trigger this.
5091 should_focus_location_bar_by_default_ =
5092 controller_.IsInitialNavigation() &&
5093 !navigation_handle->IsRendererInitiated() &&
5094 navigation_handle->GetURL() == url::kAboutBlankURL;
5095 }
clamy0e119882015-07-31 16:12:335096}
5097
5098void WebContentsImpl::DidRedirectNavigation(
5099 NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:485100 TRACE_EVENT1("navigation", "WebContentsImpl::DidRedirectNavigation",
5101 "navigation_handle", navigation_handle);
Alexander Timin90c20c32020-08-12 15:28:325102 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5103 observer->DidRedirectNavigation(navigation_handle);
5104 });
jam5f358e52017-02-13 16:37:035105 // Notify accessibility if this is a reload. This has to called on the
5106 // BrowserAccessibilityManager associated with the old RFHI.
5107 if (navigation_handle->GetReloadType() != ReloadType::NONE) {
Mohamed Abdelhalim95794962019-09-20 11:16:495108 NavigationRequest* request = NavigationRequest::From(navigation_handle);
jam5f358e52017-02-13 16:37:035109 BrowserAccessibilityManager* manager =
Mohamed Abdelhalim95794962019-09-20 11:16:495110 request->frame_tree_node()
jam5f358e52017-02-13 16:37:035111 ->current_frame_host()
5112 ->browser_accessibility_manager();
5113 if (manager)
5114 manager->UserIsReloading();
5115 }
clamy0e119882015-07-31 16:12:335116}
5117
clamyefca29e2015-09-17 00:22:115118void WebContentsImpl::ReadyToCommitNavigation(
5119 NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:485120 TRACE_EVENT1("navigation", "WebContentsImpl::ReadyToCommitNavigation",
5121 "navigation_handle", navigation_handle);
Alexander Timin90c20c32020-08-12 15:28:325122 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5123 observer->ReadyToCommitNavigation(navigation_handle);
5124 });
Kenneth Russell954ed9ce2018-04-12 23:07:015125 // If any domains are blocked from accessing 3D APIs because they may
5126 // have caused the GPU to reset recently, unblock them here if the user
5127 // initiated this navigation. This implies that the user was involved in
5128 // the decision to navigate, so there's no concern about
5129 // denial-of-service issues. Want to do this as early as
5130 // possible to avoid race conditions with pages attempting to access
5131 // WebGL early on.
5132 //
5133 // TODO(crbug.com/617904): currently navigations initiated by the browser
5134 // (reload button, reload menu option, pressing return in the Omnibox)
5135 // return false from HasUserGesture(). If or when that is addressed,
5136 // remove the check for IsRendererInitiated() below.
5137 //
5138 // TODO(crbug.com/832180): HasUserGesture comes from the renderer
5139 // process and isn't validated. Until it is, don't trust it.
5140 if (!navigation_handle->IsRendererInitiated()) {
5141 GpuDataManagerImpl::GetInstance()->UnblockDomainFrom3DAPIs(
5142 navigation_handle->GetURL());
5143 }
5144
John Abd-El-Malekfde08e6da2017-12-05 04:06:245145 if (navigation_handle->IsSameDocument())
5146 return;
5147
Livvie Lin139bf442018-08-10 00:18:545148 // SSLInfo is not needed on subframe navigations since the main-frame
5149 // certificate is the only one that can be inspected (using the info
5150 // bubble) without refreshing the page with DevTools open.
Carlos ILaed1e7b2019-03-12 19:27:215151 // We don't call DidStartResourceResponse on net errors, since that results on
5152 // existing cert exceptions being revoked, which leads to weird behavior with
5153 // committed interstitials or while offline. We only need the error check for
5154 // the main frame case because unlike this method, SubresourceResponseStarted
5155 // does not get called on network errors.
5156 if (navigation_handle->IsInMainFrame() &&
5157 navigation_handle->GetNetErrorCode() == net::OK) {
Livvie Lin139bf442018-08-10 00:18:545158 controller_.ssl_manager()->DidStartResourceResponse(
Lukasz Anforowiczd334bba2020-02-10 23:32:555159 navigation_handle->GetURL(),
Camille Lamy62b826012019-02-26 09:15:475160 navigation_handle->GetSSLInfo().has_value()
5161 ? net::IsCertStatusError(
5162 navigation_handle->GetSSLInfo()->cert_status)
5163 : false);
5164 }
John Abd-El-Malekfde08e6da2017-12-05 04:06:245165
Bruce Dawsone1c5c842020-09-15 02:09:145166 // LoadingStateChanged must be called last in case it triggers deletion of
5167 // |this| due to recursive message pumps.
John Abd-El-Malekfde08e6da2017-12-05 04:06:245168 SetNotWaitingForResponse();
clamyefca29e2015-09-17 00:22:115169}
5170
clamy0e119882015-07-31 16:12:335171void WebContentsImpl::DidFinishNavigation(NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:485172 TRACE_EVENT1("navigation", "WebContentsImpl::DidFinishNavigation",
5173 "navigation_handle", navigation_handle);
Steven Holte38041342018-06-22 22:00:575174
Alexander Timin90c20c32020-08-12 15:28:325175 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5176 observer->DidFinishNavigation(navigation_handle);
5177 });
Becca Hughesd11d6502018-07-31 17:01:285178 if (display_cutout_host_impl_)
5179 display_cutout_host_impl_->DidFinishNavigation(navigation_handle);
5180
jam5f358e52017-02-13 16:37:035181 if (navigation_handle->HasCommitted()) {
Ian Prestcdd843d2020-01-28 18:59:585182 // TODO(domfarolino, dmazzoni): Do this using WebContentsObserver. See
5183 // https://crbug.com/981271.
5184 BrowserAccessibilityManager* manager =
5185 static_cast<RenderFrameHostImpl*>(
5186 navigation_handle->GetRenderFrameHost())
5187 ->browser_accessibility_manager();
5188 if (manager) {
5189 if (navigation_handle->IsErrorPage()) {
5190 manager->NavigationFailed();
5191 } else {
5192 manager->NavigationSucceeded();
5193 }
5194 }
5195
Yue Ru Sun979c4b162019-11-06 16:11:045196 if (navigation_handle->IsInMainFrame()) {
5197 last_committed_source_id_including_same_document_ =
Steven Holte38041342018-06-22 22:00:575198 ukm::ConvertToSourceId(navigation_handle->GetNavigationId(),
5199 ukm::SourceIdType::NAVIGATION_ID);
Yue Ru Sun979c4b162019-11-06 16:11:045200
5201 if (!navigation_handle->IsSameDocument()) {
5202 was_ever_audible_ = false;
Yue Ru Sun979c4b162019-11-06 16:11:045203 }
Tommy Steimel18360512017-11-01 00:38:195204 }
Lan Weif81c6e7c2020-02-12 16:46:095205
5206 if (!navigation_handle->IsSameDocument())
5207 last_screen_orientation_change_time_ = base::TimeTicks();
dmazzonibf8cec42015-02-08 08:28:085208 }
Xiyuan Xia2a66b112018-12-06 15:52:165209
5210 // If we didn't end up on about:blank after setting this in DidStartNavigation
5211 // then don't focus the location bar.
5212 if (should_focus_location_bar_by_default_ &&
5213 navigation_handle->GetURL() != url::kAboutBlankURL) {
5214 should_focus_location_bar_by_default_ = false;
5215 }
yilkal796e89e2019-10-02 23:58:285216
yilkal172da772019-11-06 22:49:075217 if (navigation_handle->IsInMainFrame() && first_navigation_completed_)
5218 RecordMaxFrameCountUMA(max_loaded_frame_count_);
yilkal796e89e2019-10-02 23:58:285219
yilkal172da772019-11-06 22:49:075220 // If navigation has successfully finished in the main frame, set
5221 // |first_navigation_completed_| to true so that we will record
5222 // |max_loaded_frame_count_| above when future main frame navigations finish.
5223 if (navigation_handle->IsInMainFrame() && !navigation_handle->IsErrorPage()) {
5224 first_navigation_completed_ = true;
5225
5226 // Navigation has completed in main frame. Reset |max_loaded_frame_count_|.
5227 // |max_loaded_frame_count_| is not necessarily 1 if the navigation was
5228 // served from BackForwardCache.
5229 max_loaded_frame_count_ =
5230 GetMainFrame()->frame_tree_node()->GetFrameTreeSize();
yilkal796e89e2019-10-02 23:58:285231 }
Rakina Zata Amni347b70902020-07-22 10:49:045232
5233 if (web_preferences_) {
5234 // Update the WebPreferences for this WebContents that depends on changes
5235 // that might occur during navigation. This will only update the preferences
5236 // that needs to be updated (and won't cause an update/overwrite preferences
5237 // that needs to stay the same after navigations).
5238 bool value_changed_due_to_override =
5239 GetContentClient()->browser()->OverrideWebPreferencesAfterNavigation(
5240 this, web_preferences_.get());
5241 // We need to update the WebPreferences value on the renderer if the value
5242 // is changed due to the override above, or if the navigation is served from
5243 // the back-forward cache, because the WebPreferences value stored in the
5244 // renderer might be stale (because we don't send WebPreferences updates to
5245 // bfcached renderers).
5246 // TODO(rakina): Maybe handle the back-forward cache case in
5247 // ReadyToCommitNavigation instead?
5248 if (value_changed_due_to_override ||
5249 NavigationRequest::From(navigation_handle)
5250 ->IsServedFromBackForwardCache()) {
5251 SetWebPreferences(*web_preferences_.get());
5252 }
5253 }
[email protected]400992b2012-06-14 00:03:545254}
5255
[email protected]b80624c2014-02-09 02:46:555256void WebContentsImpl::DidFailLoadWithError(
5257 RenderFrameHostImpl* render_frame_host,
[email protected]b80624c2014-02-09 02:46:555258 const GURL& url,
Dave Tapuska924ef3c2020-01-22 18:20:595259 int error_code) {
Alexander Timin5fdeff22020-09-08 09:20:375260 TRACE_EVENT2("content,navigation", "WebContentsImpl::DidFailLoadWithError",
5261 "render_frame_host",
5262 base::trace_event::ToTracedValue(render_frame_host), "url",
5263 base::trace_event::ValueToString(url));
Alexander Timin90c20c32020-08-12 15:28:325264 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5265 observer->DidFailLoad(render_frame_host, url, error_code);
5266 });
[email protected]b80624c2014-02-09 02:46:555267}
5268
[email protected]52913802013-12-10 05:52:185269void WebContentsImpl::NotifyChangedNavigationState(
5270 InvalidateTypes changed_flags) {
5271 NotifyNavigationStateChanged(changed_flags);
5272}
5273
lukasza1d025732016-09-28 21:36:085274bool WebContentsImpl::ShouldTransferNavigation(bool is_main_frame_navigation) {
Alexander Timin5fdeff22020-09-08 09:20:375275 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ShouldTransferNavigation",
5276 "is_main_frame_navigation", is_main_frame_navigation);
creis29460272015-12-16 04:38:225277 if (!delegate_)
5278 return true;
lukasza1d025732016-09-28 21:36:085279 return delegate_->ShouldTransferNavigation(is_main_frame_navigation);
creis29460272015-12-16 04:38:225280}
5281
[email protected]aa62afd2014-04-22 19:22:465282bool WebContentsImpl::ShouldPreserveAbortedURLs() {
Alexander Timin5fdeff22020-09-08 09:20:375283 OPTIONAL_TRACE_EVENT0("content",
5284 "WebContentsImpl::ShouldPreserveAbortedURLs");
[email protected]aa62afd2014-04-22 19:22:465285 if (!delegate_)
5286 return false;
5287 return delegate_->ShouldPreserveAbortedURLs(this);
5288}
5289
[email protected]0d0f4c492014-04-02 06:42:575290void WebContentsImpl::DidNavigateMainFramePreCommit(
[email protected]5cfbddc2014-06-23 23:52:235291 bool navigation_is_within_page) {
Alexander Timin5fdeff22020-09-08 09:20:375292 TRACE_EVENT1("content,navigation",
5293 "WebContentsImpl::DidNavigateMainFramePreCommit",
5294 "navigation_is_within_page", navigation_is_within_page);
[email protected]0d0f4c492014-04-02 06:42:575295 // Ensure fullscreen mode is exited before committing the navigation to a
5296 // different page. The next page will not start out assuming it is in
5297 // fullscreen mode.
[email protected]5cfbddc2014-06-23 23:52:235298 if (navigation_is_within_page) {
[email protected]dfc39cb2014-04-09 22:58:195299 // No page change? Then, the renderer and browser can remain in fullscreen.
[email protected]0d0f4c492014-04-02 06:42:575300 return;
5301 }
Avi Drissman97aef042020-06-30 21:04:485302 if (IsFullscreen())
bokanece34a82016-01-28 19:49:465303 ExitFullscreen(false);
Avi Drissman97aef042020-06-30 21:04:485304 DCHECK(!IsFullscreen());
Joe Downingc1a57efe2018-05-09 18:23:545305
5306 // Clean up keyboard lock state when navigating.
5307 CancelKeyboardLock(keyboard_lock_widget_);
[email protected]0d0f4c492014-04-02 06:42:575308}
5309
[email protected]37567b432014-02-12 01:12:225310void WebContentsImpl::DidNavigateMainFramePostCommit(
sky8b00392d2015-01-10 00:30:285311 RenderFrameHostImpl* render_frame_host,
[email protected]37567b432014-02-12 01:12:225312 const LoadCommittedDetails& details,
5313 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
Alexander Timin5fdeff22020-09-08 09:20:375314 OPTIONAL_TRACE_EVENT1(
5315 "content,navigation", "WebContentsImpl::DidNavigateMainFramePostCommit",
5316 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host));
[email protected]37567b432014-02-12 01:12:225317 if (details.is_navigation_to_different_page()) {
5318 // Clear the status bubble. This is a workaround for a bug where WebKit
5319 // doesn't let us know that the cursor left an element during a
5320 // transition (this is also why the mouse cursor remains as a hand after
5321 // clicking on a link); see bugs 1184641 and 980803. We don't want to
5322 // clear the bubble when a user navigates to a named anchor in the same
5323 // page.
Lukasz Anforowiczfd707142018-02-07 19:46:135324 ClearTargetURL();
lanwei9d343ad22015-02-11 01:46:005325
5326 RenderWidgetHostViewBase* rwhvb =
5327 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
5328 if (rwhvb)
5329 rwhvb->OnDidNavigateMainFrameToNewPage();
[email protected]37567b432014-02-12 01:12:225330 }
5331
[email protected]e85165c642014-06-10 14:34:315332 if (delegate_)
[email protected]37567b432014-02-12 01:12:225333 delegate_->DidNavigateMainFramePostCommit(this);
[email protected]e85165c642014-06-10 14:34:315334 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
Shivani Sharma985474f2019-05-23 21:36:475335
Alan Cutterd73a15d92020-08-21 07:12:455336 // The following events will not fire again if the page is restored from the
5337 // BackForwardCache. So fire them ourselves if needed.
Carlos Caballero91fffb22019-10-29 15:24:305338 if (details.is_navigation_to_different_page() &&
5339 GetRenderViewHost()->did_first_visually_non_empty_paint()) {
Carlos Caballero91fffb22019-10-29 15:24:305340 DidFirstVisuallyNonEmptyPaint(GetRenderViewHost());
5341 }
Alan Cutterd73a15d92020-08-21 07:12:455342 if (GetRenderViewHost()->theme_color() != last_sent_theme_color_)
Carlos Caballero1215f882019-10-29 15:58:435343 OnThemeColorChanged(GetRenderViewHost());
Alan Cutterd73a15d92020-08-21 07:12:455344 if (GetRenderViewHost()->background_color() != last_sent_background_color_)
5345 OnBackgroundColorChanged(GetRenderViewHost());
[email protected]37567b432014-02-12 01:12:225346}
5347
5348void WebContentsImpl::DidNavigateAnyFramePostCommit(
5349 RenderFrameHostImpl* render_frame_host,
5350 const LoadCommittedDetails& details,
5351 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
Alexander Timin5fdeff22020-09-08 09:20:375352 OPTIONAL_TRACE_EVENT1(
5353 "content,navigation", "WebContentsImpl::DidNavigateAnyFramePostCommit",
5354 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host));
[email protected]b4c84012014-04-28 19:51:105355 // Now that something has committed, we don't need to track whether the
5356 // initial page has been accessed.
5357 has_accessed_initial_document_ = false;
5358
[email protected]37567b432014-02-12 01:12:225359 // If we navigate off the page, close all JavaScript dialogs.
eugenebutee08663a2017-04-27 17:43:125360 if (!details.is_same_document)
creis89a0f782015-05-27 16:13:175361 CancelActiveAndPendingDialogs();
[email protected]37567b432014-02-12 01:12:225362
avid53461d2016-02-25 17:15:045363 // If this is a user-initiated navigation, start allowing JavaScript dialogs
5364 // again.
avi5d3b8692016-10-12 22:00:465365 if (params.gesture == NavigationGestureUser && dialog_manager_) {
avi6879fcf2017-01-21 05:27:535366 dialog_manager_->CancelDialogs(this, /*reset_state=*/true);
avi5d3b8692016-10-12 22:00:465367 }
[email protected]37567b432014-02-12 01:12:225368}
5369
[email protected]277857a2014-06-03 10:38:015370bool WebContentsImpl::CanOverscrollContent() const {
Alexander Timin5fdeff22020-09-08 09:20:375371 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::CanOverscrollContent");
[email protected]e85165c642014-06-10 14:34:315372 // Disable overscroll when touch emulation is on. See crbug.com/369938.
[email protected]34ff1cfc2014-08-20 06:16:055373 if (force_disable_overscroll_content_)
[email protected]e85165c642014-06-10 14:34:315374 return false;
5375
[email protected]37567b432014-02-12 01:12:225376 if (delegate_)
5377 return delegate_->CanOverscrollContent();
5378
5379 return false;
5380}
5381
Carlos Caballero1215f882019-10-29 15:58:435382void WebContentsImpl::OnThemeColorChanged(RenderViewHostImpl* source) {
Alexander Timin5fdeff22020-09-08 09:20:375383 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnThemeColorChanged",
5384 "render_view_host", source);
Carlos Caballero1215f882019-10-29 15:58:435385 if (source->did_first_visually_non_empty_paint() &&
5386 last_sent_theme_color_ != source->theme_color()) {
Alexander Timin90c20c32020-08-12 15:28:325387 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5388 observer->DidChangeThemeColor();
5389 });
Matt Jones36fc2882020-08-25 14:25:125390 last_sent_theme_color_ = source->theme_color();
peter90afaba2015-06-01 12:05:295391 }
[email protected]e7104762014-06-20 19:17:255392}
5393
Alan Cutterd73a15d92020-08-21 07:12:455394void WebContentsImpl::OnBackgroundColorChanged(RenderViewHostImpl* source) {
Rune Lillesveend14781f2020-10-06 19:36:115395 if (source->did_first_visually_non_empty_paint()) {
5396 if (last_sent_background_color_ != source->background_color()) {
5397 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5398 observer->OnBackgroundColorChanged();
5399 });
5400 last_sent_background_color_ = source->background_color();
5401 }
5402 return;
5403 }
5404
5405 if (source->background_color().has_value()) {
5406 // <meta name="color-scheme" content="dark"> may pass the dark canvas
5407 // background before the first paint in order to avoid flashing the white
5408 // background in between loading documents. If we perform a navigation
5409 // within the same renderer process, we keep the content background from the
5410 // previous page while rendering is blocked in the new page, but for cross
5411 // process navigations we would paint the default background (typically
5412 // white) while the rendering is blocked.
5413 if (auto* view = GetRenderWidgetHostView()) {
5414 static_cast<RenderWidgetHostViewBase*>(view)->SetContentBackgroundColor(
5415 source->background_color().value());
5416 }
Alan Cutterd73a15d92020-08-21 07:12:455417 }
5418}
5419
Gyuyoung Kim1905f7c2020-05-02 00:00:245420void WebContentsImpl::DidLoadResourceFromMemoryCache(
nicka0ac8382016-12-15 23:59:235421 RenderFrameHostImpl* source,
[email protected]724159a2010-12-30 01:11:185422 const GURL& url,
[email protected]70435962011-08-02 20:13:285423 const std::string& http_method,
[email protected]6d6cfb3a2012-05-23 22:53:185424 const std::string& mime_type,
Kinuko Yasuda433f710a2020-02-14 02:11:585425 network::mojom::RequestDestination request_destination) {
Alexander Timin5fdeff22020-09-08 09:20:375426 OPTIONAL_TRACE_EVENT2(
5427 "content", "WebContentsImpl::DidLoadResourceFromMemoryCache",
5428 "render_frame_host", base::trace_event::ToTracedValue(source), "url",
5429 base::trace_event::ValueToString(url));
Alexander Timin90c20c32020-08-12 15:28:325430 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5431 observer->DidLoadResourceFromMemoryCache(url, mime_type,
5432 request_destination);
5433 });
[email protected]b0f724c2013-09-05 04:21:135434
Steven Bingler674fb0822018-12-12 18:04:525435 if (url.is_valid() && url.SchemeIsHTTPOrHTTPS()) {
nicka0ac8382016-12-15 23:59:235436 StoragePartition* partition = source->GetProcess()->GetStoragePartition();
John Abd-El-Malekf4fe9d82019-07-31 04:05:595437 partition->GetNetworkContext()->NotifyExternalCacheHit(
Matt Menke2a33dee2019-12-02 17:01:545438 url, http_method, source->GetNetworkIsolationKey());
[email protected]8bfc8272013-09-09 20:10:535439 }
[email protected]724159a2010-12-30 01:11:185440}
5441
carloskd9d97942017-02-16 08:58:095442void WebContentsImpl::DidDisplayInsecureContent() {
Alexander Timin5fdeff22020-09-08 09:20:375443 OPTIONAL_TRACE_EVENT0("content",
5444 "WebContentsImpl::DidDisplayInsecureContent");
estarkc2273502016-10-12 22:03:025445 controller_.ssl_manager()->DidDisplayMixedContent();
[email protected]724159a2010-12-30 01:11:185446}
5447
Dave Tapuskaa657d872019-10-21 20:23:215448void WebContentsImpl::DidContainInsecureFormAction() {
Alexander Timin5fdeff22020-09-08 09:20:375449 OPTIONAL_TRACE_EVENT0("content",
5450 "WebContentsImpl::DidContainInsecureFormAction");
elawrenceb2ac2a232017-03-27 21:46:255451 controller_.ssl_manager()->DidContainInsecureFormAction();
5452}
5453
Julie Jeongeun Kim0b103492020-01-29 05:30:515454void WebContentsImpl::DocumentAvailableInMainFrame() {
Alexander Timin5fdeff22020-09-08 09:20:375455 OPTIONAL_TRACE_EVENT0("content",
5456 "WebContentsImpl::DocumentAvailableInMainFrame");
Alexander Timin90c20c32020-08-12 15:28:325457 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5458 observer->DocumentAvailableInMainFrame();
5459 });
Julie Jeongeun Kim0b103492020-01-29 05:30:515460}
5461
nicka0ac8382016-12-15 23:59:235462void WebContentsImpl::OnDidRunInsecureContent(RenderFrameHostImpl* source,
5463 const GURL& security_origin,
estark910b4572015-12-09 20:55:415464 const GURL& target_url) {
Alexander Timin5fdeff22020-09-08 09:20:375465 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnDidRunInsecureContent",
5466 "render_frame_host",
5467 base::trace_event::ToTracedValue(source));
nicka0ac8382016-12-15 23:59:235468 // TODO(nick, estark): Should we call FilterURL using |source|'s process on
5469 // these parameters? |target_url| seems unused, except for a log message. And
5470 // |security_origin| might be replaceable with the origin of the main frame.
carloskd9d97942017-02-16 08:58:095471 DidRunInsecureContent(security_origin, target_url);
5472}
5473
5474void WebContentsImpl::DidRunInsecureContent(const GURL& security_origin,
5475 const GURL& target_url) {
Alexander Timin5fdeff22020-09-08 09:20:375476 OPTIONAL_TRACE_EVENT2(
5477 "content", "WebContentsImpl::DidRunInsecureContent", "security_origin",
5478 base::trace_event::ValueToString(security_origin), "target_url",
5479 base::trace_event::ValueToString(target_url));
[email protected]9450c462013-11-23 01:22:585480 LOG(WARNING) << security_origin << " ran insecure content from "
5481 << target_url.possibly_invalid_spec();
[email protected]e6e30ac2014-01-13 21:24:395482 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
estark910b4572015-12-09 20:55:415483 if (base::EndsWith(security_origin.spec(), kDotGoogleDotCom,
brettwa7ff1b292015-07-16 17:49:295484 base::CompareCase::INSENSITIVE_ASCII))
[email protected]e6e30ac2014-01-13 21:24:395485 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
estarkc2273502016-10-12 22:03:025486 controller_.ssl_manager()->DidRunMixedContent(security_origin);
[email protected]724159a2010-12-30 01:11:185487}
5488
carloskd9d97942017-02-16 08:58:095489void WebContentsImpl::PassiveInsecureContentFound(const GURL& resource_url) {
Alexander Timin5fdeff22020-09-08 09:20:375490 OPTIONAL_TRACE_EVENT1(
5491 "content", "WebContentsImpl::PassiveInsecureContentFound", "resource_url",
5492 base::trace_event::ValueToString(resource_url));
Sergey Kuznetsov3ebc01b2018-02-01 04:57:365493 if (delegate_) {
5494 delegate_->PassiveInsecureContentFound(resource_url);
5495 }
carloskd9d97942017-02-16 08:58:095496}
5497
5498bool WebContentsImpl::ShouldAllowRunningInsecureContent(
carloskd9d97942017-02-16 08:58:095499 bool allowed_per_prefs,
5500 const url::Origin& origin,
5501 const GURL& resource_url) {
Alexander Timin5fdeff22020-09-08 09:20:375502 OPTIONAL_TRACE_EVENT0("content",
5503 "WebContentsImpl::ShouldAllowRunningInsecureContent");
Sergey Kuznetsov3ebc01b2018-02-01 04:57:365504 if (delegate_) {
Carlos IL29294a62020-05-15 00:21:165505 return delegate_->ShouldAllowRunningInsecureContent(this, allowed_per_prefs,
5506 origin, resource_url);
Sergey Kuznetsov3ebc01b2018-02-01 04:57:365507 }
5508
5509 return allowed_per_prefs;
carloskd9d97942017-02-16 08:58:095510}
5511
Lukasz Anforowicze1b954d92017-10-30 21:28:065512void WebContentsImpl::ViewSource(RenderFrameHostImpl* frame) {
Alexander Timin5fdeff22020-09-08 09:20:375513 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ViewSource",
5514 "render_frame_host",
5515 base::trace_event::ToTracedValue(frame));
Lukasz Anforowicze1b954d92017-10-30 21:28:065516 DCHECK_EQ(this, WebContents::FromRenderFrameHost(frame));
5517
5518 // Don't do anything if there is no |delegate_| that could accept and show the
5519 // new WebContents containing the view-source.
5520 if (!delegate_)
5521 return;
5522
5523 // Use the last committed entry, since the pending entry hasn't loaded yet and
5524 // won't be copied into the cloned tab.
5525 NavigationEntryImpl* last_committed_entry =
Fergal Daly09d6c762020-05-29 02:05:185526 GetController().GetLastCommittedEntry();
Lukasz Anforowicze1b954d92017-10-30 21:28:065527 if (!last_committed_entry)
5528 return;
5529
5530 FrameNavigationEntry* frame_entry =
5531 last_committed_entry->GetFrameEntry(frame->frame_tree_node());
5532 if (!frame_entry)
5533 return;
5534
5535 // Any new WebContents opened while this WebContents is in fullscreen can be
5536 // used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:455537 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
5538 // The new view source contents will be independent of this contents, so
5539 // release the fullscreen block.
5540 fullscreen_block.RunAndReset();
Lukasz Anforowicze1b954d92017-10-30 21:28:065541
5542 // We intentionally don't share the SiteInstance with the original frame so
5543 // that view source has a consistent process model and always ends up in a new
5544 // process (https://crbug.com/699493).
5545 scoped_refptr<SiteInstanceImpl> site_instance_for_view_source = nullptr;
Lukasz Anforowicz435bcb582019-07-12 20:50:065546 // Referrer and initiator are not important, because view-source should not
5547 // hit the network, but should be served from the cache instead.
Lukasz Anforowicze1b954d92017-10-30 21:28:065548 Referrer referrer_for_view_source;
Lukasz Anforowicz435bcb582019-07-12 20:50:065549 base::Optional<url::Origin> initiator_for_view_source = base::nullopt;
Lukasz Anforowicze1b954d92017-10-30 21:28:065550 // Do not restore title, derive it from the url.
5551 base::string16 title_for_view_source;
5552 auto navigation_entry = std::make_unique<NavigationEntryImpl>(
5553 site_instance_for_view_source, frame_entry->url(),
Lukasz Anforowicz435bcb582019-07-12 20:50:065554 referrer_for_view_source, initiator_for_view_source,
5555 title_for_view_source, ui::PAGE_TRANSITION_LINK,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:095556 /* is_renderer_initiated = */ false,
5557 /* blob_url_loader_factory = */ nullptr);
Joel Hockey891e88062020-04-30 05:38:445558 const GURL url(content::kViewSourceScheme + std::string(":") +
5559 frame_entry->url().spec());
5560 navigation_entry->SetVirtualURL(url);
Matt Menkea56c5992020-04-10 20:53:565561 navigation_entry->set_isolation_info(
5562 frame->GetIsolationInfoForSubresources());
Yao Xiaof68f57d2019-10-03 04:20:055563
Lukasz Anforowicze1b954d92017-10-30 21:28:065564 // Do not restore scroller position.
5565 // TODO(creis, lukasza, arthursonzogni): Do not reuse the original PageState,
5566 // but start from a new one and only copy the needed data.
Miyoung Shin5d77f72072020-10-09 15:14:205567 const blink::PageState& new_page_state =
Lukasz Anforowicze1b954d92017-10-30 21:28:065568 frame_entry->page_state().RemoveScrollOffset();
5569
5570 scoped_refptr<FrameNavigationEntry> new_frame_entry =
5571 navigation_entry->root_node()->frame_entry;
5572 new_frame_entry->set_method(frame_entry->method());
5573 new_frame_entry->SetPageState(new_page_state);
5574
5575 // Create a new WebContents, which is used to display the source code.
erikchenbee5c9622018-04-27 19:30:255576 std::unique_ptr<WebContents> view_source_contents =
Erik Chenbb8e738e2018-04-28 14:10:435577 Create(CreateParams(GetBrowserContext()));
Lukasz Anforowicze1b954d92017-10-30 21:28:065578
5579 // Restore the previously created NavigationEntry.
5580 std::vector<std::unique_ptr<NavigationEntry>> navigation_entries;
5581 navigation_entries.push_back(std::move(navigation_entry));
5582 view_source_contents->GetController().Restore(0, RestoreType::CURRENT_SESSION,
5583 &navigation_entries);
5584
5585 // Add |view_source_contents| as a new tab.
5586 gfx::Rect initial_rect;
5587 constexpr bool kUserGesture = true;
5588 bool ignored_was_blocked;
Joel Hockey891e88062020-04-30 05:38:445589 delegate_->AddNewContents(this, std::move(view_source_contents), url,
Lukasz Anforowicze1b954d92017-10-30 21:28:065590 WindowOpenDisposition::NEW_FOREGROUND_TAB,
5591 initial_rect, kUserGesture, &ignored_was_blocked);
5592 // Note that the |delegate_| could have deleted |view_source_contents| during
5593 // AddNewContents method call.
5594}
5595
Lukasz Anforowiczd334bba2020-02-10 23:32:555596void WebContentsImpl::SubresourceResponseStarted(const GURL& url,
5597 net::CertStatus cert_status) {
Alexander Timin5fdeff22020-09-08 09:20:375598 OPTIONAL_TRACE_EVENT1("content",
5599 "WebContentsImpl::SubresourceResponseStarted", "url",
5600 base::trace_event::ValueToString(url));
Lukasz Anforowiczd334bba2020-02-10 23:32:555601 controller_.ssl_manager()->DidStartResourceResponse(url, cert_status);
Jay Civellid5904f02018-03-23 19:43:575602 SetNotWaitingForResponse();
5603}
5604
Jay Civelli116683f2018-03-27 19:56:235605void WebContentsImpl::ResourceLoadComplete(
Jay Civelli52a63302018-04-30 22:39:555606 RenderFrameHost* render_frame_host,
Clark DuVall36164bd2018-08-09 22:49:085607 const GlobalRequestID& request_id,
Minggang Wangee5af392020-02-05 02:55:285608 blink::mojom::ResourceLoadInfoPtr resource_load_info) {
Alexander Timin5fdeff22020-09-08 09:20:375609 OPTIONAL_TRACE_EVENT2(
5610 "content", "WebContentsImpl::ResourceLoadComplete", "render_frame_host",
5611 base::trace_event::ToTracedValue(render_frame_host), "request_id",
5612 base::trace_event::TracedValue::Build(
5613 {{"child_id", request_id.child_id},
5614 {"request_id", request_id.request_id}}));
Alexander Timin90c20c32020-08-12 15:28:325615 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5616 observer->ResourceLoadComplete(render_frame_host, request_id,
5617 *resource_load_info);
5618 });
John Abd-El-Malekd4882642017-12-04 21:45:195619}
5620
Gyuyoung Kim1ac4ca782020-09-11 03:32:515621const blink::web_pref::WebPreferences&
5622WebContentsImpl::GetOrCreateWebPreferences() {
Alexander Timin5fdeff22020-09-08 09:20:375623 OPTIONAL_TRACE_EVENT0("content",
5624 "WebContentsImpl::GetOrCreateWebPreferences");
Rakina Zata Amni347b70902020-07-22 10:49:045625 // Compute WebPreferences based on the current state if it's null.
5626 if (!web_preferences_)
Rakina Zata Amni4029b6d2020-07-28 02:36:205627 OnWebPreferencesChanged();
Rakina Zata Amni347b70902020-07-22 10:49:045628 return *web_preferences_.get();
5629}
5630
5631bool WebContentsImpl::IsWebPreferencesSet() const {
5632 return web_preferences_.get();
5633}
5634
Gyuyoung Kim1ac4ca782020-09-11 03:32:515635void WebContentsImpl::SetWebPreferences(
5636 const blink::web_pref::WebPreferences& prefs) {
Alexander Timin5fdeff22020-09-08 09:20:375637 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetWebPreferences");
Gyuyoung Kim1ac4ca782020-09-11 03:32:515638 web_preferences_ = std::make_unique<blink::web_pref::WebPreferences>(prefs);
Rakina Zata Amni347b70902020-07-22 10:49:045639 // Get all the RenderViewHosts (except the ones for currently back-forward
5640 // cached pages), and make them send the current WebPreferences
5641 // to the renderer. WebPreferences updates for back-forward cached pages will
5642 // be sent when we restore those pages from the back-forward cache.
5643 for (auto& rvh : frame_tree_.render_view_hosts()) {
5644 rvh.second->SendWebPreferencesToRenderer();
5645 }
5646}
5647
5648void WebContentsImpl::RecomputeWebPreferencesSlow() {
Alexander Timin5fdeff22020-09-08 09:20:375649 OPTIONAL_TRACE_EVENT0("content",
5650 "WebContentsImpl::RecomputeWebPreferencesSlow");
Rakina Zata Amni4029b6d2020-07-28 02:36:205651 // OnWebPreferencesChanged is a no-op when this is true.
5652 if (updating_web_preferences_)
5653 return;
Rakina Zata Amni347b70902020-07-22 10:49:045654 // Resets |web_preferences_| so that we won't have any cached value for slow
5655 // attributes (which won't get recomputed if we have pre-existing values for
5656 // them).
5657 web_preferences_.reset();
Rakina Zata Amni4029b6d2020-07-28 02:36:205658 OnWebPreferencesChanged();
Rakina Zata Amni347b70902020-07-22 10:49:045659}
5660
Wei Li5bb659742018-02-14 03:07:585661void WebContentsImpl::PrintCrossProcessSubframe(
5662 const gfx::Rect& rect,
5663 int document_cookie,
5664 RenderFrameHost* subframe_host) {
Alexander Timin5fdeff22020-09-08 09:20:375665 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::PrintCrossProcessSubframe",
5666 "subframe",
5667 base::trace_event::ToTracedValue(subframe_host));
Wei Li5c0b4d12018-03-22 15:05:225668 auto* outer_contents = GetOuterWebContents();
5669 if (outer_contents) {
5670 // When an extension or app page is printed, the content should be
5671 // composited with outer content, so the outer contents should handle the
5672 // print request.
5673 outer_contents->PrintCrossProcessSubframe(rect, document_cookie,
5674 subframe_host);
5675 return;
5676 }
5677
Wei Li5bb659742018-02-14 03:07:585678 // If there is no delegate such as in tests or during deletion, do nothing.
5679 if (!delegate_)
5680 return;
5681
5682 delegate_->PrintCrossProcessSubframe(this, rect, document_cookie,
5683 subframe_host);
5684}
5685
ckitagawa8695799b2020-02-05 16:08:495686void WebContentsImpl::CapturePaintPreviewOfCrossProcessSubframe(
5687 const gfx::Rect& rect,
5688 const base::UnguessableToken& guid,
5689 RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:375690 OPTIONAL_TRACE_EVENT1(
5691 "content", "WebContentsImpl::CapturePaintPreviewOfCrossProcessSubframe",
5692 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host));
ckitagawa8695799b2020-02-05 16:08:495693 if (!delegate_)
5694 return;
ckitagawac43ac982020-07-07 17:41:175695 delegate_->CapturePaintPreviewOfSubframe(this, rect, guid, render_frame_host);
ckitagawa8695799b2020-02-05 16:08:495696}
5697
rob.buis300b0872017-03-10 20:43:585698#if defined(OS_ANDROID)
5699base::android::ScopedJavaLocalRef<jobject>
5700WebContentsImpl::GetJavaRenderFrameHostDelegate() {
5701 return GetJavaWebContents();
5702}
5703#endif
5704
Hiroki Nakagawa39d1bbe2020-07-14 16:15:525705void WebContentsImpl::OnDidDisplayContentWithCertificateErrors() {
Alexander Timin5fdeff22020-09-08 09:20:375706 OPTIONAL_TRACE_EVENT0(
5707 "content", "WebContentsImpl::OnDidDisplayContentWithCertificateErrors");
estarkc2273502016-10-12 22:03:025708 controller_.ssl_manager()->DidDisplayContentWithCertErrors();
estark910b4572015-12-09 20:55:415709}
5710
5711void WebContentsImpl::OnDidRunContentWithCertificateErrors(
Zhuoyu Qian4353f7f2018-01-08 05:33:005712 RenderFrameHostImpl* source) {
Alexander Timin5fdeff22020-09-08 09:20:375713 OPTIONAL_TRACE_EVENT1(
5714 "content", "WebContentsImpl::OnDidRunContentWithCertificateErrors",
5715 "render_frame_host", base::trace_event::ToTracedValue(source));
Emily Starkabbdd662020-06-05 02:40:135716 // For RenderFrameHosts that are inactive and going to be discarded, we can
5717 // disregard this message; there's no need to update the UI if the UI will
5718 // never be shown again.
5719 //
5720 // We still process this message for speculative RenderFrameHosts. This can
5721 // happen when a subframe's main resource has a certificate error. The
5722 // currently committed navigation entry will get marked as having run insecure
5723 // content and that will carry over to the navigation entry for the
5724 // speculative RFH when it commits.
5725 if (source->lifecycle_state() !=
5726 RenderFrameHostImpl::LifecycleState::kSpeculative &&
5727 source->IsInactiveAndDisallowReactivation()) {
estarkaeda1422016-05-10 02:31:125728 return;
Emily Starkabbdd662020-06-05 02:40:135729 }
estarkcd2e30c2016-08-12 06:51:155730 controller_.ssl_manager()->DidRunContentWithCertErrors(
Emily Starkabbdd662020-06-05 02:40:135731 source->GetMainFrame()->GetLastCommittedOrigin().GetURL());
estark910b4572015-12-09 20:55:415732}
5733
Kouhei Ueno97e0990d2019-09-25 02:57:275734void WebContentsImpl::DOMContentLoaded(RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:375735 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DOMContentLoaded",
5736 "render_frame_host",
5737 base::trace_event::ToTracedValue(render_frame_host));
Alexander Timin90c20c32020-08-12 15:28:325738 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5739 observer->DOMContentLoaded(render_frame_host);
5740 });
[email protected]724159a2010-12-30 01:11:185741}
5742
Gyuyoung Kim525e0c5d2020-03-09 15:04:195743void WebContentsImpl::OnDidFinishLoad(RenderFrameHost* render_frame_host,
nicka0ac8382016-12-15 23:59:235744 const GURL& url) {
Alexander Timin5fdeff22020-09-08 09:20:375745 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnDidFinishLoad",
5746 "render_frame_host",
5747 base::trace_event::ToTracedValue(render_frame_host),
5748 "url", base::trace_event::ValueToString(url));
[email protected]8b3af1e2014-01-24 13:29:125749 GURL validated_url(url);
Gyuyoung Kim525e0c5d2020-03-09 15:04:195750 render_frame_host->GetProcess()->FilterURL(false, &validated_url);
[email protected]028053d42014-03-05 22:20:375751
Alexander Timin90c20c32020-08-12 15:28:325752 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5753 observer->DidFinishLoad(render_frame_host, validated_url);
5754 });
yilkal172da772019-11-06 22:49:075755 size_t tree_size = frame_tree_.root()->GetFrameTreeSize();
5756 if (max_loaded_frame_count_ < tree_size)
5757 max_loaded_frame_count_ = tree_size;
5758
Gyuyoung Kim525e0c5d2020-03-09 15:04:195759 if (!render_frame_host->GetParent())
yilkal172da772019-11-06 22:49:075760 UMA_HISTOGRAM_COUNTS_1000("Navigation.MainFrame.FrameCount", tree_size);
[email protected]1a55c5b2011-11-29 11:36:315761}
5762
Dave Tapuska549baab2019-03-19 15:52:405763void WebContentsImpl::OnGoToEntryAtOffset(RenderFrameHostImpl* source,
Julie Jeongeun Kim144f8192020-01-18 06:59:035764 int32_t offset,
Dave Tapuska043b94a2019-09-10 14:14:355765 bool has_user_gesture) {
Alexander Timin5fdeff22020-09-08 09:20:375766 OPTIONAL_TRACE_EVENT2(
5767 "content", "WebContentsImpl::OnGoToEntryAtOffset", "render_frame_host",
5768 base::trace_event::ToTracedValue(source), "offset", offset);
Arthur Sonzognia7d715a2018-09-20 16:11:135769 // Non-user initiated navigations coming from the renderer should be ignored
5770 // if there is an ongoing browser-initiated navigation.
5771 // See https://crbug.com/879965.
5772 // TODO(arthursonzogni): See if this should check for ongoing navigations in
5773 // the frame(s) affected by the session history navigation, rather than just
5774 // the main frame.
Kevin McNee96851e12020-07-16 03:43:225775 if (Navigator::ShouldIgnoreIncomingRendererRequest(
5776 frame_tree_.root()->navigation_request(), has_user_gesture))
5777 return;
Arthur Sonzognia7d715a2018-09-20 16:11:135778
nicka0ac8382016-12-15 23:59:235779 // All frames are allowed to navigate the global history.
Dave Tapuska8bfd84c2019-03-26 20:47:165780 if (!delegate_ || delegate_->OnGoToEntryOffset(offset)) {
arthursonzognib93a4472020-04-10 07:38:005781 if (source->IsSandboxed(network::mojom::WebSandboxFlags::kTopNavigation)) {
Dave Tapuska8bfd84c2019-03-26 20:47:165782 // Keep track of whether this is a session history from a sandboxed iframe
5783 // with top level navigation disallowed.
5784 controller_.GoToOffsetInSandboxedFrame(offset,
5785 source->GetFrameTreeNodeId());
5786 } else {
5787 controller_.GoToOffset(offset);
5788 }
5789 }
[email protected]216813952011-05-19 22:21:265790}
5791
Dave Tapuska4c02911b2020-02-14 22:52:075792void WebContentsImpl::OnPageScaleFactorChanged(RenderFrameHostImpl* source,
nicka0ac8382016-12-15 23:59:235793 float page_scale_factor) {
Alexander Timin5fdeff22020-09-08 09:20:375794 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnPageScaleFactorChanged",
5795 "render_frame_host",
5796 base::trace_event::ToTracedValue(source),
5797 "page_scale_factor", page_scale_factor);
mcnee336ea2c2017-05-23 22:50:595798#if !defined(OS_ANDROID)
5799 // While page scale factor is used on mobile, this PageScaleFactorIsOne logic
5800 // is only needed on desktop.
mcnee432e47d2015-11-09 19:37:465801 bool is_one = page_scale_factor == 1.f;
5802 if (is_one != page_scale_factor_is_one_) {
5803 page_scale_factor_is_one_ = is_one;
5804
5805 HostZoomMapImpl* host_zoom_map =
5806 static_cast<HostZoomMapImpl*>(HostZoomMap::GetForWebContents(this));
5807
nicka0ac8382016-12-15 23:59:235808 if (host_zoom_map) {
mcnee432e47d2015-11-09 19:37:465809 host_zoom_map->SetPageScaleFactorIsOneForView(
Dave Tapuska4c02911b2020-02-14 22:52:075810 source->GetProcess()->GetID(),
5811 source->GetRenderViewHost()->GetRoutingID(),
mcnee432e47d2015-11-09 19:37:465812 page_scale_factor_is_one_);
5813 }
5814 }
mcnee336ea2c2017-05-23 22:50:595815#endif // !defined(OS_ANDROID)
mcnee432e47d2015-11-09 19:37:465816
Alexander Timin90c20c32020-08-12 15:28:325817 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5818 observer->OnPageScaleFactorChanged(page_scale_factor);
5819 });
mcnee432e47d2015-11-09 19:37:465820}
5821
W. James MacLean62198672019-06-04 16:46:105822void WebContentsImpl::OnTextAutosizerPageInfoChanged(
Henrique Ferreiroba535472020-04-21 11:38:365823 RenderFrameHostImpl* source,
5824 blink::mojom::TextAutosizerPageInfoPtr page_info) {
Alexander Timin5fdeff22020-09-08 09:20:375825 OPTIONAL_TRACE_EVENT1(
5826 "content", "WebContentsImpl::OnTextAutosizerPageInfoChanged",
5827 "render_frame_host", base::trace_event::ToTracedValue(source));
W. James MacLean62198672019-06-04 16:46:105828 // Keep a copy of |page_info| in case we create a new RenderView before
5829 // the next update.
Henrique Ferreiroba535472020-04-21 11:38:365830 text_autosizer_page_info_.main_frame_width = page_info->main_frame_width;
5831 text_autosizer_page_info_.main_frame_layout_width =
5832 page_info->main_frame_layout_width;
5833 text_autosizer_page_info_.device_scale_adjustment =
5834 page_info->device_scale_adjustment;
Antonio Gomesda7e03d2020-08-05 15:03:085835
5836 auto remote_frames_broadcast_callback = base::BindRepeating(
5837 [](const blink::mojom::TextAutosizerPageInfo& page_info,
5838 RenderFrameProxyHost* proxy_host) {
5839 DCHECK(proxy_host);
5840 proxy_host->GetAssociatedRemoteMainFrame()->UpdateTextAutosizerPageInfo(
5841 page_info.Clone());
5842 },
5843 text_autosizer_page_info_);
5844
5845 frame_tree_.root()->render_manager()->ExecuteRemoteFramesBroadcastMethod(
5846 std::move(remote_frames_broadcast_callback), source->GetSiteInstance());
W. James MacLean62198672019-06-04 16:46:105847}
5848
Kent Tamura8c9e0562018-11-06 07:02:195849void WebContentsImpl::EnumerateDirectory(
5850 RenderFrameHost* render_frame_host,
Kent Tamura3abb32d2020-07-02 00:23:015851 scoped_refptr<FileChooserImpl::FileSelectListenerImpl> listener,
Kent Tamura8c9e0562018-11-06 07:02:195852 const base::FilePath& directory_path) {
Alexander Timin5fdeff22020-09-08 09:20:375853 OPTIONAL_TRACE_EVENT2(
5854 "content", "WebContentsImpl::EnumerateDirectory", "render_frame_host",
5855 base::trace_event::ToTracedValue(render_frame_host), "directory_path",
5856 base::trace_event::ValueToString(directory_path));
Avi Drissman1a55a9d62020-03-10 18:56:455857 // Any explicit focusing of another window while this WebContents is in
5858 // fullscreen can be used to confuse the user, so drop fullscreen.
5859 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
5860 listener->SetFullscreenBlock(std::move(fullscreen_block));
5861
Kent Tamura8c9e0562018-11-06 07:02:195862 if (delegate_)
5863 delegate_->EnumerateDirectory(this, std::move(listener), directory_path);
5864 else
5865 listener->FileSelectionCanceled();
[email protected]3a29a6e2011-08-24 18:26:215866}
5867
Dave Tapuskaf9fc3122019-10-18 19:42:555868void WebContentsImpl::RegisterProtocolHandler(RenderFrameHostImpl* source,
5869 const std::string& protocol,
5870 const GURL& url,
5871 const base::string16& title,
5872 bool user_gesture) {
Alexander Timin5fdeff22020-09-08 09:20:375873 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RegisterProtocolHandler",
5874 "render_frame_host",
5875 base::trace_event::ToTracedValue(source), "protocol",
5876 protocol);
nicka0ac8382016-12-15 23:59:235877 // TODO(nick): Do we need to apply FilterURL to |url|?
[email protected]e5f2de02012-07-20 22:15:435878 if (!delegate_)
5879 return;
5880
Raymes Khoury58373df2019-08-06 06:29:205881 if (!AreValidRegisterProtocolHandlerArguments(
5882 protocol, url, source->GetLastCommittedOrigin())) {
5883 ReceivedBadMessage(source->GetProcess(),
5884 bad_message::REGISTER_PROTOCOL_HANDLER_INVALID_URL);
[email protected]b9535422012-02-09 01:47:595885 return;
Raymes Khoury58373df2019-08-06 06:29:205886 }
[email protected]8f810632013-06-06 22:33:325887
Carlos Caballero8a6c6b72020-07-20 16:56:225888 delegate_->RegisterProtocolHandler(source, protocol, url, user_gesture);
[email protected]7d189022011-08-25 22:54:205889}
5890
Dave Tapuskaf9fc3122019-10-18 19:42:555891void WebContentsImpl::UnregisterProtocolHandler(RenderFrameHostImpl* source,
5892 const std::string& protocol,
5893 const GURL& url,
5894 bool user_gesture) {
Alexander Timin5fdeff22020-09-08 09:20:375895 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::UnregisterProtocolHandler",
5896 "render_frame_host",
5897 base::trace_event::ToTracedValue(source), "protocol",
5898 protocol);
nicka0ac8382016-12-15 23:59:235899 // TODO(nick): Do we need to apply FilterURL to |url|?
[email protected]f5273e52014-07-14 16:30:205900 if (!delegate_)
5901 return;
5902
Raymes Khoury58373df2019-08-06 06:29:205903 if (!AreValidRegisterProtocolHandlerArguments(
5904 protocol, url, source->GetLastCommittedOrigin())) {
5905 ReceivedBadMessage(source->GetProcess(),
5906 bad_message::REGISTER_PROTOCOL_HANDLER_INVALID_URL);
[email protected]f5273e52014-07-14 16:30:205907 return;
Raymes Khoury58373df2019-08-06 06:29:205908 }
[email protected]f5273e52014-07-14 16:30:205909
Carlos Caballero8a6c6b72020-07-20 16:56:225910 delegate_->UnregisterProtocolHandler(source, protocol, url, user_gesture);
[email protected]f5273e52014-07-14 16:30:205911}
5912
Marijn Kruisselbrink7f519672019-02-05 19:12:505913void WebContentsImpl::OnAppCacheAccessed(const GURL& manifest_url,
[email protected]b172aee2012-04-10 17:05:265914 bool blocked_by_policy) {
Alexander Timin5fdeff22020-09-08 09:20:375915 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnAppCacheAccessed");
nicka0ac8382016-12-15 23:59:235916 // TODO(nick): Should we consider |source| here? Should we call FilterURL on
5917 // |manifest_url|?
5918
[email protected]7fc4bbb2011-09-08 21:23:105919 // Notify observers about navigation.
Alexander Timin90c20c32020-08-12 15:28:325920 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5921 observer->AppCacheAccessed(manifest_url, blocked_by_policy);
5922 });
[email protected]7fc4bbb2011-09-08 21:23:105923}
5924
Gyuyoung Kimc5f4ac12020-05-08 10:59:395925void WebContentsImpl::DomOperationResponse(const std::string& json_string) {
Alexander Timin5fdeff22020-09-08 09:20:375926 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DomOperationResponse",
5927 "json_string", json_string);
5928
Gyuyoung Kimc5f4ac12020-05-08 10:59:395929 // TODO(lukasza): The notification below should probably indicate which
5930 // RenderFrameHostImpl the message is coming from. This can enable tests to
5931 // talk to 2 frames at the same time, without being confused which frame a
5932 // given response comes from. See also a corresponding TODO in the
5933 // ExecuteScriptHelper in //content/public/test/browser_test_utils.cc
5934 NotificationService::current()->Notify(
5935 NOTIFICATION_DOM_OPERATION_RESPONSE, Source<WebContents>(this),
5936 Details<const std::string>(&json_string));
5937}
5938
Gyuyoung Kim4c50517842020-06-04 17:50:445939void WebContentsImpl::SavableResourceLinksResponse(
5940 RenderFrameHostImpl* source,
5941 const std::vector<GURL>& resources_list,
5942 blink::mojom::ReferrerPtr referrer,
5943 const std::vector<blink::mojom::SavableSubframePtr>& subframes) {
Alexander Timin5fdeff22020-09-08 09:20:375944 OPTIONAL_TRACE_EVENT1(
5945 "content", "WebContentsImpl::SavableResourceLinksResponse",
5946 "render_frame_host", base::trace_event::ToTracedValue(source));
Gyuyoung Kim4c50517842020-06-04 17:50:445947 save_package_->SavableResourceLinksResponse(source, resources_list,
5948 std::move(referrer), subframes);
5949}
5950
5951void WebContentsImpl::SavableResourceLinksError(RenderFrameHostImpl* source) {
Alexander Timin5fdeff22020-09-08 09:20:375952 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SavableResourceLinksError",
5953 "render_frame_host",
5954 base::trace_event::ToTracedValue(source));
Gyuyoung Kim4c50517842020-06-04 17:50:445955 save_package_->SavableResourceLinksError(source);
5956}
5957
Alexander Timin17edc742020-04-23 18:22:185958void WebContentsImpl::OnServiceWorkerAccessed(
5959 RenderFrameHost* render_frame_host,
5960 const GURL& scope,
5961 AllowServiceWorkerResult allowed) {
Alexander Timin5fdeff22020-09-08 09:20:375962 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnServiceWorkerAccessed",
5963 "render_frame_host",
5964 base::trace_event::ToTracedValue(render_frame_host),
5965 "scope", base::trace_event::ValueToString(scope));
Alexander Timin90c20c32020-08-12 15:28:325966 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5967 observer->OnServiceWorkerAccessed(render_frame_host, scope, allowed);
5968 });
Alexander Timin17edc742020-04-23 18:22:185969}
5970
5971void WebContentsImpl::OnServiceWorkerAccessed(
5972 NavigationHandle* navigation,
5973 const GURL& scope,
5974 AllowServiceWorkerResult allowed) {
Alexander Timin5fdeff22020-09-08 09:20:375975 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnServiceWorkerAccessed",
5976 "navigation_handle", navigation, "scope",
5977 base::trace_event::ValueToString(scope));
Alexander Timin90c20c32020-08-12 15:28:325978 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5979 observer->OnServiceWorkerAccessed(navigation, scope, allowed);
5980 });
Alexander Timin17edc742020-04-23 18:22:185981}
5982
Miyoung Shincb6475a2019-11-09 10:49:455983void WebContentsImpl::OnColorChooserFactoryReceiver(
Julie Jeongeun Kim8e2879e2019-08-06 23:55:205984 mojo::PendingReceiver<blink::mojom::ColorChooserFactory> receiver) {
Alexander Timin5fdeff22020-09-08 09:20:375985 OPTIONAL_TRACE_EVENT0("content",
5986 "WebContentsImpl::OnColorChooserFactoryReceiver");
Julie Jeongeun Kim8e2879e2019-08-06 23:55:205987 color_chooser_factory_receivers_.Add(this, std::move(receiver));
Joel Hockey85b379d2017-12-11 10:42:135988}
5989
5990void WebContentsImpl::OpenColorChooser(
Julie Jeongeun Kim8e2879e2019-08-06 23:55:205991 mojo::PendingReceiver<blink::mojom::ColorChooser> chooser_receiver,
5992 mojo::PendingRemote<blink::mojom::ColorChooserClient> client,
[email protected]8ed16472014-04-11 19:02:485993 SkColor color,
Joel Hockey163835a2017-12-20 11:51:575994 std::vector<blink::mojom::ColorSuggestionPtr> suggestions) {
Alexander Timin5fdeff22020-09-08 09:20:375995 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OpenColorChooser");
Joel Hockey85b379d2017-12-11 10:42:135996 content::ColorChooser* new_color_chooser =
Ivan Kotenkov2c0d2bb32017-11-01 15:41:285997 delegate_ ? delegate_->OpenColorChooser(this, color, suggestions)
5998 : nullptr;
[email protected]820957a2014-01-14 14:56:305999 if (!new_color_chooser)
[email protected]cb805452013-05-22 15:16:216000 return;
[email protected]8ed16472014-04-11 19:02:486001
Joel Hockey85b379d2017-12-11 10:42:136002 color_chooser_.reset();
6003 color_chooser_ = std::make_unique<ColorChooser>(
Julie Jeongeun Kim8e2879e2019-08-06 23:55:206004 new_color_chooser, std::move(chooser_receiver), std::move(client));
[email protected]da8543762012-03-20 08:52:206005}
6006
brettw4b461082016-11-19 18:55:166007#if BUILDFLAG(ENABLE_PLUGINS)
nicka0ac8382016-12-15 23:59:236008void WebContentsImpl::OnPepperInstanceCreated(RenderFrameHostImpl* source,
6009 int32_t pp_instance) {
Alexander Timin5fdeff22020-09-08 09:20:376010 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPepperInstanceCreated",
6011 "render_frame_host",
6012 base::trace_event::ToTracedValue(source));
Alexander Timin90c20c32020-08-12 15:28:326013 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6014 observer->PepperInstanceCreated();
6015 });
nicka0ac8382016-12-15 23:59:236016 pepper_playback_observer_->PepperInstanceCreated(source, pp_instance);
emaxxe70f5e12015-05-29 11:26:006017}
6018
nicka0ac8382016-12-15 23:59:236019void WebContentsImpl::OnPepperInstanceDeleted(RenderFrameHostImpl* source,
6020 int32_t pp_instance) {
Alexander Timin5fdeff22020-09-08 09:20:376021 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPepperInstanceDeleted",
6022 "render_frame_host",
6023 base::trace_event::ToTracedValue(source));
Alexander Timin90c20c32020-08-12 15:28:326024 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6025 observer->PepperInstanceDeleted();
6026 });
nicka0ac8382016-12-15 23:59:236027 pepper_playback_observer_->PepperInstanceDeleted(source, pp_instance);
emaxxe70f5e12015-05-29 11:26:006028}
6029
nicka0ac8382016-12-15 23:59:236030void WebContentsImpl::OnPepperPluginHung(RenderFrameHostImpl* source,
6031 int plugin_child_id,
tommyclie6633ca72014-10-31 00:40:426032 const base::FilePath& path,
6033 bool is_hung) {
Alexander Timin5fdeff22020-09-08 09:20:376034 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPepperPluginHung",
6035 "render_frame_host",
6036 base::trace_event::ToTracedValue(source));
Steven Holte95922222018-09-14 20:06:236037 UMA_HISTOGRAM_COUNTS_1M("Pepper.PluginHung", 1);
tommyclie6633ca72014-10-31 00:40:426038
Alexander Timin90c20c32020-08-12 15:28:326039 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6040 observer->PluginHungStatusChanged(plugin_child_id, path, is_hung);
6041 });
tommyclie6633ca72014-10-31 00:40:426042}
6043
nicka0ac8382016-12-15 23:59:236044void WebContentsImpl::OnPepperStartsPlayback(RenderFrameHostImpl* source,
6045 int32_t pp_instance) {
Alexander Timin5fdeff22020-09-08 09:20:376046 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPepperStartsPlayback",
6047 "render_frame_host",
6048 base::trace_event::ToTracedValue(source));
nicka0ac8382016-12-15 23:59:236049 pepper_playback_observer_->PepperStartsPlayback(source, pp_instance);
zqzhang181047e62016-07-01 13:37:176050}
6051
nicka0ac8382016-12-15 23:59:236052void WebContentsImpl::OnPepperStopsPlayback(RenderFrameHostImpl* source,
6053 int32_t pp_instance) {
Alexander Timin5fdeff22020-09-08 09:20:376054 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPepperStopsPlayback",
6055 "render_frame_host",
6056 base::trace_event::ToTracedValue(source));
nicka0ac8382016-12-15 23:59:236057 pepper_playback_observer_->PepperStopsPlayback(source, pp_instance);
zqzhang181047e62016-07-01 13:37:176058}
6059
nicka0ac8382016-12-15 23:59:236060void WebContentsImpl::OnPluginCrashed(RenderFrameHostImpl* source,
6061 const base::FilePath& plugin_path,
tommyclie6633ca72014-10-31 00:40:426062 base::ProcessId plugin_pid) {
Alexander Timin5fdeff22020-09-08 09:20:376063 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPluginCrashed",
6064 "render_frame_host",
6065 base::trace_event::ToTracedValue(source));
nicka0ac8382016-12-15 23:59:236066 // TODO(nick): Eliminate the |plugin_pid| parameter, which can't be trusted,
Gyuyoung Kim26c7bc92020-04-29 00:53:006067 // and is only used by WebTestControlHost.
Alexander Timin90c20c32020-08-12 15:28:326068 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6069 observer->PluginCrashed(plugin_path, plugin_pid);
6070 });
tommyclie6633ca72014-10-31 00:40:426071}
6072
brettw4b461082016-11-19 18:55:166073#endif // BUILDFLAG(ENABLE_PLUGINS)
[email protected]19be7a62012-10-01 23:03:376074
Miyoung Shin5709ab02020-02-19 06:50:416075void WebContentsImpl::UpdateFaviconURL(
6076 RenderFrameHost* source,
6077 std::vector<blink::mojom::FaviconURLPtr> candidates) {
Alexander Timin5fdeff22020-09-08 09:20:376078 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::UpdateFaviconURL",
6079 "render_frame_host",
6080 base::trace_event::ToTracedValue(source));
lukasza178ff092017-06-07 23:39:506081 // Ignore favicons for non-main frame.
6082 if (source->GetParent()) {
6083 NOTREACHED();
6084 return;
6085 }
6086
pkotwiczf9bc20592015-04-21 18:57:066087 // We get updated favicon URLs after the page stops loading. If a cross-site
6088 // navigation occurs while a page is still loading, the initial page
6089 // may stop loading and send us updated favicon URLs after the navigation
6090 // for the new page has committed.
lukasza178ff092017-06-07 23:39:506091 if (!source->IsCurrent())
pkotwiczf9bc20592015-04-21 18:57:066092 return;
6093
Miyoung Shin5709ab02020-02-19 06:50:416094 favicon_urls_ = std::move(candidates);
Mounir Lamouri7b4a1f232019-12-23 16:32:106095
Alexander Timin90c20c32020-08-12 15:28:326096 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6097 observer->DidUpdateFaviconURL(source, favicon_urls_);
6098 });
[email protected]795c28972012-12-06 06:13:396099}
6100
qinmin72e8bd02016-10-21 19:35:376101void WebContentsImpl::SetIsOverlayContent(bool is_overlay_content) {
Alexander Timin5fdeff22020-09-08 09:20:376102 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetIsOverlayContent",
6103 "is_overlay_content", is_overlay_content);
qinmin72e8bd02016-10-21 19:35:376104 is_overlay_content_ = is_overlay_content;
6105}
6106
Albert J. Wongfb64e142018-10-16 01:10:456107void WebContentsImpl::DidFirstVisuallyNonEmptyPaint(
6108 RenderViewHostImpl* source) {
Alexander Timin5fdeff22020-09-08 09:20:376109 OPTIONAL_TRACE_EVENT1("content",
6110 "WebContentsImpl::DidFirstVisuallyNonEmptyPaint",
6111 "render_view_host", source);
nicka0ac8382016-12-15 23:59:236112 // TODO(nick): When this is ported to FrameHostMsg_, we should only listen if
6113 // |source| is the main frame.
Alexander Timin90c20c32020-08-12 15:28:326114 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6115 observer->DidFirstVisuallyNonEmptyPaint();
6116 });
Carlos Caballero1215f882019-10-29 15:58:436117 if (source->theme_color() != last_sent_theme_color_) {
yusufod41c5f92015-03-06 00:14:286118 // Theme color should have updated by now if there was one.
Alexander Timin90c20c32020-08-12 15:28:326119 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6120 observer->DidChangeThemeColor();
6121 });
Carlos Caballero1215f882019-10-29 15:58:436122 last_sent_theme_color_ = source->theme_color();
yusufod41c5f92015-03-06 00:14:286123 }
Alan Cutterd73a15d92020-08-21 07:12:456124
6125 if (source->background_color() != last_sent_background_color_) {
6126 // Background color should have updated by now if there was one.
6127 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6128 observer->OnBackgroundColorChanged();
6129 });
6130 last_sent_background_color_ = source->background_color();
6131 }
[email protected]9f268072013-11-07 00:02:156132}
[email protected]d9030b82013-07-19 08:26:066133
Kevin McNee068c3eb2020-04-03 18:24:196134bool WebContentsImpl::IsPortal() {
Adithya Srinivasan46b8a792019-02-01 14:47:236135 return portal();
6136}
6137
Kevin McNee94ea52f52020-06-23 17:42:066138WebContentsImpl* WebContentsImpl::GetPortalHostWebContents() {
6139 return portal() ? portal()->GetPortalHostContents() : nullptr;
6140}
6141
[email protected]17e286e2013-03-01 23:29:396142void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
Alexander Timin5fdeff22020-09-08 09:20:376143 OPTIONAL_TRACE_EVENT0("content",
6144 "WebContentsImpl::NotifyBeforeFormRepostWarningShow");
Alexander Timin90c20c32020-08-12 15:28:326145 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6146 observer->BeforeFormRepostWarningShow();
6147 });
[email protected]17e286e2013-03-01 23:29:396148}
6149
[email protected]ec6c05f2013-10-23 18:41:576150void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
Alexander Timin5fdeff22020-09-08 09:20:376151 OPTIONAL_TRACE_EVENT0(
6152 "content", "WebContentsImpl::ActivateAndShowRepostFormWarningDialog");
[email protected]ec6c05f2013-10-23 18:41:576153 Activate();
6154 if (delegate_)
6155 delegate_->ShowRepostFormWarningDialog(this);
6156}
6157
[email protected]b4c84012014-04-28 19:51:106158bool WebContentsImpl::HasAccessedInitialDocument() {
6159 return has_accessed_initial_document_;
6160}
6161
afakhry6f0c1ec22016-07-14 13:55:136162void WebContentsImpl::UpdateTitleForEntry(NavigationEntry* entry,
[email protected]fcf75d42013-12-03 20:11:266163 const base::string16& title) {
Alexander Timin5fdeff22020-09-08 09:20:376164 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::UpdateTitleForEntry",
6165 "title", base::trace_event::ValueToString(title));
[email protected]fcf75d42013-12-03 20:11:266166 base::string16 final_title;
Avi Drissman93002212017-09-27 03:20:526167 base::TrimWhitespace(title, base::TRIM_ALL, &final_title);
[email protected]420ae012009-04-24 05:16:326168
[email protected]987fc3a2011-05-26 14:18:096169 // If a page is created via window.open and never navigated,
6170 // there will be no navigation entry. In this situation,
[email protected]73eb2602012-02-09 19:50:556171 // |page_title_when_no_navigation_entry_| will be used for page title.
[email protected]987fc3a2011-05-26 14:18:096172 if (entry) {
[email protected]36fc0392011-12-25 03:59:516173 if (final_title == entry->GetTitle())
afakhry6f0c1ec22016-07-14 13:55:136174 return; // Nothing changed, don't bother.
[email protected]420ae012009-04-24 05:16:326175
[email protected]36fc0392011-12-25 03:59:516176 entry->SetTitle(final_title);
Avi Drissman93002212017-09-27 03:20:526177
6178 // The title for display may differ from the title just set; grab it.
6179 final_title = entry->GetTitleForDisplay();
[email protected]987fc3a2011-05-26 14:18:096180 } else {
6181 if (page_title_when_no_navigation_entry_ == final_title)
afakhry6f0c1ec22016-07-14 13:55:136182 return; // Nothing changed, don't bother.
[email protected]987fc3a2011-05-26 14:18:096183
6184 page_title_when_no_navigation_entry_ = final_title;
6185 }
[email protected]420ae012009-04-24 05:16:326186
[email protected]420ae012009-04-24 05:16:326187 // Lastly, set the title for the view.
[email protected]790e2fd2011-09-21 20:28:236188 view_->SetPageTitle(final_title);
[email protected]420ae012009-04-24 05:16:326189
Alexander Timin90c20c32020-08-12 15:28:326190 observers_.ForEachObserver(
6191 [&](WebContentsObserver* observer) { observer->TitleWasSet(entry); });
afakhry6f0c1ec22016-07-14 13:55:136192 // Broadcast notifications when the UI should be updated.
6193 if (entry == controller_.GetEntryAtOffset(0))
6194 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE);
[email protected]420ae012009-04-24 05:16:326195}
6196
fdegansa696e5112015-04-17 01:57:596197void WebContentsImpl::SendChangeLoadProgress() {
Alexander Timin5fdeff22020-09-08 09:20:376198 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SendChangeLoadProgress",
6199 "load_progress", frame_tree_.load_progress());
[email protected]960b0372014-05-19 18:01:006200 loading_last_progress_update_ = base::TimeTicks::Now();
Alexander Timin90c20c32020-08-12 15:28:326201 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6202 observer->LoadProgressChanged(frame_tree_.load_progress());
6203 });
[email protected]960b0372014-05-19 18:01:006204}
6205
6206void WebContentsImpl::ResetLoadProgressState() {
Alexander Timin5fdeff22020-09-08 09:20:376207 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ResetLoadProgressState");
fdegans1d16355162015-03-26 11:58:346208 frame_tree_.ResetLoadProgress();
[email protected]960b0372014-05-19 18:01:006209 loading_weak_factory_.InvalidateWeakPtrs();
6210 loading_last_progress_update_ = base::TimeTicks();
6211}
6212
clamy44e84ce2016-02-22 15:38:256213// Notifies the RenderWidgetHost instance about the fact that the page is
6214// loading, or done loading.
6215void WebContentsImpl::LoadingStateChanged(bool to_different_document,
clamy44e84ce2016-02-22 15:38:256216 LoadNotificationDetails* details) {
Nate Chapin22ea6592019-03-05 22:29:026217 if (is_being_destroyed_)
6218 return;
clamy44e84ce2016-02-22 15:38:256219
6220 bool is_loading = IsLoading();
6221
Alexander Timin5fdeff22020-09-08 09:20:376222 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::LoadingStateChanged",
6223 "is_loading", is_loading);
6224
clamy44e84ce2016-02-22 15:38:256225 if (!is_loading) {
6226 load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
6227 base::string16());
6228 load_state_host_.clear();
6229 upload_size_ = 0;
6230 upload_position_ = 0;
6231 }
6232
6233 GetRenderManager()->SetIsLoading(is_loading);
6234
6235 waiting_for_response_ = is_loading;
6236 is_load_to_different_document_ = to_different_document;
6237
6238 if (delegate_)
6239 delegate_->LoadingStateChanged(this, to_different_document);
6240 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD);
6241
6242 std::string url = (details ? details->url.possibly_invalid_spec() : "NULL");
6243 if (is_loading) {
6244 TRACE_EVENT_ASYNC_BEGIN2("browser,navigation", "WebContentsImpl Loading",
6245 this, "URL", url, "Main FrameTreeNode id",
6246 GetFrameTree()->root()->frame_tree_node_id());
Alexander Timin90c20c32020-08-12 15:28:326247 observers_.ForEachObserver(
6248 [&](WebContentsObserver* observer) { observer->DidStartLoading(); });
clamy44e84ce2016-02-22 15:38:256249 } else {
6250 TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
6251 this, "URL", url);
Alexander Timin90c20c32020-08-12 15:28:326252 observers_.ForEachObserver(
6253 [&](WebContentsObserver* observer) { observer->DidStopLoading(); });
clamy44e84ce2016-02-22 15:38:256254 }
6255
6256 // TODO(avi): Remove. http://crbug.com/170921
6257 int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP;
6258 NotificationDetails det = NotificationService::NoDetails();
6259 if (details)
6260 det = Details<LoadNotificationDetails>(details);
6261 NotificationService::current()->Notify(
6262 type, Source<NavigationController>(&controller_), det);
6263}
6264
danakja0bce4c952020-05-12 20:40:286265void WebContentsImpl::NotifyViewSwapped(RenderViewHost* old_view,
6266 RenderViewHost* new_view) {
Alexander Timin5fdeff22020-09-08 09:20:376267 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::NotifyViewSwapped",
6268 "old_view", old_view, "new_view", new_view);
danakja0bce4c952020-05-12 20:40:286269 DCHECK_NE(old_view, new_view);
[email protected]420ae012009-04-24 05:16:326270 // After sending out a swap notification, we need to send a disconnect
6271 // notification so that clients that pick up a pointer to |this| can NULL the
6272 // pointer. See Bug 1230284.
6273 notify_disconnection_ = true;
Alexander Timin90c20c32020-08-12 15:28:326274 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6275 observer->RenderViewHostChanged(old_view, new_view);
6276 });
danakja0bce4c952020-05-12 20:40:286277 view_->RenderViewHostChanged(old_view, new_view);
Jinsuk Kimdc5284c22018-07-11 02:22:066278
Lucas Furukawa Gadanif9ea4fc2018-08-03 23:57:136279 // If this is an inner WebContents that has swapped views, we need to reattach
6280 // it to its outer WebContents.
6281 if (node_.outer_web_contents())
6282 ReattachToOuterWebContentsFrame();
6283
[email protected]7a846df2012-09-20 19:17:396284 // Ensure that the associated embedder gets cleared after a RenderViewHost
6285 // gets swapped, so we don't reuse the same embedder next time a
6286 // RenderViewHost is attached to this WebContents.
6287 RemoveBrowserPluginEmbedder();
[email protected]420ae012009-04-24 05:16:326288}
6289
danakja0bce4c952020-05-12 20:40:286290void WebContentsImpl::NotifyFrameSwapped(RenderFrameHost* old_frame,
6291 RenderFrameHost* new_frame,
Jinsuk Kim895b2c52018-07-03 06:49:166292 bool is_main_frame) {
Alexander Timin5fdeff22020-09-08 09:20:376293 TRACE_EVENT2("content", "WebContentsImpl::NotifyFrameSwapped", "old_frame",
6294 base::trace_event::ToTracedValue(old_frame), "new_frame",
6295 base::trace_event::ToTracedValue(new_frame));
Bo Liu168c8642017-08-28 18:26:026296#if defined(OS_ANDROID)
danakja0bce4c952020-05-12 20:40:286297 // Copy importance from |old_frame| if |new_frame| is a main frame.
6298 if (old_frame && !new_frame->GetParent()) {
6299 RenderWidgetHostImpl* old_widget =
6300 static_cast<RenderFrameHostImpl*>(old_frame)->GetRenderWidgetHost();
6301 RenderWidgetHostImpl* new_widget =
6302 static_cast<RenderFrameHostImpl*>(new_frame)->GetRenderWidgetHost();
6303 new_widget->SetImportance(old_widget->importance());
Bo Liu7c6779e92017-08-16 02:02:286304 }
Bo Liu168c8642017-08-28 18:26:026305#endif
Alexander Timin90c20c32020-08-12 15:28:326306 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6307 observer->RenderFrameHostChanged(old_frame, new_frame);
6308 });
[email protected]02d7b6e2014-06-24 21:01:506309}
6310
[email protected]da7a7182013-09-06 08:11:116311// TODO(avi): Remove this entire function because this notification is already
6312// covered by two observer functions. http://crbug.com/170921
[email protected]b172aee2012-04-10 17:05:266313void WebContentsImpl::NotifyDisconnected() {
Alexander Timin5fdeff22020-09-08 09:20:376314 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::NotifyDisconnected");
[email protected]420ae012009-04-24 05:16:326315 if (!notify_disconnection_)
6316 return;
6317
6318 notify_disconnection_ = false;
[email protected]8ff00d72012-10-23 19:12:216319 NotificationService::current()->Notify(
6320 NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
6321 Source<WebContents>(this),
6322 NotificationService::NoDetails());
[email protected]420ae012009-04-24 05:16:326323}
6324
[email protected]cbb1ef592013-06-05 19:49:466325void WebContentsImpl::NotifyNavigationEntryCommitted(
6326 const LoadCommittedDetails& load_details) {
Alexander Timin5fdeff22020-09-08 09:20:376327 OPTIONAL_TRACE_EVENT0("content",
6328 "WebContentsImpl::NotifyNavigationEntryCommitted");
Alexander Timin90c20c32020-08-12 15:28:326329 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6330 observer->NavigationEntryCommitted(load_details);
6331 });
[email protected]cbb1ef592013-06-05 19:49:466332}
6333
Sam McNally5c087a32017-08-25 01:46:146334void WebContentsImpl::NotifyNavigationEntryChanged(
6335 const EntryChangedDetails& change_details) {
Alexander Timin5fdeff22020-09-08 09:20:376336 OPTIONAL_TRACE_EVENT0("content",
6337 "WebContentsImpl::NotifyNavigationEntryChanged");
Alexander Timin90c20c32020-08-12 15:28:326338 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6339 observer->NavigationEntryChanged(change_details);
6340 });
Sam McNally5c087a32017-08-25 01:46:146341}
6342
6343void WebContentsImpl::NotifyNavigationListPruned(
6344 const PrunedDetails& pruned_details) {
Alexander Timin5fdeff22020-09-08 09:20:376345 OPTIONAL_TRACE_EVENT0("content",
6346 "WebContentsImpl::NotifyNavigationListPruned");
Alexander Timin90c20c32020-08-12 15:28:326347 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6348 observer->NavigationListPruned(pruned_details);
6349 });
Sam McNally5c087a32017-08-25 01:46:146350}
6351
Christian Dullweber1af31e62018-02-22 11:49:486352void WebContentsImpl::NotifyNavigationEntriesDeleted() {
Alexander Timin5fdeff22020-09-08 09:20:376353 OPTIONAL_TRACE_EVENT0("content",
6354 "WebContentsImpl::NotifyNavigationEntriesDeleted");
Alexander Timin90c20c32020-08-12 15:28:326355 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6356 observer->NavigationEntriesDeleted();
6357 });
Christian Dullweber1af31e62018-02-22 11:49:486358}
6359
rockotf62002a2016-09-15 00:08:596360void WebContentsImpl::OnAssociatedInterfaceRequest(
6361 RenderFrameHost* render_frame_host,
6362 const std::string& interface_name,
6363 mojo::ScopedInterfaceEndpointHandle handle) {
Alexander Timin5fdeff22020-09-08 09:20:376364 OPTIONAL_TRACE_EVENT2(
6365 "content", "WebContentsImpl::OnAssociatedInterfaceRequest",
6366 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host),
6367 "interface_name", interface_name);
Julie Jeongeun Kim7d0986172019-12-04 03:17:256368 auto it = receiver_sets_.find(interface_name);
6369 if (it != receiver_sets_.end())
6370 it->second->OnReceiverForFrame(render_frame_host, std::move(handle));
rockotf62002a2016-09-15 00:08:596371}
6372
Ben Goodger9e24929e2017-07-21 03:13:406373void WebContentsImpl::OnInterfaceRequest(
6374 RenderFrameHost* render_frame_host,
6375 const std::string& interface_name,
6376 mojo::ScopedMessagePipeHandle* interface_pipe) {
Alexander Timin5fdeff22020-09-08 09:20:376377 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnInterfaceRequest",
6378 "render_frame_host",
6379 base::trace_event::ToTracedValue(render_frame_host),
6380 "interface_name", interface_name);
Alexander Timin90c20c32020-08-12 15:28:326381 for (auto& observer : observers_.observer_list()) {
Ben Goodger9e24929e2017-07-21 03:13:406382 observer.OnInterfaceRequestFromFrame(render_frame_host, interface_name,
6383 interface_pipe);
6384 if (!interface_pipe->is_valid())
6385 break;
6386 }
6387}
6388
Varun Khaneja5da94302019-06-25 04:48:106389void WebContentsImpl::OnDidBlockNavigation(
6390 const GURL& blocked_url,
6391 const GURL& initiator_url,
Abhijeet Kandalkarde7348e2020-01-13 06:06:546392 blink::mojom::NavigationBlockedReason reason) {
Alexander Timin5fdeff22020-09-08 09:20:376393 OPTIONAL_TRACE_EVENT1(
6394 "content", "WebContentsImpl::OnDidBlockNavigation", "details",
6395 base::trace_event::TracedValue::Build(
6396 {{"blocked_url", base::trace_event::ValueToString(blocked_url)},
6397 {"initiator_url", base::trace_event::ValueToString(initiator_url)},
6398 {"reason", base::trace_event::ValueToString(reason)}}));
Nicolas Dossou-gbetebcab2472017-09-09 12:28:406399 if (delegate_)
Varun Khaneja5da94302019-06-25 04:48:106400 delegate_->OnDidBlockNavigation(this, blocked_url, initiator_url, reason);
Nicolas Dossou-gbetebcab2472017-09-09 12:28:406401}
6402
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416403const GURL& WebContentsImpl::GetMainFrameLastCommittedURL() {
[email protected]c31a84802014-04-03 15:55:496404 return GetLastCommittedURL();
6405}
6406
[email protected]b849847b2013-12-10 21:57:586407void WebContentsImpl::RenderFrameCreated(RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:376408 TRACE_EVENT1("content", "WebContentsImpl::RenderFrameCreated",
6409 "render_frame_host", render_frame_host);
Alexander Timin90c20c32020-08-12 15:28:326410 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6411 observer->RenderFrameCreated(render_frame_host);
6412 });
dmazzonif8a31042016-12-03 00:52:136413 UpdateAccessibilityModeOnFrame(render_frame_host);
clamy91b7abf2016-03-24 15:17:456414
Becca Hughesd11d6502018-07-31 17:01:286415 if (display_cutout_host_impl_)
6416 display_cutout_host_impl_->RenderFrameCreated(render_frame_host);
6417
clamy91b7abf2016-03-24 15:17:456418 if (!render_frame_host->IsRenderFrameLive() || render_frame_host->GetParent())
6419 return;
6420
6421 NavigationEntry* entry = controller_.GetPendingEntry();
6422 if (entry && entry->IsViewSourceMode()) {
6423 // Put the renderer in view source mode.
Dave Tapuska3c05e1c2019-11-27 18:34:186424 static_cast<RenderFrameHostImpl*>(render_frame_host)
6425 ->GetAssociatedLocalFrame()
6426 ->EnableViewSourceMode();
clamy91b7abf2016-03-24 15:17:456427 }
[email protected]b849847b2013-12-10 21:57:586428}
6429
6430void WebContentsImpl::RenderFrameDeleted(RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:376431 TRACE_EVENT1("content", "WebContentsImpl::RenderFrameDeleted",
6432 "render_frame_host",
6433 base::trace_event::ToTracedValue(render_frame_host));
yilkal172da772019-11-06 22:49:076434 if (IsBeingDestroyed() && !render_frame_host->GetParent() &&
6435 first_navigation_completed_ &&
Hajime Hoshibbc509c2020-04-06 08:55:086436 !render_frame_host->IsInBackForwardCache()) {
yilkal796e89e2019-10-02 23:58:286437 // Main frame has been deleted because WebContents is being destroyed.
Rakina Zata Amni74627df2019-10-15 02:03:176438 // Note that we aren't recording this here when the main frame is in the
6439 // back-forward cache because that means we've actually already navigated
6440 // away from it (and we got to this point because the WebContents is
yilkal172da772019-11-06 22:49:076441 // deleted), which means |max_loaded_frame_count_| is already overwritten.
6442 // The |max_loaded_frame_count_| value will instead be recorded from within
6443 // |WebContentsImpl::DidFinishNavigation()|.
6444 RecordMaxFrameCountUMA(max_loaded_frame_count_);
yilkal796e89e2019-10-02 23:58:286445 }
6446
Alexander Timin90c20c32020-08-12 15:28:326447 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6448 observer->RenderFrameDeleted(render_frame_host);
6449 });
zqzhang7b6f4f02016-12-07 22:10:226450#if BUILDFLAG(ENABLE_PLUGINS)
6451 pepper_playback_observer_->RenderFrameDeleted(render_frame_host);
6452#endif
Becca Hughesfd5d8f892018-06-14 18:23:366453
Becca Hughesd11d6502018-07-31 17:01:286454 if (display_cutout_host_impl_)
6455 display_cutout_host_impl_->RenderFrameDeleted(render_frame_host);
6456
Becca Hughesfd5d8f892018-06-14 18:23:366457 // Remove any fullscreen state that the frame has stored.
6458 FullscreenStateChanged(render_frame_host, false /* is_fullscreen */);
[email protected]b849847b2013-12-10 21:57:586459}
6460
[email protected]a09d53ce2014-01-31 00:46:426461void WebContentsImpl::ShowContextMenu(RenderFrameHost* render_frame_host,
6462 const ContextMenuParams& params) {
Alexander Timin5fdeff22020-09-08 09:20:376463 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ShowContextMenu",
6464 "render_frame_host",
6465 base::trace_event::ToTracedValue(render_frame_host));
avie9fd8722017-04-10 16:17:586466 // If a renderer fires off a second command to show a context menu before the
6467 // first context menu is closed, just ignore it. https://crbug.com/707534
ekaramadf6750aa2017-06-06 18:29:426468 if (showing_context_menu_)
avie9fd8722017-04-10 16:17:586469 return;
6470
[email protected]077e704b2014-05-23 19:24:106471 ContextMenuParams context_menu_params(params);
[email protected]a09d53ce2014-01-31 00:46:426472 // Allow WebContentsDelegates to handle the context menu operation first.
Joel Klinghed0ea22ea2019-02-20 22:04:226473 if (delegate_ &&
6474 delegate_->HandleContextMenu(render_frame_host, context_menu_params))
[email protected]a09d53ce2014-01-31 00:46:426475 return;
6476
[email protected]077e704b2014-05-23 19:24:106477 render_view_host_delegate_view_->ShowContextMenu(render_frame_host,
6478 context_menu_params);
[email protected]a09d53ce2014-01-31 00:46:426479}
6480
Avi Drissman4891b852018-09-25 18:12:586481namespace {
6482// Normalizes the line endings: \r\n -> \n, lone \r -> \n.
6483base::string16 NormalizeLineBreaks(const base::string16& source) {
6484 static const base::NoDestructor<base::string16> kReturnNewline(
6485 base::ASCIIToUTF16("\r\n"));
6486 static const base::NoDestructor<base::string16> kReturn(
6487 base::ASCIIToUTF16("\r"));
6488 static const base::NoDestructor<base::string16> kNewline(
6489 base::ASCIIToUTF16("\n"));
6490
6491 std::vector<base::StringPiece16> pieces;
6492
6493 for (const auto& rn_line : base::SplitStringPieceUsingSubstr(
6494 source, *kReturnNewline, base::KEEP_WHITESPACE,
6495 base::SPLIT_WANT_ALL)) {
6496 auto r_lines = base::SplitStringPieceUsingSubstr(
6497 rn_line, *kReturn, base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
6498 std::move(std::begin(r_lines), std::end(r_lines),
6499 std::back_inserter(pieces));
6500 }
6501
6502 return base::JoinString(pieces, *kNewline);
6503}
6504} // namespace
6505
Dave Tapuskacdf545cc2020-01-23 18:38:526506void WebContentsImpl::RunJavaScriptDialog(
6507 RenderFrameHost* render_frame_host,
6508 const base::string16& message,
6509 const base::string16& default_prompt,
6510 JavaScriptDialogType dialog_type,
6511 JavaScriptDialogCallback response_callback) {
Alexander Timin5fdeff22020-09-08 09:20:376512 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RunJavaScriptDialog",
6513 "render_frame_host",
6514 base::trace_event::ToTracedValue(render_frame_host));
Avi Drissman2ccbb402018-03-20 21:11:366515 // Ensure that if showing a dialog is the first thing that a page does, that
6516 // the contents of the previous page aren't shown behind it. This is required
6517 // because showing a dialog freezes the renderer, so no frames will be coming
6518 // from it. https://crbug.com/823353
6519 auto* render_widget_host_impl =
6520 static_cast<RenderFrameHostImpl*>(render_frame_host)
6521 ->GetRenderWidgetHost();
6522 if (render_widget_host_impl)
6523 render_widget_host_impl->ForceFirstFrameAfterNavigationTimeout();
6524
avi0720b02e2017-06-13 03:22:136525 // Running a dialog causes an exit to webpage-initiated fullscreen.
6526 // http://crbug.com/728276
Avi Drissman1a55a9d62020-03-10 18:56:456527 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
avi0720b02e2017-06-13 03:22:136528
Avi Drissman1a55a9d62020-03-10 18:56:456529 auto callback =
6530 base::BindOnce(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
6531 render_frame_host->GetProcess()->GetID(),
6532 render_frame_host->GetRoutingID(),
6533 std::move(response_callback), std::move(fullscreen_block));
Pavel Feldman3c1842b2017-08-02 05:00:166534
Pavel Feldman3c1842b2017-08-02 05:00:166535 std::vector<protocol::PageHandler*> page_handlers =
6536 protocol::PageHandler::EnabledForWebContents(this);
6537
Pavel Feldmanfab3cb62017-10-05 01:02:016538 if (delegate_)
6539 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
6540
Charlie Reis96077362019-07-04 00:34:046541 // While a JS message dialog is showing, defer commits in this WebContents.
6542 javascript_dialog_navigation_deferrer_ =
6543 std::make_unique<JavaScriptDialogNavigationDeferrer>();
6544
Carlos IL07f282f2020-05-15 22:58:296545 // Suppress JavaScript dialogs when requested.
6546 bool should_suppress = delegate_ && delegate_->ShouldSuppressDialogs(this);
Pavel Feldman1c587bc52018-04-04 21:16:056547 bool has_non_devtools_handlers = delegate_ && dialog_manager_;
6548 bool has_handlers = page_handlers.size() || has_non_devtools_handlers;
Pavel Feldmanfab3cb62017-10-05 01:02:016549 bool suppress_this_message = should_suppress || !has_handlers;
6550
6551 if (suppress_this_message) {
Avi Drissmane04d3992017-10-05 15:11:366552 std::move(callback).Run(true, false, base::string16());
Pavel Feldman3c1842b2017-08-02 05:00:166553 return;
6554 }
6555
6556 scoped_refptr<CloseDialogCallbackWrapper> wrapper =
Avi Drissmane04d3992017-10-05 15:11:366557 new CloseDialogCallbackWrapper(std::move(callback));
Pavel Feldman3c1842b2017-08-02 05:00:166558
6559 is_showing_javascript_dialog_ = true;
6560
Avi Drissman4891b852018-09-25 18:12:586561 base::string16 normalized_message = NormalizeLineBreaks(message);
6562
Pavel Feldman3c1842b2017-08-02 05:00:166563 for (auto* handler : page_handlers) {
Avi Drissmane04d3992017-10-05 15:11:366564 handler->DidRunJavaScriptDialog(
Avi Drissman4891b852018-09-25 18:12:586565 render_frame_host->GetLastCommittedURL(), normalized_message,
6566 default_prompt, dialog_type, has_non_devtools_handlers,
Avi Drissmane04d3992017-10-05 15:11:366567 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
Pavel Feldman3c1842b2017-08-02 05:00:166568 }
6569
6570 if (dialog_manager_) {
[email protected]87de04b02014-04-08 22:14:496571 dialog_manager_->RunJavaScriptDialog(
Avi Drissman4891b852018-09-25 18:12:586572 this, render_frame_host, dialog_type, normalized_message,
6573 default_prompt,
Avi Drissmane04d3992017-10-05 15:11:366574 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false),
6575 &suppress_this_message);
[email protected]87de04b02014-04-08 22:14:496576 }
6577
6578 if (suppress_this_message) {
6579 // If we are suppressing messages, just reply as if the user immediately
6580 // pressed "Cancel", passing true to |dialog_was_suppressed|.
Avi Drissmane04d3992017-10-05 15:11:366581 wrapper->Run(true, false, base::string16());
[email protected]87de04b02014-04-08 22:14:496582 }
[email protected]87de04b02014-04-08 22:14:496583}
6584
6585void WebContentsImpl::RunBeforeUnloadConfirm(
[email protected]39f2f9252014-05-03 00:54:016586 RenderFrameHost* render_frame_host,
[email protected]87de04b02014-04-08 22:14:496587 bool is_reload,
Dave Tapuskacdf545cc2020-01-23 18:38:526588 JavaScriptDialogCallback response_callback) {
Alexander Timin5fdeff22020-09-08 09:20:376589 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RunBeforeUnloadConfirm",
6590 "render_frame_host",
6591 base::trace_event::ToTracedValue(render_frame_host),
6592 "is_reload", is_reload);
Avi Drissman2ccbb402018-03-20 21:11:366593 // Ensure that if showing a dialog is the first thing that a page does, that
6594 // the contents of the previous page aren't shown behind it. This is required
6595 // because showing a dialog freezes the renderer, so no frames will be coming
6596 // from it. https://crbug.com/823353
6597 auto* render_widget_host_impl =
6598 static_cast<RenderFrameHostImpl*>(render_frame_host)
6599 ->GetRenderWidgetHost();
6600 if (render_widget_host_impl)
6601 render_widget_host_impl->ForceFirstFrameAfterNavigationTimeout();
6602
avi0720b02e2017-06-13 03:22:136603 // Running a dialog causes an exit to webpage-initiated fullscreen.
6604 // http://crbug.com/728276
Avi Drissman1a55a9d62020-03-10 18:56:456605 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
avi0720b02e2017-06-13 03:22:136606
[email protected]39f2f9252014-05-03 00:54:016607 RenderFrameHostImpl* rfhi =
6608 static_cast<RenderFrameHostImpl*>(render_frame_host);
[email protected]87de04b02014-04-08 22:14:496609 if (delegate_)
6610 delegate_->WillRunBeforeUnloadConfirm();
6611
Avi Drissman1a55a9d62020-03-10 18:56:456612 auto callback =
6613 base::BindOnce(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
6614 render_frame_host->GetProcess()->GetID(),
6615 render_frame_host->GetRoutingID(),
6616 std::move(response_callback), std::move(fullscreen_block));
Pavel Feldman3c1842b2017-08-02 05:00:166617
Pavel Feldman3c1842b2017-08-02 05:00:166618 std::vector<protocol::PageHandler*> page_handlers =
6619 protocol::PageHandler::EnabledForWebContents(this);
6620
Pavel Feldmanfab3cb62017-10-05 01:02:016621 if (delegate_)
6622 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
6623
Charlie Reis96077362019-07-04 00:34:046624 // While a JS beforeunload dialog is showing, defer commits in this
6625 // WebContents.
6626 javascript_dialog_navigation_deferrer_ =
6627 std::make_unique<JavaScriptDialogNavigationDeferrer>();
6628
Sreeja Kamishettyf352e302020-06-10 13:21:246629 bool should_suppress = !rfhi->IsCurrent() ||
Tarun Bansalc209b742019-12-24 06:53:256630 (delegate_ && delegate_->ShouldSuppressDialogs(this));
Pavel Feldman1c587bc52018-04-04 21:16:056631 bool has_non_devtools_handlers = delegate_ && dialog_manager_;
6632 bool has_handlers = page_handlers.size() || has_non_devtools_handlers;
Pavel Feldmanfab3cb62017-10-05 01:02:016633 if (should_suppress || !has_handlers) {
Avi Drissmane04d3992017-10-05 15:11:366634 std::move(callback).Run(false, true, base::string16());
[email protected]87de04b02014-04-08 22:14:496635 return;
6636 }
6637
6638 is_showing_before_unload_dialog_ = true;
Pavel Feldman3c1842b2017-08-02 05:00:166639
6640 scoped_refptr<CloseDialogCallbackWrapper> wrapper =
Avi Drissmane04d3992017-10-05 15:11:366641 new CloseDialogCallbackWrapper(std::move(callback));
Pavel Feldman3c1842b2017-08-02 05:00:166642
6643 GURL frame_url = rfhi->GetLastCommittedURL();
6644 for (auto* handler : page_handlers) {
Avi Drissmane04d3992017-10-05 15:11:366645 handler->DidRunBeforeUnloadConfirm(
Pavel Feldman1c587bc52018-04-04 21:16:056646 frame_url, has_non_devtools_handlers,
Avi Drissmane04d3992017-10-05 15:11:366647 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
Pavel Feldman3c1842b2017-08-02 05:00:166648 }
6649
6650 if (dialog_manager_) {
Avi Drissmane04d3992017-10-05 15:11:366651 dialog_manager_->RunBeforeUnloadDialog(
Avi Drissmanff9ed752017-11-28 21:18:126652 this, render_frame_host, is_reload,
Avi Drissmane04d3992017-10-05 15:11:366653 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
Pavel Feldman3c1842b2017-08-02 05:00:166654 }
[email protected]87de04b02014-04-08 22:14:496655}
6656
Kent Tamurac260c9a2018-09-14 09:10:566657void WebContentsImpl::RunFileChooser(
6658 RenderFrameHost* render_frame_host,
Kent Tamura3abb32d2020-07-02 00:23:016659 scoped_refptr<FileChooserImpl::FileSelectListenerImpl> listener,
Kent Tamurac260c9a2018-09-14 09:10:566660 const blink::mojom::FileChooserParams& params) {
Alexander Timin5fdeff22020-09-08 09:20:376661 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RunFileChooser",
6662 "render_frame_host",
6663 base::trace_event::ToTracedValue(render_frame_host));
Avi Drissman3d41e7712018-08-27 21:18:086664 // Any explicit focusing of another window while this WebContents is in
6665 // fullscreen can be used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:456666 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
6667 listener->SetFullscreenBlock(std::move(fullscreen_block));
Avi Drissman3d41e7712018-08-27 21:18:086668
naskoada75b22016-06-11 16:09:466669 if (delegate_)
Kent Tamura512a27e2018-10-04 00:49:326670 delegate_->RunFileChooser(render_frame_host, std::move(listener), params);
6671 else
6672 listener->FileSelectionCanceled();
naskoada75b22016-06-11 16:09:466673}
6674
[email protected]a86c0e962013-12-17 17:10:396675WebContents* WebContentsImpl::GetAsWebContents() {
6676 return this;
6677}
6678
mcnee336ea2c2017-05-23 22:50:596679#if !defined(OS_ANDROID)
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416680double WebContentsImpl::GetPendingPageZoomLevel() {
wjmaclean64951902016-04-29 20:59:126681 NavigationEntry* pending_entry = GetController().GetPendingEntry();
6682 if (!pending_entry)
6683 return HostZoomMap::GetZoomLevel(this);
6684
6685 GURL url = pending_entry->GetURL();
6686 return HostZoomMap::GetForWebContents(this)->GetZoomLevelForHostAndScheme(
6687 url.scheme(), net::GetHostOrSpecFromURL(url));
6688}
mcnee336ea2c2017-05-23 22:50:596689#endif // !defined(OS_ANDROID)
wjmaclean64951902016-04-29 20:59:126690
qinmin72e8bd02016-10-21 19:35:376691bool WebContentsImpl::HideDownloadUI() const {
6692 return is_overlay_content_;
6693}
6694
mlamouri5cd9ae82017-02-18 11:05:096695bool WebContentsImpl::HasPersistentVideo() const {
6696 return has_persistent_video_;
6697}
6698
Ian Vollick5d5c37f2019-06-19 22:50:576699bool WebContentsImpl::IsSpatialNavigationDisabled() const {
6700 return is_spatial_navigation_disabled_;
6701}
6702
Albert J. Wong65fe64d2019-09-20 02:48:146703RenderFrameHostImpl* WebContentsImpl::GetPendingMainFrame() {
clamy610c63b32017-12-22 15:05:186704 return GetRenderManager()->speculative_frame_host();
Alex Moshchuk27caae82017-09-11 23:11:186705}
6706
mlamourie52c1b542017-02-23 14:57:506707bool WebContentsImpl::HasActiveEffectivelyFullscreenVideo() const {
6708 return media_web_contents_observer_->HasActiveEffectivelyFullscreenVideo();
6709}
6710
François Beaufortad6c5232018-02-26 11:00:446711bool WebContentsImpl::IsPictureInPictureAllowedForFullscreenVideo() const {
6712 return media_web_contents_observer_
6713 ->IsPictureInPictureAllowedForFullscreenVideo();
6714}
6715
ekaramada110f642016-12-21 19:47:286716bool WebContentsImpl::IsFocusedElementEditable() {
6717 RenderFrameHostImpl* frame = GetFocusedFrame();
6718 return frame && frame->has_focused_editable_element();
6719}
6720
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416721bool WebContentsImpl::IsShowingContextMenu() {
ekaramadf6750aa2017-06-06 18:29:426722 return showing_context_menu_;
6723}
6724
6725void WebContentsImpl::SetShowingContextMenu(bool showing) {
Alexander Timin5fdeff22020-09-08 09:20:376726 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetShowingContextMenu",
6727 "showing", showing);
6728
ekaramadf6750aa2017-06-06 18:29:426729 DCHECK_NE(showing_context_menu_, showing);
6730 showing_context_menu_ = showing;
6731
6732 if (auto* view = GetRenderWidgetHostView()) {
6733 // Notify the main frame's RWHV to run the platform-specific code, if any.
6734 static_cast<RenderWidgetHostViewBase*>(view)->SetShowingContextMenu(
6735 showing);
6736 }
6737}
6738
ekaramada110f642016-12-21 19:47:286739void WebContentsImpl::ClearFocusedElement() {
Alexander Timin5fdeff22020-09-08 09:20:376740 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ClearFocusedElement");
ekaramada110f642016-12-21 19:47:286741 if (auto* frame = GetFocusedFrame())
6742 frame->ClearFocusedElement();
6743}
6744
danakj77eb7e82020-01-09 19:38:466745bool WebContentsImpl::IsNeverComposited() {
[email protected]7912e822014-04-16 02:37:036746 if (!delegate_)
6747 return false;
danakj77eb7e82020-01-09 19:38:466748 return delegate_->IsNeverComposited(this);
[email protected]7912e822014-04-16 02:37:036749}
6750
[email protected]5a3bdf52012-05-24 15:12:576751RenderViewHostDelegateView* WebContentsImpl::GetDelegateView() {
6752 return render_view_host_delegate_view_;
[email protected]420ae012009-04-24 05:16:326753}
6754
Mario Sanchez Prada0bd8b8c2020-10-21 17:49:236755const blink::RendererPreferences& WebContentsImpl::GetRendererPrefs() const {
[email protected]840b1512009-07-21 16:53:466756 return renderer_preferences_;
[email protected]80d96fa2009-06-10 22:34:516757}
6758
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166759RenderFrameHostImpl* WebContentsImpl::GetOuterWebContentsFrame() {
6760 if (GetOuterDelegateFrameTreeNodeId() ==
6761 FrameTreeNode::kFrameTreeNodeInvalidId) {
6762 return nullptr;
6763 }
6764
6765 FrameTreeNode* outer_node =
6766 FrameTreeNode::GloballyFindByID(GetOuterDelegateFrameTreeNodeId());
6767 // The outer node should be in the outer WebContents.
6768 DCHECK_EQ(outer_node->frame_tree(), GetOuterWebContents()->GetFrameTree());
Alexander Timin381e7e182020-04-28 19:04:036769 return outer_node->parent();
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166770}
6771
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416772WebContentsImpl* WebContentsImpl::GetOuterWebContents() {
Lucas Furukawa Gadani105de1e812018-05-31 19:38:396773 return node_.outer_web_contents();
avallee0206f782016-07-28 18:55:336774}
6775
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166776std::vector<WebContents*> WebContentsImpl::GetInnerWebContents() {
6777 std::vector<WebContents*> all_inner_contents;
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166778 const auto& inner_contents = node_.GetInnerWebContents();
6779 all_inner_contents.insert(all_inner_contents.end(), inner_contents.begin(),
6780 inner_contents.end());
6781 return all_inner_contents;
6782}
6783
Jeremy Roman7e70bf92020-01-07 23:23:586784WebContentsImpl* WebContentsImpl::GetResponsibleWebContents() {
6785 // Iteratively ask delegates which other contents is responsible until a fixed
6786 // point is found.
6787 WebContentsImpl* contents = this;
6788 while (WebContentsDelegate* delegate = contents->GetDelegate()) {
6789 auto* responsible_contents = static_cast<WebContentsImpl*>(
6790 delegate->GetResponsibleWebContents(contents));
6791 if (responsible_contents == contents)
6792 break;
6793 contents = responsible_contents;
6794 }
6795 return contents;
6796}
6797
avallee0206f782016-07-28 18:55:336798WebContentsImpl* WebContentsImpl::GetFocusedWebContents() {
lfg601233692017-03-06 22:45:446799 return GetOutermostWebContents()->node_.focused_web_contents();
avallee0206f782016-07-28 18:55:336800}
6801
Lukasz Anforowicz2cd231bf2020-10-02 19:13:206802void WebContentsImpl::SetFocusToLocationBar() {
6803 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetFocusToLocationBar");
6804 if (delegate_)
6805 delegate_->SetFocusToLocationBar();
6806}
6807
avallee9993fca2016-11-17 06:16:506808bool WebContentsImpl::ContainsOrIsFocusedWebContents() {
6809 for (WebContentsImpl* focused_contents = GetFocusedWebContents();
6810 focused_contents;
6811 focused_contents = focused_contents->GetOuterWebContents()) {
6812 if (focused_contents == this)
6813 return true;
6814 }
6815
6816 return false;
6817}
6818
W. James MacLean9437b5bf2019-12-06 17:33:446819void WebContentsImpl::RemoveBrowserPluginEmbedder() {
Alexander Timin5fdeff22020-09-08 09:20:376820 OPTIONAL_TRACE_EVENT0("content",
6821 "WebContentsImpl::RemoveBrowserPluginEmbedder");
W. James MacLean9437b5bf2019-12-06 17:33:446822 browser_plugin_embedder_.reset();
6823}
6824
avallee0206f782016-07-28 18:55:336825WebContentsImpl* WebContentsImpl::GetOutermostWebContents() {
6826 WebContentsImpl* root = this;
6827 while (root->GetOuterWebContents())
6828 root = root->GetOuterWebContents();
6829 return root;
6830}
6831
avalleed68cdd12017-06-21 22:07:276832void WebContentsImpl::FocusOuterAttachmentFrameChain() {
Alexander Timin5fdeff22020-09-08 09:20:376833 OPTIONAL_TRACE_EVENT0("content",
6834 "WebContentsImpl::FocusOuterAttachmentFrameChain");
avalleed68cdd12017-06-21 22:07:276835 WebContentsImpl* outer_contents = GetOuterWebContents();
6836 if (!outer_contents)
6837 return;
6838
6839 FrameTreeNode* outer_node =
6840 FrameTreeNode::GloballyFindByID(GetOuterDelegateFrameTreeNodeId());
6841 outer_contents->frame_tree_.SetFocusedFrame(outer_node, nullptr);
6842
6843 // For a browser initiated focus change, let embedding renderer know of the
6844 // change. Otherwise, if the currently focused element is just across a
6845 // process boundary in focus order, it will not be possible to move across
6846 // that boundary. This is because the target element will already be focused
6847 // (that renderer was not notified) and drop the event.
6848 if (GetRenderManager()->GetProxyToOuterDelegate())
6849 GetRenderManager()->GetProxyToOuterDelegate()->SetFocusedFrame();
6850
6851 outer_contents->FocusOuterAttachmentFrameChain();
6852}
6853
Sean Toppingbbc4a2bd2019-01-30 02:16:146854void WebContentsImpl::InnerWebContentsCreated(WebContents* inner_web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:376855 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::InnerWebContentsCreated");
Alexander Timin90c20c32020-08-12 15:28:326856 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6857 observer->InnerWebContentsCreated(inner_web_contents);
6858 });
Sean Toppingbbc4a2bd2019-01-30 02:16:146859}
6860
Jeremy Roman03ce13ce2020-05-29 22:16:576861void WebContentsImpl::InnerWebContentsAttached(
6862 WebContents* inner_web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:376863 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::InnerWebContentsDetached");
Jeremy Roman03ce13ce2020-05-29 22:16:576864 if (inner_web_contents->IsCurrentlyAudible())
6865 OnAudioStateChanged();
6866}
6867
6868void WebContentsImpl::InnerWebContentsDetached(
6869 WebContents* inner_web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:376870 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::InnerWebContentsCreated");
Jeremy Roman03ce13ce2020-05-29 22:16:576871 if (!is_being_destroyed_)
6872 OnAudioStateChanged();
6873}
6874
[email protected]b172aee2012-04-10 17:05:266875void WebContentsImpl::RenderViewCreated(RenderViewHost* render_view_host) {
Alexander Timin5fdeff22020-09-08 09:20:376876 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderViewCreated",
6877 "render_view_host", render_view_host);
[email protected]86f98a22013-03-20 14:35:006878 if (delegate_)
[email protected]e85165c642014-06-10 14:34:316879 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
[email protected]a6b73c62013-02-11 23:05:086880
[email protected]8ff00d72012-10-23 19:12:216881 NotificationService::current()->Notify(
6882 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
6883 Source<WebContents>(this),
6884 Details<RenderViewHost>(render_view_host));
[email protected]420ae012009-04-24 05:16:326885
Alexander Timin90c20c32020-08-12 15:28:326886 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6887 observer->RenderViewCreated(render_view_host);
6888 });
Joel Einbinder848001c2017-09-19 21:39:316889 if (delegate_)
6890 RenderFrameDevToolsAgentHost::WebContentsCreated(this);
[email protected]420ae012009-04-24 05:16:326891}
6892
[email protected]b172aee2012-04-10 17:05:266893void WebContentsImpl::RenderViewReady(RenderViewHost* rvh) {
Alexander Timin5fdeff22020-09-08 09:20:376894 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderViewReady",
6895 "render_view_host", rvh);
[email protected]151a63d2011-12-20 22:32:526896 if (rvh != GetRenderViewHost()) {
[email protected]420ae012009-04-24 05:16:326897 // Don't notify the world, since this came from a renderer in the
6898 // background.
6899 return;
6900 }
6901
dmazzoni62111452017-04-28 23:46:556902 RenderWidgetHostViewBase* rwhv =
6903 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
6904 if (rwhv)
6905 rwhv->SetMainFrameAXTreeID(GetMainFrame()->GetAXTreeID());
6906
[email protected]da7a7182013-09-06 08:11:116907 notify_disconnection_ = true;
[email protected]da7a7182013-09-06 08:11:116908
[email protected]be1f56ab2011-12-22 06:55:316909 bool was_crashed = IsCrashed();
[email protected]443b80e2010-12-14 00:42:236910 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING, 0);
[email protected]9d8a4642009-07-29 17:25:306911
6912 // Restore the focus to the tab (otherwise the focus will be on the top
6913 // window).
[email protected]484ae5912010-09-29 19:16:146914 if (was_crashed && !FocusLocationBarByDefault() &&
6915 (!delegate_ || delegate_->ShouldFocusPageAfterCrash())) {
[email protected]f3615f02013-02-26 06:09:066916 view_->Focus();
[email protected]484ae5912010-09-29 19:16:146917 }
[email protected]32ded2212011-11-10 18:51:436918
Alexander Timin90c20c32020-08-12 15:28:326919 observers_.ForEachObserver(
6920 [&](WebContentsObserver* observer) { observer->RenderViewReady(); });
Jinsuk Kim895b2c52018-07-03 06:49:166921 view_->RenderViewReady();
[email protected]420ae012009-04-24 05:16:326922}
6923
[email protected]ec6a7eb2013-04-22 17:34:226924void WebContentsImpl::RenderViewTerminated(RenderViewHost* rvh,
6925 base::TerminationStatus status,
6926 int error_code) {
Alexander Timin5fdeff22020-09-08 09:20:376927 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RenderViewTerminated",
6928 "render_view_host", rvh, "status",
6929 static_cast<int>(status));
[email protected]151a63d2011-12-20 22:32:526930 if (rvh != GetRenderViewHost()) {
[email protected]420ae012009-04-24 05:16:326931 // The pending page's RenderViewHost is gone.
6932 return;
6933 }
[email protected]2fcdcc32014-03-05 02:14:076934 // Ensure fullscreen mode is exited in the |delegate_| since a crashed
6935 // renderer may not have made a clean exit.
Avi Drissman97aef042020-06-30 21:04:486936 if (IsFullscreen())
bokanece34a82016-01-28 19:49:466937 ExitFullscreenMode(false);
[email protected]2fcdcc32014-03-05 02:14:076938
Jennifer Apacibleb4b972a2018-06-07 04:41:026939 // Ensure any video in Picture-in-Picture is exited in the |delegate_| since
6940 // a crashed renderer may not have made a clean exit.
6941 if (HasPictureInPictureVideo())
6942 ExitPictureInPicture();
6943
[email protected]698191dc2014-02-25 01:06:136944 // Cancel any visible dialogs so they are not left dangling over the sad tab.
creis89a0f782015-05-27 16:13:176945 CancelActiveAndPendingDialogs();
[email protected]698191dc2014-02-25 01:06:136946
dalecurtis3d1e1302017-02-20 22:33:256947 audio_stream_monitor_.RenderProcessGone(rvh->GetProcess()->GetID());
6948
[email protected]960b0372014-05-19 18:01:006949 // Reset the loading progress. TODO(avi): What does it mean to have a
6950 // "renderer crash" when there is more than one renderer process serving a
6951 // webpage? Once this function is called at a more granular frame level, we
6952 // probably will need to more granularly reset the state here.
6953 ResetLoadProgressState();
clamy44e84ce2016-02-22 15:38:256954 NotifyDisconnected();
6955 SetIsCrashed(status, error_code);
[email protected]960b0372014-05-19 18:01:006956
Alexander Timin5fdeff22020-09-08 09:20:376957 TRACE_EVENT0("content",
6958 "Dispatching WebContentsObserver::RenderViewTerminated");
Alexander Timin90c20c32020-08-12 15:28:326959 // Some observers might destroy WebContents in RenderViewTerminated.
6960 base::WeakPtr<WebContentsImpl> weak_ptr = weak_factory_.GetWeakPtr();
6961 auto crashed_status = GetCrashedStatus();
6962 for (auto& observer : observers_.observer_list()) {
6963 observer.RenderProcessGone(crashed_status);
6964 if (!weak_ptr)
6965 return;
6966 }
6967
6968 // |this| might have been deleted. Do not add code here.
[email protected]420ae012009-04-24 05:16:326969}
6970
[email protected]b172aee2012-04-10 17:05:266971void WebContentsImpl::RenderViewDeleted(RenderViewHost* rvh) {
Alexander Timin5fdeff22020-09-08 09:20:376972 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderViewDeleted",
6973 "render_view_host", rvh);
Alexander Timin90c20c32020-08-12 15:28:326974 observers_.ForEachObserver(
6975 [&](WebContentsObserver* observer) { observer->RenderViewDeleted(rvh); });
[email protected]2e4633c2009-07-09 16:58:066976}
6977
Lukasz Anforowiczfd707142018-02-07 19:46:136978void WebContentsImpl::ClearTargetURL() {
Alexander Timin5fdeff22020-09-08 09:20:376979 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ClearTargetURL");
Mario Sanchez Pradadffbe66e2020-09-07 12:01:086980 frame_that_set_last_target_url_ = nullptr;
Lukasz Anforowiczfd707142018-02-07 19:46:136981 if (delegate_)
6982 delegate_->UpdateTargetURL(this, GURL());
6983}
6984
[email protected]b172aee2012-04-10 17:05:266985void WebContentsImpl::Close(RenderViewHost* rvh) {
Alexander Timin5fdeff22020-09-08 09:20:376986 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::Close", "render_view_host",
6987 rvh);
Avi Drissman7c57be72020-07-29 20:09:466988#if defined(OS_MAC)
[email protected]07707302009-11-06 00:50:296989 // The UI may be in an event-tracking loop, such as between the
6990 // mouse-down and mouse-up in text selection or a button click.
6991 // Defer the close until after tracking is complete, so that we
6992 // don't free objects out from under the UI.
[email protected]07707302009-11-06 00:50:296993 // TODO(shess): This could get more fine-grained. For instance,
6994 // closing a tab in another window while selecting text in the
6995 // current window's Omnibox should be just fine.
Christopher Cameron9ae31e0d2019-03-01 20:01:196996 if (view_->CloseTabAfterEventTrackingIfNeeded())
[email protected]07707302009-11-06 00:50:296997 return;
[email protected]60780f412013-02-25 16:34:106998#endif
[email protected]07707302009-11-06 00:50:296999
[email protected]420ae012009-04-24 05:16:327000 // Ignore this if it comes from a RenderViewHost that we aren't showing.
[email protected]151a63d2011-12-20 22:32:527001 if (delegate_ && rvh == GetRenderViewHost())
[email protected]6934a702011-12-20 00:04:517002 delegate_->CloseContents(this);
[email protected]420ae012009-04-24 05:16:327003}
7004
Avi Drissman014dec72018-06-07 02:34:017005void WebContentsImpl::RequestSetBounds(const gfx::Rect& new_bounds) {
Alexander Timin5fdeff22020-09-08 09:20:377006 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::RequestSetBounds");
Mike Wassermandabad612020-08-13 04:26:277007 if (!delegate_)
7008 return;
7009
7010 // Members of |new_bounds| may be 0 to indicate uninitialized values for newly
7011 // opened windows, even if the |GetContainerBounds()| inner rect is correct.
7012 // TODO(crbug.com/897300): Plumb values as specified; fallback on outer rect.
7013 auto bounds = new_bounds;
7014 if (bounds.IsEmpty())
7015 bounds.set_size(GetContainerBounds().size());
7016
7017 // Only requests from the main frame, not subframes, should reach this code.
Mike Wassermanb6bc0152020-08-25 22:46:207018 int64_t display_id = AdjustRequestedWindowBounds(&bounds, GetMainFrame());
7019
7020 // Drop fullscreen when placing a WebContents to prohibit deceptive behavior.
7021 // Only drop fullscreen on the specific destination display, which is known.
7022 // This supports sites using cross-screen window placement capabilities to
7023 // retain fullscreen and place a window on another screen.
7024 ForSecurityDropFullscreen(display_id).RunAndReset();
7025
Mike Wassermandabad612020-08-13 04:26:277026 delegate_->SetContentsBounds(this, bounds);
[email protected]420ae012009-04-24 05:16:327027}
7028
fdegansa696e5112015-04-17 01:57:597029void WebContentsImpl::DidStartLoading(FrameTreeNode* frame_tree_node,
[email protected]e3b10d12014-03-28 16:06:097030 bool to_different_document) {
Alexander Timin5fdeff22020-09-08 09:20:377031 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DidStartLoading",
7032 "frame_tree_node", frame_tree_node);
Evan Stadec3b26022017-07-14 19:50:247033 LoadingStateChanged(frame_tree_node->IsMainFrame() && to_different_document,
Carlos IL07f282f2020-05-15 22:58:297034 nullptr);
dmazzonibf8cec42015-02-08 08:28:087035
Xiyuan Xia2a66b112018-12-06 15:52:167036 // Reset the focus state from DidStartNavigation to false if a new load starts
7037 // afterward, in case loading logic triggers a FocusLocationBarByDefault call.
7038 should_focus_location_bar_by_default_ = false;
Ian Prestcdd843d2020-01-28 18:59:587039
7040 // Notify accessibility that the user is navigating away from the
7041 // current document.
7042 // TODO(domfarolino, dmazzoni): Do this using WebContentsObserver. See
7043 // https://crbug.com/981271.
7044 BrowserAccessibilityManager* manager =
7045 frame_tree_node->current_frame_host()->browser_accessibility_manager();
7046 if (manager)
7047 manager->UserIsNavigatingAway();
[email protected]420ae012009-04-24 05:16:327048}
7049
fdegansc73eec22015-03-19 14:47:547050void WebContentsImpl::DidStopLoading() {
Alexander Timin5fdeff22020-09-08 09:20:377051 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidStopLoading");
dcheng59716272016-04-09 05:19:087052 std::unique_ptr<LoadNotificationDetails> details;
[email protected]420ae012009-04-24 05:16:327053
[email protected]9595fd82013-04-19 21:28:497054 // Use the last committed entry rather than the active one, in case a
7055 // pending entry has been created.
7056 NavigationEntry* entry = controller_.GetLastCommittedEntry();
7057
[email protected]420ae012009-04-24 05:16:327058 // An entry may not exist for a stop when loading an initial blank page or
7059 // if an iframe injected by script into a blank page finishes loading.
7060 if (entry) {
Fergal Daly55b6d722020-09-11 07:56:337061 details = std::make_unique<LoadNotificationDetails>(
7062 entry->GetVirtualURL(), &controller_,
7063 controller_.GetCurrentEntryIndex());
[email protected]420ae012009-04-24 05:16:327064 }
7065
Carlos IL07f282f2020-05-15 22:58:297066 LoadingStateChanged(true, details.get());
[email protected]420ae012009-04-24 05:16:327067}
7068
fdegansa696e5112015-04-17 01:57:597069void WebContentsImpl::DidChangeLoadProgress() {
Alexander Timin5fdeff22020-09-08 09:20:377070 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidChangeLoadProgress");
Nate Chapin22ea6592019-03-05 22:29:027071 if (is_being_destroyed_)
7072 return;
fdegansa696e5112015-04-17 01:57:597073 double load_progress = frame_tree_.load_progress();
7074
7075 // The delegate is notified immediately for the first and last updates. Also,
7076 // since the message loop may be pretty busy when a page is loaded, it might
7077 // not execute a posted task in a timely manner so the progress report is sent
7078 // immediately if enough time has passed.
7079 base::TimeDelta min_delay =
7080 base::TimeDelta::FromMilliseconds(kMinimumDelayBetweenLoadingUpdatesMS);
7081 bool delay_elapsed = loading_last_progress_update_.is_null() ||
7082 base::TimeTicks::Now() - loading_last_progress_update_ > min_delay;
7083
7084 if (load_progress == 0.0 || load_progress == 1.0 || delay_elapsed) {
7085 // If there is a pending task to send progress, it is now obsolete.
7086 loading_weak_factory_.InvalidateWeakPtrs();
7087
7088 // Notify the load progress change.
7089 SendChangeLoadProgress();
7090
7091 // Clean-up the states if needed.
7092 if (load_progress == 1.0)
7093 ResetLoadProgressState();
7094 return;
7095 }
7096
7097 if (loading_weak_factory_.HasWeakPtrs())
7098 return;
7099
skyostil95082a62015-06-05 19:53:077100 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
tzike2aca992017-09-05 08:50:547101 FROM_HERE,
7102 base::BindOnce(&WebContentsImpl::SendChangeLoadProgress,
7103 loading_weak_factory_.GetWeakPtr()),
fdegansa696e5112015-04-17 01:57:597104 min_delay);
7105}
7106
avid6d88b912017-01-13 00:16:007107std::vector<std::unique_ptr<NavigationThrottle>>
7108WebContentsImpl::CreateThrottlesForNavigation(
clamycbf524d42016-09-27 12:48:357109 NavigationHandle* navigation_handle) {
Alexander Timin5fdeff22020-09-08 09:20:377110 OPTIONAL_TRACE_EVENT1("content",
7111 "WebContentsImpl::CreateThrottlesForNavigation",
7112 "navigation", navigation_handle);
Charlie Reis96077362019-07-04 00:34:047113 auto throttles = GetContentClient()->browser()->CreateThrottlesForNavigation(
clamycbf524d42016-09-27 12:48:357114 navigation_handle);
Charlie Reis96077362019-07-04 00:34:047115
7116 // This is not a normal place to be adding a throttle. However, in the case
7117 // javascript dialogs, related logic is present in the web_contents/ layer,
7118 // and the purpose of the throttle is to ensure that navigation commits are
7119 // deferred for the entire WebContents. Most throttles are either added by
7120 // the embederrer outside of content/, or are per-frame and added by
7121 // NavigationThrottleRunner.
7122 std::unique_ptr<content::NavigationThrottle> dialog_throttle =
7123 JavaScriptDialogNavigationThrottle::MaybeCreateThrottleFor(
7124 navigation_handle);
7125 if (dialog_throttle)
7126 throttles.push_back(std::move(dialog_throttle));
7127
7128 return throttles;
clamycbf524d42016-09-27 12:48:357129}
7130
clamy1e5574e2016-09-29 16:48:447131std::unique_ptr<NavigationUIData> WebContentsImpl::GetNavigationUIData(
7132 NavigationHandle* navigation_handle) {
Alexander Timin5fdeff22020-09-08 09:20:377133 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GetNavigationUIData");
clamy1e5574e2016-09-29 16:48:447134 return GetContentClient()->browser()->GetNavigationUIData(navigation_handle);
7135}
7136
W. James MacLean1c40862c2020-04-27 21:05:577137void WebContentsImpl::RegisterExistingOriginToPreventOptInIsolation(
W. James MacLeanb70fab82020-05-01 18:51:147138 const url::Origin& origin,
7139 NavigationRequest* navigation_request_to_exclude) {
Alexander Timin5fdeff22020-09-08 09:20:377140 OPTIONAL_TRACE_EVENT2(
7141 "content",
7142 "WebContentsImpl::RegisterExistingOriginToPreventOptInIsolation",
7143 "origin", base::trace_event::ValueToString(origin),
7144 "navigation_request_to_exclude", navigation_request_to_exclude);
W. James MacLean1c40862c2020-04-27 21:05:577145 // Note: This function can be made static if we ever need call it without
7146 // a WebContentsImpl instance, in which case we can use a wrapper to
7147 // implement the override from NavigatorDelegate.
7148 for (WebContentsImpl* web_contents : GetAllWebContents()) {
7149 web_contents->controller_.RegisterExistingOriginToPreventOptInIsolation(
7150 origin);
W. James MacLeanb70fab82020-05-01 18:51:147151 // Walk the frame tree to pick up any frames without FrameNavigationEntries.
7152 // * Some frames won't have FrameNavigationEntries (Issues 524208, 608402).
7153 // * Some pending navigations won't have NavigationEntries.
7154 web_contents->GetFrameTree()->RegisterExistingOriginToPreventOptInIsolation(
7155 origin, navigation_request_to_exclude);
W. James MacLean1c40862c2020-04-27 21:05:577156 }
7157}
7158
pdr15f5b5b2017-06-20 00:58:007159void WebContentsImpl::DidCancelLoading() {
Alexander Timin5fdeff22020-09-08 09:20:377160 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidCancelLoading");
pdr15f5b5b2017-06-20 00:58:007161 controller_.DiscardNonCommittedEntries();
7162
7163 // Update the URL display.
7164 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
7165}
7166
[email protected]59167c22013-06-03 18:07:327167void WebContentsImpl::DidAccessInitialDocument() {
Alexander Timin5fdeff22020-09-08 09:20:377168 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidAccessInitialDocument");
[email protected]b4c84012014-04-28 19:51:107169 has_accessed_initial_document_ = true;
7170
[email protected]d1371bf8e2014-04-19 03:26:247171 // We may have left a failed browser-initiated navigation in the address bar
7172 // to let the user edit it and try again. Clear it now that content might
7173 // show up underneath it.
7174 if (!IsLoading() && controller_.GetPendingEntry())
avi45a72532015-04-07 21:01:457175 controller_.DiscardPendingEntry(false);
[email protected]d1371bf8e2014-04-19 03:26:247176
[email protected]59167c22013-06-03 18:07:327177 // Update the URL display.
thestigc4cac8f2014-09-04 21:17:507178 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
[email protected]59167c22013-06-03 18:07:327179}
7180
alexmosbe2f4c32015-03-10 02:30:237181void WebContentsImpl::DidChangeName(RenderFrameHost* render_frame_host,
7182 const std::string& name) {
Alexander Timin5fdeff22020-09-08 09:20:377183 OPTIONAL_TRACE_EVENT2(
7184 "content", "WebContentsImpl::DidChangeName", "render_frame_host",
7185 base::trace_event::ToTracedValue(render_frame_host), "name", name);
Alexander Timin90c20c32020-08-12 15:28:327186 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7187 observer->FrameNameChanged(render_frame_host, name);
7188 });
alexmosbe2f4c32015-03-10 02:30:237189}
7190
John Delaneyedd8d6c2019-01-25 00:23:577191void WebContentsImpl::DidReceiveFirstUserActivation(
7192 RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:377193 OPTIONAL_TRACE_EVENT1(
7194 "content", "WebContentsImpl::DidReceiveFirstUserActivation",
7195 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host));
Alexander Timin90c20c32020-08-12 15:28:327196 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7197 observer->FrameReceivedFirstUserActivation(render_frame_host);
7198 });
John Delaneyedd8d6c2019-01-25 00:23:577199}
7200
John Delaney0146a742019-01-25 19:25:287201void WebContentsImpl::DidChangeDisplayState(RenderFrameHost* render_frame_host,
7202 bool is_display_none) {
Alexander Timin5fdeff22020-09-08 09:20:377203 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::DidChangeDisplayState",
7204 "render_frame_host",
7205 base::trace_event::ToTracedValue(render_frame_host),
7206 "is_display_none", is_display_none);
Alexander Timin90c20c32020-08-12 15:28:327207 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7208 observer->FrameDisplayStateChanged(render_frame_host, is_display_none);
7209 });
John Delaney0146a742019-01-25 19:25:287210}
7211
7212void WebContentsImpl::FrameSizeChanged(RenderFrameHost* render_frame_host,
7213 const gfx::Size& frame_size) {
Alexander Timin5fdeff22020-09-08 09:20:377214 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::FrameSizeChanged",
7215 "render_frame_host",
7216 base::trace_event::ToTracedValue(render_frame_host));
Alexander Timin90c20c32020-08-12 15:28:327217 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7218 observer->FrameSizeChanged(render_frame_host, frame_size);
7219 });
John Delaney0146a742019-01-25 19:25:287220}
7221
[email protected]39f2f9252014-05-03 00:54:017222void WebContentsImpl::DocumentOnLoadCompleted(
[email protected]50279492014-05-05 23:24:297223 RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:377224 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DocumentOnLoadCompleted",
7225 "render_frame_host",
7226 base::trace_event::ToTracedValue(render_frame_host));
falken52a56e32016-12-08 05:02:407227 ShowInsecureLocalhostWarningIfNeeded();
7228
Alexander Timindd0fa0c52019-11-06 13:03:377229 GetRenderViewHost()->DocumentOnLoadCompletedInMainFrame();
7230
Alexander Timin90c20c32020-08-12 15:28:327231 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7232 observer->DocumentOnLoadCompletedInMainFrame();
7233 });
[email protected]6578fef2013-10-14 02:35:097234
7235 // TODO(avi): Remove. http://crbug.com/170921
[email protected]8ff00d72012-10-23 19:12:217236 NotificationService::current()->Notify(
7237 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
7238 Source<WebContents>(this),
[email protected]50279492014-05-05 23:24:297239 NotificationService::NoDetails());
[email protected]25497492010-09-11 15:15:087240}
7241
creis8eb8ef22015-11-04 22:51:387242void WebContentsImpl::UpdateStateForFrame(RenderFrameHost* render_frame_host,
Miyoung Shin5d77f72072020-10-09 15:14:207243 const blink::PageState& page_state) {
Alexander Timin5fdeff22020-09-08 09:20:377244 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::UpdateStateForFrame",
7245 "render_frame_host",
7246 base::trace_event::ToTracedValue(render_frame_host));
creis8eb8ef22015-11-04 22:51:387247 // The state update affects the last NavigationEntry associated with the given
7248 // |render_frame_host|. This may not be the last committed NavigationEntry (as
7249 // in the case of an UpdateState from a frame being swapped out). We track
7250 // which entry this is in the RenderFrameHost's nav_entry_id.
7251 RenderFrameHostImpl* rfhi =
7252 static_cast<RenderFrameHostImpl*>(render_frame_host);
7253 NavigationEntryImpl* entry =
7254 controller_.GetEntryWithUniqueID(rfhi->nav_entry_id());
7255 if (!entry)
7256 return;
7257
7258 FrameNavigationEntry* frame_entry =
7259 entry->GetFrameEntry(rfhi->frame_tree_node());
7260 if (!frame_entry)
7261 return;
7262
creisd06a9422015-11-11 03:08:457263 // The SiteInstance might not match if we do a cross-process navigation with
7264 // replacement (e.g., auto-subframe), in which case the swap out of the old
7265 // RenderFrameHost runs in the background after the old FrameNavigationEntry
7266 // has already been replaced and destroyed.
7267 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
7268 return;
7269
creis8eb8ef22015-11-04 22:51:387270 if (page_state == frame_entry->page_state())
7271 return; // Nothing to update.
7272
creis0cade2e2017-02-28 06:37:477273 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
nasko34634672016-07-29 18:46:067274
7275 // The document_sequence_number and item_sequence_number recorded in the
7276 // FrameNavigationEntry should not differ from the one coming with the update,
7277 // since it must come from the same document. Do not update it if a difference
7278 // is detected, as this indicates that |frame_entry| is not the correct one.
Miyoung Shin5d77f72072020-10-09 15:14:207279 blink::ExplodedPageState exploded_state;
7280 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
nasko34634672016-07-29 18:46:067281 return;
7282
7283 if (exploded_state.top.document_sequence_number !=
7284 frame_entry->document_sequence_number() ||
7285 exploded_state.top.item_sequence_number !=
7286 frame_entry->item_sequence_number()) {
7287 return;
7288 }
7289
nasko04a322f25a2016-09-01 00:00:347290 frame_entry->SetPageState(page_state);
creis8eb8ef22015-11-04 22:51:387291 controller_.NotifyEntryChanged(entry);
7292}
7293
[email protected]ef3adfc2014-05-11 00:04:547294void WebContentsImpl::UpdateTitle(RenderFrameHost* render_frame_host,
[email protected]ef3adfc2014-05-11 00:04:547295 const base::string16& title,
7296 base::i18n::TextDirection title_direction) {
Alexander Timin5fdeff22020-09-08 09:20:377297 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::UpdateTitle",
7298 "render_frame_host",
7299 base::trace_event::ToTracedValue(render_frame_host),
7300 "title", base::trace_event::ValueToString(title));
[email protected]ef3adfc2014-05-11 00:04:547301 // Try to find the navigation entry, which might not be the current one.
avi286019ce2015-07-29 01:26:587302 // For example, it might be from a recently swapped out RFH.
avi1edc8552016-10-13 21:37:167303 NavigationEntryImpl* entry = controller_.GetEntryWithUniqueID(
creisad8c31a2016-05-24 17:07:047304 static_cast<RenderFrameHostImpl*>(render_frame_host)->nav_entry_id());
[email protected]ef3adfc2014-05-11 00:04:547305
7306 // We can handle title updates when we don't have an entry in
7307 // UpdateTitleForEntry, but only if the update is from the current RVH.
7308 // TODO(avi): Change to make decisions based on the RenderFrameHost.
avi286019ce2015-07-29 01:26:587309 if (!entry && render_frame_host != GetMainFrame())
[email protected]ef3adfc2014-05-11 00:04:547310 return;
7311
7312 // TODO(evan): make use of title_direction.
7313 // http://code.google.com/p/chromium/issues/detail?id=27094
afakhry6f0c1ec22016-07-14 13:55:137314 UpdateTitleForEntry(entry, title);
[email protected]ef3adfc2014-05-11 00:04:547315}
7316
Mario Sanchez Pradadffbe66e2020-09-07 12:01:087317void WebContentsImpl::UpdateTargetURL(RenderFrameHost* render_frame_host,
7318 const GURL& url) {
Alexander Timin5fdeff22020-09-08 09:20:377319 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::UpdateTargetURL",
7320 "render_frame_host",
7321 base::trace_event::ToTracedValue(render_frame_host),
7322 "url", base::trace_event::ValueToString(url));
Mario Sanchez Pradadffbe66e2020-09-07 12:01:087323 // In case of racey updates from multiple RenderViewHosts, the last URL should
7324 // be shown - see also some discussion in https://crbug.com/807776.
7325 if (!url.is_valid() && render_frame_host != frame_that_set_last_target_url_)
7326 return;
7327 frame_that_set_last_target_url_ =
7328 url.is_valid() ? render_frame_host : nullptr;
7329
7330 if (delegate_)
7331 delegate_->UpdateTargetURL(this, url);
7332}
7333
alexmose7da5a12015-04-09 02:22:167334bool WebContentsImpl::ShouldRouteMessageEvent(
7335 RenderFrameHost* target_rfh,
7336 SiteInstance* source_site_instance) const {
Alexander Timin5fdeff22020-09-08 09:20:377337 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::ShouldRouteMessageEvent",
7338 "render_frame_host",
7339 base::trace_event::ToTracedValue(target_rfh),
7340 "source_site_instance", source_site_instance);
alexmose7da5a12015-04-09 02:22:167341 // Allow the message if this WebContents is dedicated to a browser plugin
7342 // guest.
[email protected]0eba810b2012-10-18 03:19:367343 // Note: This check means that an embedder could theoretically receive a
7344 // postMessage from anyone (not just its own guests). However, this is
7345 // probably not a risk for apps since other pages won't have references
7346 // to App windows.
alexmose7da5a12015-04-09 02:22:167347 return GetBrowserPluginGuest() || GetBrowserPluginEmbedder();
7348}
[email protected]f546640b2012-05-15 00:03:497349
alexmos58729042015-06-18 23:20:007350void WebContentsImpl::EnsureOpenerProxiesExist(RenderFrameHost* source_rfh) {
Alexander Timin5fdeff22020-09-08 09:20:377351 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::EnsureOpenerProxiesExist",
7352 "render_frame_host",
7353 base::trace_event::ToTracedValue(source_rfh));
alexmose7da5a12015-04-09 02:22:167354 WebContentsImpl* source_web_contents = static_cast<WebContentsImpl*>(
7355 WebContents::FromRenderFrameHost(source_rfh));
[email protected]f546640b2012-05-15 00:03:497356
alexmose7da5a12015-04-09 02:22:167357 if (source_web_contents) {
lazyboy6ec48b2a2015-06-29 15:18:147358 // If this message is going to outer WebContents from inner WebContents,
7359 // then we should not create a RenderView. AttachToOuterWebContentsFrame()
7360 // already created a RenderFrameProxyHost for that purpose.
7361 if (GetBrowserPluginEmbedder() &&
W. James MacLean2539adb32019-12-13 00:40:447362 source_web_contents->browser_plugin_guest_) {
lazyboy6ec48b2a2015-06-29 15:18:147363 return;
W. James MacLean2539adb32019-12-13 00:40:447364 }
lazyboy6ec48b2a2015-06-29 15:18:147365
lfg812874d2016-02-09 22:26:137366 if (this != source_web_contents && GetBrowserPluginGuest()) {
naskob3041b98a42016-03-12 04:43:067367 // We create a RenderFrameProxyHost for the embedder in the guest's render
7368 // process but we intentionally do not expose the embedder's opener chain
7369 // to it.
7370 source_web_contents->GetRenderManager()->CreateRenderFrameProxy(
7371 GetSiteInstance());
[email protected]f546640b2012-05-15 00:03:497372 } else {
alexmos58729042015-06-18 23:20:007373 RenderFrameHostImpl* source_rfhi =
7374 static_cast<RenderFrameHostImpl*>(source_rfh);
7375 source_rfhi->frame_tree_node()->render_manager()->CreateOpenerProxies(
alexmos90325cf2015-09-02 17:18:397376 GetSiteInstance(), nullptr);
[email protected]f546640b2012-05-15 00:03:497377 }
7378 }
[email protected]f546640b2012-05-15 00:03:497379}
7380
avallee9993fca2016-11-17 06:16:507381void WebContentsImpl::SetAsFocusedWebContentsIfNecessary() {
Alexander Timin5fdeff22020-09-08 09:20:377382 OPTIONAL_TRACE_EVENT0("content",
7383 "WebContentsImpl::SetAsFocusedWebContentsIfNecessary");
Adithya Srinivasan11af2c52019-12-16 22:52:557384 DCHECK(!portal());
avallee9993fca2016-11-17 06:16:507385 // Only change focus if we are not currently focused.
7386 WebContentsImpl* old_contents = GetFocusedWebContents();
7387 if (old_contents == this)
7388 return;
7389
paulmeyerfeafc2d2017-04-25 21:46:407390 GetOutermostWebContents()->node_.SetFocusedWebContents(this);
7391
avallee9993fca2016-11-17 06:16:507392 // Send a page level blur to the old contents so that it displays inactive UI
7393 // and focus this contents to activate it.
7394 if (old_contents)
7395 old_contents->GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(false);
avalleec2ff1ef2017-01-21 00:12:307396
7397 // Make sure the outer web contents knows our frame is focused. Otherwise, the
7398 // outer renderer could have the element before or after the frame element
7399 // focused which would return early without actually advancing focus.
avalleed68cdd12017-06-21 22:07:277400 FocusOuterAttachmentFrameChain();
avalleec2ff1ef2017-01-21 00:12:307401
Carlos ILd51e7702020-05-07 18:51:397402 GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(true);
avallee9993fca2016-11-17 06:16:507403}
7404
avallee0206f782016-07-28 18:55:337405void WebContentsImpl::SetFocusedFrame(FrameTreeNode* node,
7406 SiteInstance* source) {
Alexander Timin5fdeff22020-09-08 09:20:377407 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetFocusedFrame",
7408 "frame_tree_node", node, "source_site_instance",
7409 source);
Adithya Srinivasan11af2c52019-12-16 22:52:557410 DCHECK(!portal());
avallee0206f782016-07-28 18:55:337411 frame_tree_.SetFocusedFrame(node, source);
avalleed68cdd12017-06-21 22:07:277412
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:577413 if (auto* inner_contents = node_.GetInnerWebContentsInFrame(node)) {
7414 // |this| is an outer WebContents and |node| represents an inner
7415 // WebContents. Transfer the focus to the inner contents if |this| is
7416 // focused.
7417 if (GetFocusedWebContents() == this)
7418 inner_contents->SetAsFocusedWebContentsIfNecessary();
7419 } else if (node_.OuterContentsFrameTreeNode() &&
7420 node_.OuterContentsFrameTreeNode()
7421 ->current_frame_host()
7422 ->GetSiteInstance() == source) {
7423 // |this| is an inner WebContents, |node| is its main FrameTreeNode and
7424 // the outer WebContents FrameTreeNode is at |source|'s SiteInstance.
7425 // Transfer the focus to the inner WebContents if the outer WebContents is
7426 // focused. This branch is used when an inner WebContents is focused through
Lowell Mannersa9530382019-08-01 09:46:577427 // its RenderFrameProxyHost (via FrameFocused mojo call, used to
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:577428 // implement the window.focus() API).
7429 if (GetFocusedWebContents() == GetOuterWebContents())
7430 SetAsFocusedWebContentsIfNecessary();
7431 } else if (!GetOuterWebContents()) {
7432 // This is an outermost WebContents.
7433 SetAsFocusedWebContentsIfNecessary();
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:577434 }
avalleed68cdd12017-06-21 22:07:277435}
7436
Avi Drissman36f801f2018-02-01 20:06:047437void WebContentsImpl::DidCallFocus() {
Alexander Timin5fdeff22020-09-08 09:20:377438 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidCallFocus");
Avi Drissman36f801f2018-02-01 20:06:047439 // Any explicit focusing of another window while this WebContents is in
7440 // fullscreen can be used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:457441 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
7442 // The other contents is independent of this contents, so release the
7443 // fullscreen block.
7444 fullscreen_block.RunAndReset();
Avi Drissman36f801f2018-02-01 20:06:047445}
7446
avalleed68cdd12017-06-21 22:07:277447RenderFrameHost* WebContentsImpl::GetFocusedFrameIncludingInnerWebContents() {
Alexander Timin5fdeff22020-09-08 09:20:377448 OPTIONAL_TRACE_EVENT0(
7449 "content", "WebContentsImpl::GetFocusedFrameIncludingInnerWebContents");
avalleed68cdd12017-06-21 22:07:277450 WebContentsImpl* contents = this;
7451 FrameTreeNode* focused_node = contents->frame_tree_.GetFocusedFrame();
7452
7453 // If there is no focused frame in the outer WebContents, we need to return
7454 // null.
7455 if (!focused_node)
7456 return nullptr;
7457
7458 // If the focused frame is embedding an inner WebContents, we must descend
7459 // into that contents. If the current WebContents does not have a focused
7460 // frame, return the main frame of this contents instead of the focused empty
7461 // frame embedding this contents.
7462 while (true) {
7463 contents = contents->node_.GetInnerWebContentsInFrame(focused_node);
7464 if (!contents)
7465 return focused_node->current_frame_host();
7466
7467 focused_node = contents->frame_tree_.GetFocusedFrame();
7468 if (!focused_node)
7469 return contents->GetMainFrame();
7470 }
avallee0206f782016-07-28 18:55:337471}
7472
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:577473void WebContentsImpl::OnAdvanceFocus(RenderFrameHostImpl* source_rfh) {
Alexander Timin5fdeff22020-09-08 09:20:377474 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnAdvanceFocus",
7475 "render_frame_host",
7476 base::trace_event::ToTracedValue(source_rfh));
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:577477 // When a RenderFrame needs to advance focus to a RenderFrameProxy (by hitting
7478 // TAB), the RenderFrameProxy sends an IPC to RenderFrameProxyHost. When this
7479 // RenderFrameProxyHost represents an inner WebContents, the outer WebContents
7480 // needs to focus the inner WebContents.
7481 if (GetOuterWebContents() &&
7482 GetOuterWebContents() == source_rfh->delegate()->GetAsWebContents() &&
7483 GetFocusedWebContents() == GetOuterWebContents()) {
7484 SetAsFocusedWebContentsIfNecessary();
7485 }
7486}
7487
ekaramada110f642016-12-21 19:47:287488void WebContentsImpl::OnFocusedElementChangedInFrame(
7489 RenderFrameHostImpl* frame,
Emily Stark023dbacc2020-08-27 22:31:407490 const gfx::Rect& bounds_in_root_view,
7491 blink::mojom::FocusType focus_type) {
Alexander Timin5fdeff22020-09-08 09:20:377492 OPTIONAL_TRACE_EVENT1(
7493 "content", "WebContentsImpl::OnFocusedElementChangedInFrame",
7494 "render_frame_host", base::trace_event::ToTracedValue(frame));
ekaramada110f642016-12-21 19:47:287495 RenderWidgetHostViewBase* root_view =
7496 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
7497 if (!root_view || !frame->GetView())
7498 return;
Katie De0131372020-07-09 23:03:107499 // Convert to screen coordinates from window coordinates by adding the
7500 // window's origin.
ekaramada110f642016-12-21 19:47:287501 gfx::Point origin = bounds_in_root_view.origin();
7502 origin += root_view->GetViewBounds().OffsetFromOrigin();
7503 gfx::Rect bounds_in_screen(origin, bounds_in_root_view.size());
7504
7505 root_view->FocusedNodeChanged(frame->has_focused_editable_element(),
7506 bounds_in_screen);
7507
7508 FocusedNodeDetails details = {frame->has_focused_editable_element(),
Emily Stark023dbacc2020-08-27 22:31:407509 bounds_in_screen, focus_type};
ekaramada110f642016-12-21 19:47:287510
7511 // TODO(ekaramad): We should replace this with an observer notification
7512 // (https://crbug.com/675975).
7513 NotificationService::current()->Notify(
7514 NOTIFICATION_FOCUS_CHANGED_IN_PAGE,
7515 Source<RenderViewHost>(GetRenderViewHost()),
7516 Details<FocusedNodeDetails>(&details));
Jeff Fisher709b4c52019-07-29 20:07:347517
Alexander Timin90c20c32020-08-12 15:28:327518 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7519 observer->OnFocusChangedInPage(&details);
7520 });
ekaramada110f642016-12-21 19:47:287521}
7522
Lowell Manners1de5242e2019-04-25 10:18:467523bool WebContentsImpl::DidAddMessageToConsole(
7524 blink::mojom::ConsoleMessageLevel log_level,
7525 const base::string16& message,
7526 int32_t line_no,
7527 const base::string16& source_id) {
Alexander Timin5fdeff22020-09-08 09:20:377528 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DidAddMessageToConsole",
7529 "message", base::trace_event::ValueToString(message));
7530
Alexander Timin90c20c32020-08-12 15:28:327531 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7532 observer->OnDidAddMessageToConsole(log_level, message, line_no, source_id);
7533 });
Alexander Timin5fdeff22020-09-08 09:20:377534
[email protected]a796f202012-05-30 14:14:257535 if (!delegate_)
7536 return false;
Lowell Manners1de5242e2019-04-25 10:18:467537 return delegate_->DidAddMessageToConsole(this, log_level, message, line_no,
avia90ae4e2016-11-11 20:49:337538 source_id);
[email protected]a796f202012-05-30 14:14:257539}
7540
Daniel Cheng90196c82018-04-25 21:49:147541void WebContentsImpl::DidReceiveInputEvent(
dominickn9c7ceaa32016-02-27 01:52:537542 RenderWidgetHostImpl* render_widget_host,
Emily Starkc7bd40c2020-07-21 19:12:557543 const blink::WebInputEvent& event) {
Alexander Timin5fdeff22020-09-08 09:20:377544 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DidReceiveInputEvent",
7545 "render_widget_host", render_widget_host);
7546
Emily Starkc7bd40c2020-07-21 19:12:557547 if (!IsUserInteractionInputType(event.GetType()))
Daniel Cheng90196c82018-04-25 21:49:147548 return;
7549
kenrb19221852016-04-29 17:21:407550 // Ignore unless the widget is currently in the frame tree.
7551 if (!HasMatchingWidgetHost(&frame_tree_, render_widget_host))
avic3aa8422015-11-09 20:57:227552 return;
7553
Emily Starkc7bd40c2020-07-21 19:12:557554 if (event.GetType() != blink::WebInputEvent::Type::kGestureScrollBegin)
Daniel Cheng90196c82018-04-25 21:49:147555 last_interactive_input_event_time_ = ui::EventTimeForNow();
dominickn9c7ceaa32016-02-27 01:52:537556
Alexander Timin90c20c32020-08-12 15:28:327557 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7558 observer->DidGetUserInteraction(event);
7559 });
dominickn2dd142dd2015-10-29 05:30:507560}
7561
Avi Drissman738ea192018-08-29 20:24:167562bool WebContentsImpl::ShouldIgnoreInputEvents() {
7563 WebContentsImpl* web_contents = this;
7564 while (web_contents) {
7565 if (web_contents->ignore_input_events_)
7566 return true;
7567 web_contents = web_contents->GetOuterWebContents();
7568 }
7569
7570 return false;
7571}
7572
avallee9993fca2016-11-17 06:16:507573void WebContentsImpl::FocusOwningWebContents(
7574 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:377575 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::FocusOwningWebContents",
7576 "render_widget_host", render_widget_host);
Alex Moshchukc4f0a722019-11-19 22:41:287577 RenderWidgetHostImpl* main_frame_widget_host =
7578 GetMainFrame()->GetRenderWidgetHost();
avallee9993fca2016-11-17 06:16:507579 RenderWidgetHostImpl* focused_widget =
Alex Moshchukc4f0a722019-11-19 22:41:287580 GetFocusedRenderWidgetHost(main_frame_widget_host);
avallee9993fca2016-11-17 06:16:507581
7582 if (focused_widget != render_widget_host &&
avallee8e881592016-11-19 00:39:307583 (!focused_widget ||
7584 focused_widget->delegate() != render_widget_host->delegate())) {
avallee9993fca2016-11-17 06:16:507585 SetAsFocusedWebContentsIfNecessary();
7586 }
7587}
7588
[email protected]b172aee2012-04-10 17:05:267589void WebContentsImpl::OnIgnoredUIEvent() {
Alexander Timin5fdeff22020-09-08 09:20:377590 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnIgnoredUIEvent");
[email protected]31145092011-09-30 01:49:447591 // Notify observers.
Alexander Timin90c20c32020-08-12 15:28:327592 observers_.ForEachObserver(
7593 [&](WebContentsObserver* observer) { observer->DidGetIgnoredUIEvent(); });
[email protected]fa1cf0b82010-01-15 21:49:447594}
7595
avic3aa8422015-11-09 20:57:227596void WebContentsImpl::RendererUnresponsive(
Lukasz Anforowicz52b93722018-06-20 16:11:397597 RenderWidgetHostImpl* render_widget_host,
7598 base::RepeatingClosure hang_monitor_restarter) {
Alexander Timin5fdeff22020-09-08 09:20:377599 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RendererUnresponsive",
7600 "render_widget_host", render_widget_host);
avic031d392017-03-03 03:09:427601 if (ShouldIgnoreUnresponsiveRenderer())
[email protected]e5fc1632011-08-08 07:51:537602 return;
7603
Lukasz Anforowicz4f0593d2018-09-21 18:33:547604 // Do not report hangs (to task manager, to hang renderer dialog, etc.) for
7605 // invisible tabs (like extension background page, background tabs). See
7606 // https://crbug.com/881812 for rationale and for choosing the visibility
7607 // (rather than process priority) as the signal here.
7608 if (GetVisibility() != Visibility::VISIBLE)
7609 return;
7610
Avi Drissman8920def2018-01-31 19:53:367611 if (!render_widget_host->renderer_initialized())
[email protected]55452902011-06-01 21:57:477612 return;
7613
Alexander Timin90c20c32020-08-12 15:28:327614 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7615 observer->OnRendererUnresponsive(render_widget_host->GetProcess());
7616 });
Dave Tapuskac6146c52017-12-20 22:48:157617 if (delegate_)
Lukasz Anforowicz52b93722018-06-20 16:11:397618 delegate_->RendererUnresponsive(this, render_widget_host,
7619 std::move(hang_monitor_restarter));
[email protected]420ae012009-04-24 05:16:327620}
7621
avic3aa8422015-11-09 20:57:227622void WebContentsImpl::RendererResponsive(
7623 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:377624 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderResponsive",
7625 "render_widget_host", render_widget_host);
Alexander Timin90c20c32020-08-12 15:28:327626 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7627 observer->OnRendererResponsive(render_widget_host->GetProcess());
7628 });
Alexander Timin5fdeff22020-09-08 09:20:377629
[email protected]6934a702011-12-20 00:04:517630 if (delegate_)
Avi Drissman1572e8c3c2018-02-02 19:06:367631 delegate_->RendererResponsive(this, render_widget_host);
[email protected]420ae012009-04-24 05:16:327632}
7633
Alex Moshchuk7b4f0652019-05-30 18:54:417634void WebContentsImpl::SubframeCrashed(
7635 blink::mojom::FrameVisibility visibility) {
Alexander Timin5fdeff22020-09-08 09:20:377636 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SubframeCrashed",
7637 "visibility",
7638 base::trace_event::ValueToString(visibility));
Alex Moshchuk7b4f0652019-05-30 18:54:417639 // If a subframe crashed on a hidden tab, mark the tab for reload to avoid
7640 // showing a sad frame to the user if they ever switch back to that tab. Do
7641 // this for subframes that are either visible in viewport or visible but
7642 // scrolled out of view, but skip subframes that are not rendered (e.g., via
7643 // "display:none"), since in that case the user wouldn't see a sad frame
7644 // anyway.
7645 bool did_mark_for_reload = false;
7646 if (IsHidden() && visibility != blink::mojom::FrameVisibility::kNotRendered &&
7647 base::FeatureList::IsEnabled(
7648 features::kReloadHiddenTabsWithCrashedSubframes)) {
7649 controller_.SetNeedsReload(
7650 NavigationControllerImpl::NeedsReloadType::kCrashedSubframe);
7651 did_mark_for_reload = true;
7652 UMA_HISTOGRAM_ENUMERATION(
7653 "Stability.ChildFrameCrash.TabMarkedForReload.Visibility", visibility);
7654 }
7655
7656 UMA_HISTOGRAM_BOOLEAN("Stability.ChildFrameCrash.TabMarkedForReload",
7657 did_mark_for_reload);
7658}
7659
[email protected]b172aee2012-04-10 17:05:267660void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
[email protected]feaded02012-09-25 19:12:557661 bool proceed, const base::TimeTicks& proceed_time,
[email protected]420ae012009-04-24 05:16:327662 bool* proceed_to_fire_unload) {
Alexander Timin5fdeff22020-09-08 09:20:377663 OPTIONAL_TRACE_EVENT0("content",
7664 "WebContentsImpl::BeforeUnloadFiredFromRenderManager");
Alexander Timin90c20c32020-08-12 15:28:327665 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7666 observer->BeforeUnloadFired(proceed, proceed_time);
7667 });
[email protected]6934a702011-12-20 00:04:517668 if (delegate_)
7669 delegate_->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
[email protected]e80af492013-06-24 21:52:097670 // Note: |this| might be deleted at this point.
[email protected]420ae012009-04-24 05:16:327671}
7672
[email protected]58d5cfe2013-07-10 02:40:527673void WebContentsImpl::RenderProcessGoneFromRenderManager(
[email protected]3a3d47472010-07-15 21:03:547674 RenderViewHost* render_view_host) {
[email protected]443b80e2010-12-14 00:42:237675 DCHECK(crashed_status_ != base::TERMINATION_STATUS_STILL_RUNNING);
[email protected]ec6a7eb2013-04-22 17:34:227676 RenderViewTerminated(render_view_host, crashed_status_, crashed_error_code_);
[email protected]3a3d47472010-07-15 21:03:547677}
7678
[email protected]af905902013-10-01 21:38:517679void WebContentsImpl::CancelModalDialogsForRenderManager() {
Alexander Timin5fdeff22020-09-08 09:20:377680 OPTIONAL_TRACE_EVENT0("content",
7681 "WebContentsImpl::CancelModalDialogsForRenderManager");
[email protected]af905902013-10-01 21:38:517682 // We need to cancel modal dialogs when doing a process swap, since the load
avi2460c762015-04-17 15:21:547683 // deferrer would prevent us from swapping out. We also clear the state
7684 // because this is a cross-process navigation, which means that it's a new
7685 // site that should not have to pay for the sins of its predecessor.
creis89a0f782015-05-27 16:13:177686 //
Lei Zhang6410ec1a2019-01-31 21:38:587687 // Note that we don't bother telling |browser_plugin_embedder_| because the
creis89a0f782015-05-27 16:13:177688 // cross-process navigation will either destroy the browser plugins or not
7689 // require their dialogs to close.
avi5d3b8692016-10-12 22:00:467690 if (dialog_manager_) {
avi6879fcf2017-01-21 05:27:537691 dialog_manager_->CancelDialogs(this, /*reset_state=*/true);
avi5d3b8692016-10-12 22:00:467692 }
[email protected]af905902013-10-01 21:38:517693}
7694
danakja0bce4c952020-05-12 20:40:287695void WebContentsImpl::NotifySwappedFromRenderManager(RenderFrameHost* old_frame,
7696 RenderFrameHost* new_frame,
[email protected]02d7b6e2014-06-24 21:01:507697 bool is_main_frame) {
Alexander Timin5fdeff22020-09-08 09:20:377698 TRACE_EVENT2(
7699 "content", "WebContentsImpl::NotifySwappedFromRenderManager",
7700 "old_render_frame_host", base::trace_event::ToTracedValue(old_frame),
7701 "new_render_frame_host", base::trace_event::ToTracedValue(new_frame));
[email protected]02d7b6e2014-06-24 21:01:507702 if (is_main_frame) {
danakja0bce4c952020-05-12 20:40:287703 // The |new_frame| and its various compadres are already swapped into place
7704 // for the WebContentsImpl when this method is called.
7705 DCHECK(GetMainFrame() == new_frame);
7706 DCHECK(GetRenderViewHost() == new_frame->GetRenderViewHost());
7707 DCHECK(GetRenderWidgetHostView() == new_frame->GetView());
7708
Fergal Daly6767b2e2020-02-04 03:15:167709 RenderViewHost* old_rvh =
danakja0bce4c952020-05-12 20:40:287710 old_frame ? old_frame->GetRenderViewHost() : nullptr;
7711 RenderViewHost* new_rvh = new_frame->GetRenderViewHost();
Fergal Daly6767b2e2020-02-04 03:15:167712 // |old_rvh| and |new_rvh| might be equal when navigating from a crashed
7713 // RenderFrameHost to a new same-site one. With RenderDocument, this will
7714 // happen for every same-site navigation.
7715 if (old_rvh != new_rvh)
7716 NotifyViewSwapped(old_rvh, new_rvh);
[email protected]a6b73c62013-02-11 23:05:087717
[email protected]02d7b6e2014-06-24 21:01:507718 // Make sure the visible RVH reflects the new delegate's preferences.
7719 if (delegate_)
7720 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
[email protected]d56a49e2013-02-23 00:47:397721
danakja0bce4c952020-05-12 20:40:287722 auto* rwhv = static_cast<RenderWidgetHostViewBase*>(new_frame->GetView());
7723 if (rwhv) {
7724 rwhv->SetMainFrameAXTreeID(new_frame->GetAXTreeID());
7725
7726 // The RenderWidgetHostView for the speculative RenderFrameHost is not
7727 // resized with the current RenderFrameHost while a navigation is
7728 // pending. So when we swap in the main frame, we need to update the
7729 // RenderWidgetHostView's size.
7730 //
7731 // Historically, this was done to fix b/1079768 for interstitials.
7732 rwhv->SetSize(GetSizeForMainFrame());
7733 }
[email protected]02d7b6e2014-06-24 21:01:507734 }
7735
danakja0bce4c952020-05-12 20:40:287736 NotifyFrameSwapped(old_frame, new_frame, is_main_frame);
[email protected]3a3d47472010-07-15 21:03:547737}
7738
naskof5940b9f2015-03-02 23:04:057739void WebContentsImpl::NotifyMainFrameSwappedFromRenderManager(
danakja0bce4c952020-05-12 20:40:287740 RenderFrameHost* old_frame,
7741 RenderFrameHost* new_frame) {
7742 NotifyViewSwapped(old_frame ? old_frame->GetRenderViewHost() : nullptr,
7743 new_frame->GetRenderViewHost());
naskof5940b9f2015-03-02 23:04:057744}
7745
[email protected]b172aee2012-04-10 17:05:267746NavigationControllerImpl& WebContentsImpl::GetControllerForRenderManager() {
[email protected]d1198fd2012-08-13 22:50:197747 return GetController();
[email protected]3a3d47472010-07-15 21:03:547748}
7749
dcheng59716272016-04-09 05:19:087750std::unique_ptr<WebUIImpl> WebContentsImpl::CreateWebUIForRenderFrameHost(
Miyoung Shin072d4052020-07-13 07:52:447751 RenderFrameHost* frame_host,
Denis Kuznetsov [CET]2c6f0159f2020-05-18 14:18:167752 const GURL& url) {
Miyoung Shin072d4052020-07-13 07:52:447753 return CreateWebUI(frame_host, url);
[email protected]420ae012009-04-24 05:16:327754}
7755
lfgbede6392015-09-11 21:54:067756void WebContentsImpl::CreateRenderWidgetHostViewForRenderManager(
7757 RenderViewHost* render_view_host) {
Alexander Timin5fdeff22020-09-08 09:20:377758 OPTIONAL_TRACE_EVENT1(
7759 "content", "WebContentsImpl::CreateRenderWidgetHostViewForRenderManager",
7760 "render_view_host", render_view_host);
lfgc740d4b22016-04-15 16:45:337761 RenderWidgetHostViewBase* rwh_view =
W. James MacLean13d834d2019-12-04 16:06:457762 view_->CreateViewForWidget(render_view_host->GetWidget());
danakja0bce4c952020-05-12 20:40:287763 rwh_view->SetSize(GetSizeForMainFrame());
lfgbede6392015-09-11 21:54:067764}
7765
Fergal Daly6de62f52020-10-14 01:56:447766void WebContentsImpl::ReattachOuterDelegateIfNeeded() {
7767 if (node_.outer_web_contents())
7768 ReattachToOuterWebContentsFrame();
7769}
7770
lfgbede6392015-09-11 21:54:067771bool WebContentsImpl::CreateRenderViewForRenderManager(
7772 RenderViewHost* render_view_host,
Antonio Gomesb3dd5fc2020-05-25 22:53:277773 const base::Optional<base::UnguessableToken>& opener_frame_token,
Daniel Chengabfdb002020-06-04 06:02:307774 int proxy_routing_id) {
Alexander Timin5fdeff22020-09-08 09:20:377775 TRACE_EVENT1("browser,navigation",
7776 "WebContentsImpl::CreateRenderViewForRenderManager",
7777 "render_view_host", render_view_host);
lfgbede6392015-09-11 21:54:067778
piman00cf9402017-04-03 17:09:207779 if (proxy_routing_id == MSG_ROUTING_NONE)
lfg9431efd2016-12-14 14:45:267780 CreateRenderWidgetHostViewForRenderManager(render_view_host);
lfg9431efd2016-12-14 14:45:267781
piman00cf9402017-04-03 17:09:207782 if (!static_cast<RenderViewHostImpl*>(render_view_host)
Daniel Chengabfdb002020-06-04 06:02:307783 ->CreateRenderView(opener_frame_token, proxy_routing_id,
Antonio Gomesb3dd5fc2020-05-25 22:53:277784 created_with_opener_)) {
[email protected]a4127722011-04-27 23:13:527785 return false;
[email protected]14392a52012-05-02 20:28:447786 }
W. James MacLean62198672019-06-04 16:46:107787 // Set the TextAutosizer state from the main frame's renderer on the new view,
7788 // but only if it's not for the main frame. Main frame renderers should create
7789 // this state themselves from up-to-date values, so we shouldn't override it
7790 // with the cached values.
7791 if (!render_view_host->GetMainFrame()) {
Antonio Gomesda7e03d2020-08-05 15:03:087792 auto* proxy_host = GetRenderManager()->GetRenderFrameProxyHost(
7793 render_view_host->GetSiteInstance());
7794 proxy_host->GetAssociatedRemoteMainFrame()->UpdateTextAutosizerPageInfo(
7795 text_autosizer_page_info_.Clone());
W. James MacLean62198672019-06-04 16:46:107796 }
[email protected]a4127722011-04-27 23:13:527797
Fergal Daly6de62f52020-10-14 01:56:447798 if (proxy_routing_id == MSG_ROUTING_NONE)
7799 ReattachOuterDelegateIfNeeded();
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:147800
avi2b177592014-12-10 02:08:027801 SetHistoryOffsetAndLengthForView(render_view_host,
7802 controller_.GetLastCommittedEntryIndex(),
7803 controller_.GetEntryCount());
7804
Avi Drissman7c57be72020-07-29 20:09:467805#if defined(OS_POSIX) && !defined(OS_MAC) && !defined(OS_ANDROID)
[email protected]f8233cc2011-05-31 20:24:507806 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
7807 // linux. See crbug.com/83941.
avif9ab5d942015-10-15 14:05:447808 RenderWidgetHostView* rwh_view = render_view_host->GetWidget()->GetView();
[email protected]245f7d52011-11-28 15:36:447809 if (rwh_view) {
7810 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
Fady Samuel0b911822018-04-25 13:22:167811 render_widget_host->SynchronizeVisualProperties();
[email protected]245f7d52011-11-28 15:36:447812 }
[email protected]f8233cc2011-05-31 20:24:507813#endif
7814
[email protected]420ae012009-04-24 05:16:327815 return true;
7816}
7817
mfomitchev2b8b066a2016-01-28 19:23:157818#if defined(OS_ANDROID)
[email protected]fc2b46b2014-05-03 16:33:457819
[email protected]155c7f22013-12-09 17:07:187820base::android::ScopedJavaLocalRef<jobject>
7821WebContentsImpl::GetJavaWebContents() {
mostynb042582e2015-03-16 22:13:407822 DCHECK_CURRENTLY_ON(BrowserThread::UI);
[email protected]0e813a52014-08-13 10:34:567823 return GetWebContentsAndroid()->GetJavaObject();
7824}
[email protected]155c7f22013-12-09 17:07:187825
[email protected]0e813a52014-08-13 10:34:567826WebContentsAndroid* WebContentsImpl::GetWebContentsAndroid() {
Kevin McNee576bb5d82019-05-29 16:47:517827 if (!web_contents_android_) {
7828 web_contents_android_ = std::make_unique<WebContentsAndroid>(this);
[email protected]155c7f22013-12-09 17:07:187829 }
Kevin McNee576bb5d82019-05-29 16:47:517830 return web_contents_android_.get();
7831}
7832
7833void WebContentsImpl::ClearWebContentsAndroid() {
7834 DCHECK_CURRENTLY_ON(BrowserThread::UI);
7835 web_contents_android_.reset();
[email protected]155c7f22013-12-09 17:07:187836}
7837
paulmeyerc0b762b2016-04-13 11:55:177838void WebContentsImpl::ActivateNearestFindResult(float x,
7839 float y) {
Alexander Timin5fdeff22020-09-08 09:20:377840 OPTIONAL_TRACE_EVENT0("content",
7841 "WebContentsImpl::ActivateNearestFindResult");
paulmeyerc0b762b2016-04-13 11:55:177842 GetOrCreateFindRequestManager()->ActivateNearestFindResult(x, y);
7843}
7844
7845void WebContentsImpl::RequestFindMatchRects(int current_version) {
Alexander Timin5fdeff22020-09-08 09:20:377846 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::RequestFindMatchRects");
paulmeyerc0b762b2016-04-13 11:55:177847 GetOrCreateFindRequestManager()->RequestFindMatchRects(current_version);
7848}
7849
rockot400ea35b2016-10-15 19:15:327850service_manager::InterfaceProvider* WebContentsImpl::GetJavaInterfaces() {
sammcf5f1b0f2016-09-20 23:05:117851 if (!java_interfaces_) {
Gyuyoung Kim6c9ce9022019-11-26 05:40:087852 mojo::PendingRemote<service_manager::mojom::InterfaceProvider> provider;
7853 BindInterfaceRegistryForWebContents(
7854 provider.InitWithNewPipeAndPassReceiver(), this);
rockot400ea35b2016-10-15 19:15:327855 java_interfaces_.reset(new service_manager::InterfaceProvider);
sammcf5f1b0f2016-09-20 23:05:117856 java_interfaces_->Bind(std::move(provider));
7857 }
7858 return java_interfaces_.get();
7859}
7860
Francois Doray6c26f3342018-08-24 17:17:227861#endif
7862
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:417863bool WebContentsImpl::CompletedFirstVisuallyNonEmptyPaint() {
Carlos Caballero91fffb22019-10-29 15:24:307864 return GetRenderViewHost()->did_first_visually_non_empty_paint();
spqchane72c3cb2017-06-30 23:02:107865}
7866
pkotwicz75ca8ffd2016-02-16 23:10:197867void WebContentsImpl::OnDidDownloadImage(
Avi Drissmana5a52dd2018-03-27 03:39:027868 ImageDownloadCallback callback,
pkotwicz75ca8ffd2016-02-16 23:10:197869 int id,
7870 const GURL& image_url,
leon.hancbc4bc3c2016-02-26 07:08:527871 int32_t http_status_code,
leon.hanc2228532016-08-16 05:59:187872 const std::vector<SkBitmap>& images,
7873 const std::vector<gfx::Size>& original_image_sizes) {
Alexander Timin5fdeff22020-09-08 09:20:377874 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnDidDownloadImage",
7875 "image_url",
7876 base::trace_event::ValueToString(image_url));
Avi Drissmana5a52dd2018-03-27 03:39:027877 std::move(callback).Run(id, http_status_code, image_url, images,
7878 original_image_sizes);
pkotwicz75ca8ffd2016-02-16 23:10:197879}
7880
[email protected]6fba26d2014-04-29 09:38:287881void WebContentsImpl::OnDialogClosed(int render_process_id,
7882 int render_frame_id,
Dave Tapuskacdf545cc2020-01-23 18:38:527883 JavaScriptDialogCallback response_callback,
Avi Drissman1a55a9d62020-03-10 18:56:457884 base::ScopedClosureRunner fullscreen_block,
[email protected]87de04b02014-04-08 22:14:497885 bool dialog_was_suppressed,
[email protected]b172aee2012-04-10 17:05:267886 bool success,
[email protected]fcf75d42013-12-03 20:11:267887 const base::string16& user_input) {
[email protected]6fba26d2014-04-29 09:38:287888 RenderFrameHostImpl* rfh = RenderFrameHostImpl::FromID(render_process_id,
7889 render_frame_id);
Alexander Timin5fdeff22020-09-08 09:20:377890 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnDialogClosed",
7891 "render_frame_host",
7892 base::trace_event::ToTracedValue(rfh));
[email protected]87de04b02014-04-08 22:14:497893 last_dialog_suppressed_ = dialog_was_suppressed;
Avi Drissman1a55a9d62020-03-10 18:56:457894 fullscreen_block.RunAndReset();
[email protected]87de04b02014-04-08 22:14:497895
Charlie Reis96077362019-07-04 00:34:047896 javascript_dialog_navigation_deferrer_.reset();
7897
[email protected]beb440c2009-11-06 04:08:547898 if (is_showing_before_unload_dialog_ && !success) {
clamybc6f4152016-04-01 20:14:237899 // It is possible for the current RenderFrameHost to have changed in the
7900 // meantime. Do not reset the navigation state in that case.
7901 if (rfh && rfh == rfh->frame_tree_node()->current_frame_host()) {
clamy44e84ce2016-02-22 15:38:257902 rfh->frame_tree_node()->BeforeUnloadCanceled();
clamybc6f4152016-04-01 20:14:237903 controller_.DiscardNonCommittedEntries();
7904 }
[email protected]ec8e8b02013-06-19 04:57:107905
Charles Reis15d60b132017-11-03 17:43:477906 // Update the URL display either way, to avoid showing a stale URL.
7907 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
7908
Alexander Timin90c20c32020-08-12 15:28:327909 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7910 observer->BeforeUnloadDialogCancelled();
7911 });
[email protected]beb440c2009-11-06 04:08:547912 }
[email protected]87de04b02014-04-08 22:14:497913
Dave Tapuskacdf545cc2020-01-23 18:38:527914 std::move(response_callback).Run(success, user_input);
Pavel Feldman3c1842b2017-08-02 05:00:167915
Dave Tapuskacdf545cc2020-01-23 18:38:527916 std::vector<protocol::PageHandler*> page_handlers =
7917 protocol::PageHandler::EnabledForWebContents(this);
7918 for (auto* handler : page_handlers)
7919 handler->DidCloseJavaScriptDialog(success, user_input);
avi1c51fb62017-02-27 20:43:037920
7921 is_showing_javascript_dialog_ = false;
7922 is_showing_before_unload_dialog_ = false;
[email protected]beb440c2009-11-06 04:08:547923}
7924
[email protected]1ac10dca2013-08-20 20:47:047925bool WebContentsImpl::IsHidden() {
Francois Doraye6161152018-03-27 22:05:377926 return !IsBeingCaptured() && visibility_ != Visibility::VISIBLE;
[email protected]1ac10dca2013-08-20 20:47:047927}
7928
rob97250742015-12-10 17:45:157929int WebContentsImpl::GetOuterDelegateFrameTreeNodeId() {
lfg601233692017-03-06 22:45:447930 return node_.outer_contents_frame_tree_node_id();
lazyboy6ec48b2a2015-06-29 15:18:147931}
7932
[email protected]b0936d22013-11-28 06:47:367933RenderFrameHostManager* WebContentsImpl::GetRenderManager() const {
[email protected]fa944cb82013-11-15 17:51:217934 return frame_tree_.root()->render_manager();
7935}
7936
[email protected]f8497342013-02-05 22:15:027937BrowserPluginGuest* WebContentsImpl::GetBrowserPluginGuest() const {
[email protected]7a846df2012-09-20 19:17:397938 return browser_plugin_guest_.get();
7939}
7940
Albert J. Wongc55cc64d2018-10-12 02:50:047941void WebContentsImpl::SetBrowserPluginGuest(
7942 std::unique_ptr<BrowserPluginGuest> guest) {
Alexander Timin5fdeff22020-09-08 09:20:377943 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetBrowserPluginGuest");
Albert J. Wongc55cc64d2018-10-12 02:50:047944 DCHECK(!browser_plugin_guest_);
7945 DCHECK(guest);
7946 browser_plugin_guest_ = std::move(guest);
[email protected]738f57a2013-06-29 21:06:547947}
7948
Aidan Wolter52bcc12a2018-11-14 03:27:297949base::UnguessableToken WebContentsImpl::GetAudioGroupId() {
Aidan Wolter52bcc12a2018-11-14 03:27:297950 return GetAudioStreamFactory()->group_id();
7951}
7952
Miyoung Shin5709ab02020-02-19 06:50:417953const std::vector<blink::mojom::FaviconURLPtr>&
7954WebContentsImpl::GetFaviconURLs() {
Mounir Lamouri7b4a1f232019-12-23 16:32:107955 return favicon_urls_;
7956}
7957
Mugdha Lakhani0a0d7862020-07-29 09:58:457958// The Mac implementation of the next two methods is in
7959// web_contents_impl_mac.mm
Avi Drissmand4d79f72020-07-30 18:35:187960#if !defined(OS_MAC)
Mugdha Lakhani0a0d7862020-07-29 09:58:457961
7962void WebContentsImpl::Resize(const gfx::Rect& new_bounds) {
Alexander Timin5fdeff22020-09-08 09:20:377963 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Resize");
Mugdha Lakhani0a0d7862020-07-29 09:58:457964#if defined(USE_AURA)
7965 aura::Window* window = GetNativeView();
7966 window->SetBounds(gfx::Rect(window->bounds().origin(), new_bounds.size()));
7967#elif defined(OS_ANDROID)
7968 content::RenderWidgetHostView* view = GetRenderWidgetHostView();
7969 if (view)
7970 view->SetBounds(new_bounds);
7971#endif
7972}
7973
7974gfx::Size WebContentsImpl::GetSize() {
7975#if defined(USE_AURA)
7976 aura::Window* window = GetNativeView();
7977 return window->bounds().size();
7978#elif defined(OS_ANDROID)
7979 ui::ViewAndroid* view_android = GetNativeView();
7980 return view_android->bounds().size();
7981#endif
7982}
7983
Avi Drissmand4d79f72020-07-30 18:35:187984#endif // !defined(OS_MAC)
Mugdha Lakhani0a0d7862020-07-29 09:58:457985
[email protected]f8497342013-02-05 22:15:027986BrowserPluginEmbedder* WebContentsImpl::GetBrowserPluginEmbedder() const {
[email protected]7a846df2012-09-20 19:17:397987 return browser_plugin_embedder_.get();
7988}
[email protected]8ff00d72012-10-23 19:12:217989
fsamuel60b42282015-03-10 03:29:147990void WebContentsImpl::CreateBrowserPluginEmbedderIfNecessary() {
Alexander Timin5fdeff22020-09-08 09:20:377991 OPTIONAL_TRACE_EVENT0(
7992 "content", "WebContentsImpl::CreateBrowserPluginEmbedderIfNecessary");
fsamuel60b42282015-03-10 03:29:147993 if (browser_plugin_embedder_)
7994 return;
7995 browser_plugin_embedder_.reset(BrowserPluginEmbedder::Create(this));
7996}
7997
danakja0bce4c952020-05-12 20:40:287998gfx::Size WebContentsImpl::GetSizeForMainFrame() {
7999 if (delegate_) {
8000 // The delegate has a chance to specify a size independent of the UI.
8001 gfx::Size delegate_size = delegate_->GetSizeForNewRenderView(this);
8002 if (!delegate_size.IsEmpty())
8003 return delegate_size;
8004 }
8005
8006 // Device emulation, when enabled, can specify a size independent of the UI.
8007 if (!device_emulation_size_.IsEmpty())
8008 return device_emulation_size_;
8009
8010 return GetContainerBounds().size();
[email protected]dc0fd432013-08-27 15:29:218011}
8012
[email protected]ae7eeda2014-07-04 01:53:268013void WebContentsImpl::OnFrameRemoved(RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:378014 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnFrameRemoved",
8015 "render_frame_host",
8016 base::trace_event::ToTracedValue(render_frame_host));
Alexander Timin90c20c32020-08-12 15:28:328017 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8018 observer->FrameDeleted(render_frame_host);
8019 });
[email protected]9b159a52013-10-03 17:24:558020}
8021
[email protected]222f5822014-02-05 23:40:498022void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size& old_size) {
Alexander Timin5fdeff22020-09-08 09:20:378023 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnPreferredSizeChanged");
[email protected]222f5822014-02-05 23:40:498024 if (!delegate_)
8025 return;
8026 const gfx::Size new_size = GetPreferredSize();
8027 if (new_size != old_size)
8028 delegate_->UpdatePreferredSize(this, new_size);
8029}
8030
Miyoung Shin072d4052020-07-13 07:52:448031std::unique_ptr<WebUIImpl> WebContentsImpl::CreateWebUI(
8032 RenderFrameHost* frame_host,
8033 const GURL& url) {
Alexander Timin5fdeff22020-09-08 09:20:378034 TRACE_EVENT2("content", "WebContentsImpl::CreateWebUI", "frame_host",
8035 base::trace_event::ToTracedValue(frame_host), "url",
8036 base::trace_event::ValueToString(url));
Miyoung Shin072d4052020-07-13 07:52:448037 std::unique_ptr<WebUIImpl> web_ui =
8038 std::make_unique<WebUIImpl>(this, frame_host);
Lei Zhangee3b63ad2018-06-06 23:25:318039 std::unique_ptr<WebUIController> controller(
avie865b1d2016-10-24 19:42:598040 WebUIControllerFactoryRegistry::GetInstance()
Lei Zhangee3b63ad2018-06-06 23:25:318041 ->CreateWebUIControllerForURL(web_ui.get(), url));
dbeama1b926a2015-08-31 23:17:518042 if (controller) {
Lei Zhangee3b63ad2018-06-06 23:25:318043 web_ui->SetController(std::move(controller));
dbeama1b926a2015-08-31 23:17:518044 return web_ui;
8045 }
8046
avie865b1d2016-10-24 19:42:598047 return nullptr;
dbeama1b926a2015-08-31 23:17:518048}
8049
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:418050FindRequestManager* WebContentsImpl::GetFindRequestManager() {
8051 for (auto* contents = this; contents;
paulmeyerfeafc2d2017-04-25 21:46:408052 contents = contents->GetOuterWebContents()) {
8053 if (contents->find_request_manager_)
8054 return contents->find_request_manager_.get();
8055 }
8056
8057 return nullptr;
8058}
8059
paulmeyerc0b762b2016-04-13 11:55:178060FindRequestManager* WebContentsImpl::GetOrCreateFindRequestManager() {
paulmeyerfeafc2d2017-04-25 21:46:408061 if (FindRequestManager* manager = GetFindRequestManager())
8062 return manager;
8063
Ehsan Karamad6beb2ea2018-11-25 18:15:138064 DCHECK(!browser_plugin_guest_ || GetOuterWebContents());
8065
paulmeyerfeafc2d2017-04-25 21:46:408066 // No existing FindRequestManager found, so one must be created.
Fergal Daly55b6d722020-09-11 07:56:338067 find_request_manager_ = std::make_unique<FindRequestManager>(this);
paulmeyerfeafc2d2017-04-25 21:46:408068
8069 // Concurrent find sessions must not overlap, so destroy any existing
8070 // FindRequestManagers in any inner WebContentses.
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:168071 for (WebContents* contents : GetWebContentsAndAllInner()) {
8072 auto* web_contents_impl = static_cast<WebContentsImpl*>(contents);
8073 if (web_contents_impl == this)
paulmeyerfeafc2d2017-04-25 21:46:408074 continue;
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:168075 if (web_contents_impl->find_request_manager_) {
8076 web_contents_impl->find_request_manager_->StopFinding(
8077 STOP_FIND_ACTION_CLEAR_SELECTION);
8078 web_contents_impl->find_request_manager_.release();
paulmeyerfeafc2d2017-04-25 21:46:408079 }
8080 }
paulmeyerc0b762b2016-04-13 11:55:178081
8082 return find_request_manager_.get();
8083}
8084
8085void WebContentsImpl::NotifyFindReply(int request_id,
8086 int number_of_matches,
8087 const gfx::Rect& selection_rect,
8088 int active_match_ordinal,
8089 bool final_update) {
Alexander Timin5fdeff22020-09-08 09:20:378090 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::NotifyFindReply");
Sebastien Marchandcf97ed52017-07-24 23:50:348091 if (delegate_ && !is_being_destroyed_ &&
Lukasz Anforowicze9ae3722017-09-29 17:37:388092 !GetMainFrame()->GetProcess()->FastShutdownStarted()) {
paulmeyerc0b762b2016-04-13 11:55:178093 delegate_->FindReply(this, request_id, number_of_matches, selection_rect,
8094 active_match_ordinal, final_update);
8095 }
8096}
8097
ortuno467e5792016-06-10 04:32:398098void WebContentsImpl::IncrementBluetoothConnectedDeviceCount() {
Alexander Timin5fdeff22020-09-08 09:20:378099 OPTIONAL_TRACE_EVENT0(
8100 "content", "WebContentsImpl::IncrementBluetoothConnectedDeviceCount");
ortuno467e5792016-06-10 04:32:398101 // Trying to invalidate the tab state while being destroyed could result in a
8102 // use after free.
8103 if (IsBeingDestroyed()) {
8104 return;
8105 }
8106 // Notify for UI updates if the state changes.
8107 bluetooth_connected_device_count_++;
8108 if (bluetooth_connected_device_count_ == 1) {
Francois Doray66766a572019-12-17 20:56:498109 OnIsConnectedToBluetoothDeviceChanged(true);
ortuno467e5792016-06-10 04:32:398110 }
8111}
8112
8113void WebContentsImpl::DecrementBluetoothConnectedDeviceCount() {
Alexander Timin5fdeff22020-09-08 09:20:378114 OPTIONAL_TRACE_EVENT0(
8115 "content", "WebContentsImpl::DecrementBluetoothConnectedDeviceCount");
ortuno467e5792016-06-10 04:32:398116 // Trying to invalidate the tab state while being destroyed could result in a
8117 // use after free.
8118 if (IsBeingDestroyed()) {
8119 return;
8120 }
8121 // Notify for UI updates if the state changes.
Lukasz Anforowicze9ae3722017-09-29 17:37:388122 DCHECK_NE(bluetooth_connected_device_count_, 0u);
ortuno467e5792016-06-10 04:32:398123 bluetooth_connected_device_count_--;
8124 if (bluetooth_connected_device_count_ == 0) {
Francois Doray66766a572019-12-17 20:56:498125 OnIsConnectedToBluetoothDeviceChanged(false);
8126 }
8127}
8128
8129void WebContentsImpl::OnIsConnectedToBluetoothDeviceChanged(
8130 bool is_connected_to_bluetooth_device) {
Alexander Timin5fdeff22020-09-08 09:20:378131 OPTIONAL_TRACE_EVENT0(
8132 "content", "WebContentsImpl::OnIsConnectedToBluetoothDeviceChanged");
Francois Doray66766a572019-12-17 20:56:498133 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
Alexander Timin90c20c32020-08-12 15:28:328134 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8135 observer->OnIsConnectedToBluetoothDeviceChanged(
Francois Doray66766a572019-12-17 20:56:498136 is_connected_to_bluetooth_device);
Alexander Timin90c20c32020-08-12 15:28:328137 });
ortuno467e5792016-06-10 04:32:398138}
8139
Ovidio Henriquez76696f62020-07-08 03:06:598140void WebContentsImpl::IncrementBluetoothScanningSessionsCount() {
Alexander Timin5fdeff22020-09-08 09:20:378141 OPTIONAL_TRACE_EVENT0(
8142 "content", "WebContentsImpl::IncrementBluetoothScanningSessionsCount");
Ovidio Henriquez76696f62020-07-08 03:06:598143 // Trying to invalidate the tab state while being destroyed could result in a
8144 // use after free.
8145 if (IsBeingDestroyed())
8146 return;
8147
8148 // Notify for UI updates if the state changes.
8149 bluetooth_scanning_sessions_count_++;
8150 if (bluetooth_scanning_sessions_count_ == 1)
8151 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8152}
8153
8154void WebContentsImpl::DecrementBluetoothScanningSessionsCount() {
Alexander Timin5fdeff22020-09-08 09:20:378155 OPTIONAL_TRACE_EVENT0(
8156 "content", "WebContentsImpl::DecrementBluetoothScanningSessionsCount");
Ovidio Henriquez76696f62020-07-08 03:06:598157 // Trying to invalidate the tab state while being destroyed could result in a
8158 // use after free.
8159 if (IsBeingDestroyed())
8160 return;
8161
8162 DCHECK_NE(0u, bluetooth_scanning_sessions_count_);
8163 bluetooth_scanning_sessions_count_--;
8164 if (bluetooth_scanning_sessions_count_ == 0)
8165 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8166}
8167
Reilly Grant5e7c79b22019-04-09 17:26:208168void WebContentsImpl::IncrementSerialActiveFrameCount() {
Alexander Timin5fdeff22020-09-08 09:20:378169 OPTIONAL_TRACE_EVENT0("content",
8170 "WebContentsImpl::IncrementSerialActiveFrameCount");
Reilly Grant5e7c79b22019-04-09 17:26:208171 // Trying to invalidate the tab state while being destroyed could result in a
8172 // use after free.
8173 if (IsBeingDestroyed())
8174 return;
8175
8176 // Notify for UI updates if the state changes.
8177 serial_active_frame_count_++;
8178 if (serial_active_frame_count_ == 1)
8179 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8180}
8181
8182void WebContentsImpl::DecrementSerialActiveFrameCount() {
Alexander Timin5fdeff22020-09-08 09:20:378183 OPTIONAL_TRACE_EVENT0("content",
8184 "WebContentsImpl::DecrementSerialActiveFrameCount");
Reilly Grant5e7c79b22019-04-09 17:26:208185 // Trying to invalidate the tab state while being destroyed could result in a
8186 // use after free.
8187 if (IsBeingDestroyed())
8188 return;
8189
8190 // Notify for UI updates if the state changes.
8191 DCHECK_NE(0u, serial_active_frame_count_);
8192 serial_active_frame_count_--;
8193 if (serial_active_frame_count_ == 0)
8194 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8195}
8196
Matt Reynoldse8c6c1f2019-11-02 09:53:538197void WebContentsImpl::IncrementHidActiveFrameCount() {
Alexander Timin5fdeff22020-09-08 09:20:378198 OPTIONAL_TRACE_EVENT0("content",
8199 "WebContentsImpl::IncrementHidActiveFrameCount");
Matt Reynoldse8c6c1f2019-11-02 09:53:538200 // Trying to invalidate the tab state while being destroyed could result in a
8201 // use after free.
8202 if (IsBeingDestroyed())
8203 return;
8204
8205 // Notify for UI updates if the active frame count transitions from zero to
8206 // non-zero.
8207 hid_active_frame_count_++;
8208 if (hid_active_frame_count_ == 1)
8209 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8210}
8211
8212void WebContentsImpl::DecrementHidActiveFrameCount() {
Alexander Timin5fdeff22020-09-08 09:20:378213 OPTIONAL_TRACE_EVENT0("content",
8214 "WebContentsImpl::DecrementHidActiveFrameCount");
Matt Reynoldse8c6c1f2019-11-02 09:53:538215 // Trying to invalidate the tab state while being destroyed could result in a
8216 // use after free.
8217 if (IsBeingDestroyed())
8218 return;
8219
8220 // Notify for UI updates if the active frame count transitions from non-zero
8221 // to zero.
8222 DCHECK_NE(0u, hid_active_frame_count_);
8223 hid_active_frame_count_--;
8224 if (hid_active_frame_count_ == 0)
8225 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8226}
8227
Marijn Kruisselbrink29051042019-08-06 22:56:558228void WebContentsImpl::IncrementNativeFileSystemHandleCount() {
Alexander Timin5fdeff22020-09-08 09:20:378229 OPTIONAL_TRACE_EVENT0(
8230 "content", "WebContentsImpl::IncrementNativeFileSystemHandleCount");
Marijn Kruisselbrink29051042019-08-06 22:56:558231 // Trying to invalidate the tab state while being destroyed could result in a
8232 // use after free.
8233 if (IsBeingDestroyed())
8234 return;
8235
8236 // Notify for UI updates if the state changes. Need both TYPE_TAB and TYPE_URL
8237 // to update both the tab-level usage indicator and the usage indicator in the
8238 // omnibox.
8239 native_file_system_handle_count_++;
8240 if (native_file_system_handle_count_ == 1) {
8241 NotifyNavigationStateChanged(static_cast<content::InvalidateTypes>(
8242 INVALIDATE_TYPE_TAB | INVALIDATE_TYPE_URL));
8243 }
8244}
8245
8246void WebContentsImpl::DecrementNativeFileSystemHandleCount() {
Alexander Timin5fdeff22020-09-08 09:20:378247 OPTIONAL_TRACE_EVENT0(
8248 "content", "WebContentsImpl::DecrementNativeFileSystemHandleCount");
Marijn Kruisselbrink29051042019-08-06 22:56:558249 // Trying to invalidate the tab state while being destroyed could result in a
8250 // use after free.
8251 if (IsBeingDestroyed())
8252 return;
8253
8254 // Notify for UI updates if the state changes. Need both TYPE_TAB and TYPE_URL
8255 // to update both the tab-level usage indicator and the usage indicator in the
8256 // omnibox.
8257 DCHECK_NE(0u, native_file_system_handle_count_);
8258 native_file_system_handle_count_--;
8259 if (native_file_system_handle_count_ == 0) {
8260 NotifyNavigationStateChanged(static_cast<content::InvalidateTypes>(
8261 INVALIDATE_TYPE_TAB | INVALIDATE_TYPE_URL));
8262 }
8263}
8264
zqzhang8ac49002017-03-16 21:51:358265void WebContentsImpl::SetHasPersistentVideo(bool has_persistent_video) {
Alexander Timin5fdeff22020-09-08 09:20:378266 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetHasPersistentVideo",
8267 "has_persistent_video", has_persistent_video,
8268 "had_persistent_value", has_persistent_video_);
zqzhang8ac49002017-03-16 21:51:358269 if (has_persistent_video_ == has_persistent_video)
mlamouri5cd9ae82017-02-18 11:05:098270 return;
8271
zqzhang8ac49002017-03-16 21:51:358272 has_persistent_video_ = has_persistent_video;
mlamouri5cd9ae82017-02-18 11:05:098273 NotifyPreferencesChanged();
zqzhang8ac49002017-03-16 21:51:358274 media_web_contents_observer()->RequestPersistentVideo(has_persistent_video);
mlamouri5cd9ae82017-02-18 11:05:098275}
8276
Ian Vollick5d5c37f2019-06-19 22:50:578277void WebContentsImpl::SetSpatialNavigationDisabled(bool disabled) {
Alexander Timin5fdeff22020-09-08 09:20:378278 OPTIONAL_TRACE_EVENT2(
8279 "content", "WebContentsImpl::SetSpatialNavigationDisabled", "disabled",
8280 disabled, "was_disabled", is_spatial_navigation_disabled_);
Ian Vollick5d5c37f2019-06-19 22:50:578281 if (is_spatial_navigation_disabled_ == disabled)
8282 return;
8283
8284 is_spatial_navigation_disabled_ = disabled;
8285 NotifyPreferencesChanged();
8286}
8287
paulmeyerfeafc2d2017-04-25 21:46:408288void WebContentsImpl::BrowserPluginGuestWillDetach() {
Alexander Timin5fdeff22020-09-08 09:20:378289 OPTIONAL_TRACE_EVENT0("content",
8290 "WebContentsImpl::BrowserPluginGuestWillDetach");
paulmeyerfeafc2d2017-04-25 21:46:408291 WebContentsImpl* outermost = GetOutermostWebContents();
8292 if (this != outermost && ContainsOrIsFocusedWebContents())
8293 outermost->SetAsFocusedWebContentsIfNecessary();
8294}
8295
Becca Hughes112832e2019-06-11 17:19:028296PictureInPictureResult WebContentsImpl::EnterPictureInPicture(
Mounir Lamouri11e9ef42018-05-22 03:10:168297 const viz::SurfaceId& surface_id,
8298 const gfx::Size& natural_size) {
Alexander Timin5fdeff22020-09-08 09:20:378299 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::EnterPictureInPicture");
François Beaufortf09e4462019-01-18 14:34:518300 return delegate_
8301 ? delegate_->EnterPictureInPicture(this, surface_id, natural_size)
Becca Hughes112832e2019-06-11 17:19:028302 : PictureInPictureResult::kNotSupported;
Mounir Lamouri11e9ef42018-05-22 03:10:168303}
8304
Mounir Lamouri6d759e12018-05-16 20:01:308305void WebContentsImpl::ExitPictureInPicture() {
Alexander Timin5fdeff22020-09-08 09:20:378306 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ExitPictureInPicture");
Mounir Lamouri6d759e12018-05-16 20:01:308307 if (delegate_)
8308 delegate_->ExitPictureInPicture();
8309}
8310
paulmeyerc0b762b2016-04-13 11:55:178311#if defined(OS_ANDROID)
8312void WebContentsImpl::NotifyFindMatchRectsReply(
8313 int version,
8314 const std::vector<gfx::RectF>& rects,
8315 const gfx::RectF& active_rect) {
Alexander Timin5fdeff22020-09-08 09:20:378316 OPTIONAL_TRACE_EVENT0("content",
8317 "WebContentsImpl::NotifyFindMatchRectsReply");
paulmeyerc0b762b2016-04-13 11:55:178318 if (delegate_)
8319 delegate_->FindMatchRectsReply(this, version, rects, active_rect);
8320}
8321#endif
8322
[email protected]34ff1cfc2014-08-20 06:16:058323void WebContentsImpl::SetForceDisableOverscrollContent(bool force_disable) {
Alexander Timin5fdeff22020-09-08 09:20:378324 OPTIONAL_TRACE_EVENT1("content",
8325 "WebContentsImpl::SetForceDisableOverscrollContent",
8326 "force_disable", force_disable);
[email protected]34ff1cfc2014-08-20 06:16:058327 force_disable_overscroll_content_ = force_disable;
8328 if (view_)
8329 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
8330}
8331
Jianzhou Fengd8720c72018-01-18 03:06:308332bool WebContentsImpl::SetDeviceEmulationSize(const gfx::Size& new_size) {
Alexander Timin5fdeff22020-09-08 09:20:378333 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetDeviceEmulationSize");
Jianzhou Fengd8720c72018-01-18 03:06:308334 device_emulation_size_ = new_size;
8335 RenderWidgetHostView* rwhv = GetMainFrame()->GetView();
8336
8337 const gfx::Size current_size = rwhv->GetViewBounds().size();
8338 if (view_size_before_emulation_.IsEmpty())
8339 view_size_before_emulation_ = current_size;
8340
8341 if (current_size != new_size)
8342 rwhv->SetSize(new_size);
8343
8344 return current_size != new_size;
8345}
8346
8347void WebContentsImpl::ClearDeviceEmulationSize() {
Alexander Timin5fdeff22020-09-08 09:20:378348 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ClearDeviceEmulationSize");
Jianzhou Fengd8720c72018-01-18 03:06:308349 RenderWidgetHostView* rwhv = GetMainFrame()->GetView();
8350 // WebContentsView could get resized during emulation, which also resizes
8351 // RWHV. If it happens, assume user would like to keep using the size after
8352 // emulation.
8353 // TODO(jzfeng): Prohibit resizing RWHV through any other means (at least when
8354 // WebContentsView size changes).
Dmitry Gozmanc63707182018-03-06 00:09:398355 if (!view_size_before_emulation_.IsEmpty() && rwhv &&
8356 rwhv->GetViewBounds().size() == device_emulation_size_) {
Jianzhou Fengd8720c72018-01-18 03:06:308357 rwhv->SetSize(view_size_before_emulation_);
Dmitry Gozmanc63707182018-03-06 00:09:398358 }
Jianzhou Fengd8720c72018-01-18 03:06:308359 device_emulation_size_ = gfx::Size();
8360 view_size_before_emulation_ = gfx::Size();
8361}
8362
Max Morin5bc74f52018-05-09 07:00:218363ForwardingAudioStreamFactory* WebContentsImpl::GetAudioStreamFactory() {
8364 if (!audio_stream_factory_) {
8365 audio_stream_factory_.emplace(
8366 this,
Max Morinddebb972018-09-20 10:04:148367 // BrowserMainLoop::GetInstance() may be null in unit tests.
8368 BrowserMainLoop::GetInstance()
8369 ? static_cast<media::UserInputMonitorBase*>(
8370 BrowserMainLoop::GetInstance()->user_input_monitor())
8371 : nullptr,
Ken Rockot72964402019-12-06 10:40:518372 AudioStreamBrokerFactory::CreateImpl());
Max Morin5bc74f52018-05-09 07:00:218373 }
8374
8375 return &*audio_stream_factory_;
8376}
8377
dalecurtis88c240072015-12-09 02:11:188378void WebContentsImpl::MediaStartedPlaying(
billorr21c005d2016-11-17 03:57:048379 const WebContentsObserver::MediaPlayerInfo& media_info,
Mounir Lamouri0f5bdf52019-04-04 16:32:358380 const MediaPlayerId& id) {
Alexander Timin5fdeff22020-09-08 09:20:378381 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MediaStartedPlaying");
billorr21c005d2016-11-17 03:57:048382 if (media_info.has_video)
8383 currently_playing_video_count_++;
8384
Alexander Timin90c20c32020-08-12 15:28:328385 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8386 observer->MediaStartedPlaying(media_info, id);
8387 });
dalecurtis88c240072015-12-09 02:11:188388}
8389
8390void WebContentsImpl::MediaStoppedPlaying(
billorr21c005d2016-11-17 03:57:048391 const WebContentsObserver::MediaPlayerInfo& media_info,
Mounir Lamouri0f5bdf52019-04-04 16:32:358392 const MediaPlayerId& id,
Becca Hughes220bfc102017-11-14 18:24:078393 WebContentsObserver::MediaStoppedReason reason) {
Alexander Timin5fdeff22020-09-08 09:20:378394 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MediaStoppedPlaying");
billorr21c005d2016-11-17 03:57:048395 if (media_info.has_video)
8396 currently_playing_video_count_--;
8397
Alexander Timin90c20c32020-08-12 15:28:328398 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8399 observer->MediaStoppedPlaying(media_info, id, reason);
8400 });
billorr21c005d2016-11-17 03:57:048401}
8402
Mounir Lamouri0f5bdf52019-04-04 16:32:358403void WebContentsImpl::MediaResized(const gfx::Size& size,
8404 const MediaPlayerId& id) {
Alexander Timin5fdeff22020-09-08 09:20:378405 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MediaResized");
peconn257951522017-06-09 18:24:598406 cached_video_sizes_[id] = size;
8407
Alexander Timin90c20c32020-08-12 15:28:328408 observers_.ForEachObserver(
8409 [&](WebContentsObserver* observer) { observer->MediaResized(size, id); });
peconn257951522017-06-09 18:24:598410}
8411
Michael Crousee75c7a42020-07-31 21:11:558412void WebContentsImpl::MediaBufferUnderflow(const MediaPlayerId& id) {
Alexander Timin5fdeff22020-09-08 09:20:378413 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MediaBufferUnderflow");
Alexander Timin90c20c32020-08-12 15:28:328414 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8415 observer->MediaBufferUnderflow(id);
8416 });
Michael Crousee75c7a42020-07-31 21:11:558417}
8418
rajendrant4c288462020-10-13 07:35:358419void WebContentsImpl::MediaPlayerSeek(const MediaPlayerId& id) {
8420 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MediaPlayerSeek");
8421 observers_.ForEachObserver(
8422 [&](WebContentsObserver* observer) { observer->MediaPlayerSeek(id); });
8423}
8424
Peter E Conneccb34c22017-09-08 09:37:588425void WebContentsImpl::MediaEffectivelyFullscreenChanged(bool is_fullscreen) {
Alexander Timin5fdeff22020-09-08 09:20:378426 OPTIONAL_TRACE_EVENT1("content",
8427 "WebContentsImpl::MediaEffectivelyFullscreenChanged",
8428 "is_fullscreen", is_fullscreen);
Alexander Timin90c20c32020-08-12 15:28:328429 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8430 observer->MediaEffectivelyFullscreenChanged(is_fullscreen);
8431 });
Peter E Conneccb34c22017-09-08 09:37:588432}
8433
Peter Conn31c726a2017-08-17 11:07:348434base::Optional<gfx::Size> WebContentsImpl::GetFullscreenVideoSize() {
Mounir Lamouri0f5bdf52019-04-04 16:32:358435 base::Optional<MediaPlayerId> id =
Peter Conn31c726a2017-08-17 11:07:348436 media_web_contents_observer_->GetFullscreenVideoMediaPlayerId();
Jan Wilken Dörrie531be7ca2019-06-07 10:05:578437 if (id && base::Contains(cached_video_sizes_, id.value()))
Peter Conn31c726a2017-08-17 11:07:348438 return base::Optional<gfx::Size>(cached_video_sizes_[id.value()]);
Lei Zhang6410ec1a2019-01-31 21:38:588439 return base::nullopt;
peconn257951522017-06-09 18:24:598440}
8441
billorr21c005d2016-11-17 03:57:048442int WebContentsImpl::GetCurrentlyPlayingVideoCount() {
8443 return currently_playing_video_count_;
dalecurtis88c240072015-12-09 02:11:188444}
8445
Raymond Toye413650c2018-08-31 00:12:478446void WebContentsImpl::AudioContextPlaybackStarted(RenderFrameHost* host,
8447 int context_id) {
Alexander Timin5fdeff22020-09-08 09:20:378448 OPTIONAL_TRACE_EVENT1(
8449 "content", "WebContentsImpl::AudioContextPlaybackStarted",
8450 "render_frame_host", base::trace_event::ToTracedValue(host));
Raymond Toye413650c2018-08-31 00:12:478451 WebContentsObserver::AudioContextId audio_context_id(host, context_id);
Alexander Timin90c20c32020-08-12 15:28:328452 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8453 observer->AudioContextPlaybackStarted(audio_context_id);
8454 });
Raymond Toye413650c2018-08-31 00:12:478455}
8456
8457void WebContentsImpl::AudioContextPlaybackStopped(RenderFrameHost* host,
8458 int context_id) {
Alexander Timin5fdeff22020-09-08 09:20:378459 OPTIONAL_TRACE_EVENT1(
8460 "content", "WebContentsImpl::AudioContextPlaybackStopped",
8461 "render_frame_host", base::trace_event::ToTracedValue(host));
Raymond Toye413650c2018-08-31 00:12:478462 WebContentsObserver::AudioContextId audio_context_id(host, context_id);
Alexander Timin90c20c32020-08-12 15:28:328463 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8464 observer->AudioContextPlaybackStopped(audio_context_id);
8465 });
Raymond Toye413650c2018-08-31 00:12:478466}
8467
Chris Hamilton16ca64a2020-05-14 23:13:178468void WebContentsImpl::OnFrameAudioStateChanged(RenderFrameHost* host,
8469 bool is_audible) {
Alexander Timin5fdeff22020-09-08 09:20:378470 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnFrameAudioStateChanged",
8471 "render_frame_host",
8472 base::trace_event::ToTracedValue(host), "is_audible",
8473 is_audible);
Alexander Timin90c20c32020-08-12 15:28:328474 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8475 observer->OnFrameAudioStateChanged(host, is_audible);
8476 });
Chris Hamilton16ca64a2020-05-14 23:13:178477}
8478
evliu7f736f02019-11-07 17:43:508479media::MediaMetricsProvider::RecordAggregateWatchTimeCallback
8480WebContentsImpl::GetRecordAggregateWatchTimeCallback() {
Alexander Timin5fdeff22020-09-08 09:20:378481 OPTIONAL_TRACE_EVENT0("content",
8482 "WebContentsImpl::RecordAggregateWatchTimeCallback");
Becca Hughes53652442020-03-17 15:35:428483 if (!delegate_ || !delegate_->GetDelegateWeakPtr())
8484 return base::DoNothing();
8485
evliu7f736f02019-11-07 17:43:508486 return base::BindRepeating(
Becca Hughes53652442020-03-17 15:35:428487 [](base::WeakPtr<WebContentsDelegate> delegate, GURL last_committed_url,
8488 base::TimeDelta total_watch_time, base::TimeDelta time_stamp,
8489 bool has_video, bool has_audio) {
evliua283c9e2019-11-08 22:57:228490 content::MediaPlayerWatchTime watch_time(
8491 last_committed_url, last_committed_url.GetOrigin(),
8492 total_watch_time, time_stamp, has_video, has_audio);
evliu7f736f02019-11-07 17:43:508493
8494 // Save the watch time if the delegate is still alive.
8495 if (delegate)
8496 delegate->MediaWatchTimeChanged(watch_time);
8497 },
Becca Hughes53652442020-03-17 15:35:428498 delegate_->GetDelegateWeakPtr(), GetMainFrameLastCommittedURL());
evliu7f736f02019-11-07 17:43:508499}
8500
Ehsan Karamad1c631762019-05-13 23:04:018501RenderFrameHostImpl* WebContentsImpl::GetMainFrameForInnerDelegate(
8502 FrameTreeNode* frame_tree_node) {
8503 if (auto* web_contents = node_.GetInnerWebContentsInFrame(frame_tree_node))
8504 return web_contents->GetMainFrame();
8505 return nullptr;
8506}
8507
John Budorickee1c9512019-10-17 15:32:198508bool WebContentsImpl::IsFrameLowPriority(
8509 const RenderFrameHost* render_frame_host) {
8510 if (!delegate_)
8511 return false;
8512 return delegate_->IsFrameLowPriority(this, render_frame_host);
8513}
8514
Roger Tawa03ffdbd2020-01-16 18:12:548515void WebContentsImpl::IsClipboardPasteAllowed(
8516 const GURL& url,
8517 const ui::ClipboardFormatType& data_type,
8518 const std::string& data,
8519 IsClipboardPasteAllowedCallback callback) {
Dominique Fauteux-Chapleau99244382020-07-08 20:37:008520 ++suppress_unresponsive_renderer_count_;
Roger Tawa03ffdbd2020-01-16 18:12:548521 GetContentClient()->browser()->IsClipboardPasteAllowed(
Dominique Fauteux-Chapleau99244382020-07-08 20:37:008522 this, url, data_type, data,
8523 base::BindOnce(&WebContentsImpl::IsClipboardPasteAllowedWrapperCallback,
8524 weak_factory_.GetWeakPtr(), std::move(callback)));
8525}
8526
8527void WebContentsImpl::IsClipboardPasteAllowedWrapperCallback(
8528 IsClipboardPasteAllowedCallback callback,
8529 ClipboardPasteAllowed allowed) {
8530 std::move(callback).Run(allowed);
8531 --suppress_unresponsive_renderer_count_;
Roger Tawa03ffdbd2020-01-16 18:12:548532}
8533
Lan Weif81c6e7c2020-02-12 16:46:098534bool WebContentsImpl::HasSeenRecentScreenOrientationChange() {
8535 static constexpr base::TimeDelta kMaxInterval =
8536 base::TimeDelta::FromSeconds(1);
8537 base::TimeDelta delta =
8538 ui::EventTimeForNow() - last_screen_orientation_change_time_;
Mike Wassermandb8f4f02020-10-06 01:18:378539 // Return whether a screen orientation change happened in the last 1 second.
Lan Weif81c6e7c2020-02-12 16:46:098540 return delta <= kMaxInterval;
8541}
8542
Mike Wassermandb8f4f02020-10-06 01:18:378543bool WebContentsImpl::IsTransientAllowFullscreenActive() const {
8544 return transient_allow_fullscreen_.IsActive();
8545}
8546
Lan Weif81c6e7c2020-02-12 16:46:098547void WebContentsImpl::DidChangeScreenOrientation() {
8548 last_screen_orientation_change_time_ = ui::EventTimeForNow();
8549}
8550
Miyoung Shin8f2e1832020-04-27 09:00:028551bool WebContentsImpl::ShowPopupMenu(
Miyoung Shin4d947d22020-04-24 04:48:338552 RenderFrameHostImpl* render_frame_host,
Miyoung Shin8f2e1832020-04-27 09:00:028553 mojo::PendingRemote<blink::mojom::PopupMenuClient>* popup_client,
Miyoung Shin4d947d22020-04-24 04:48:338554 const gfx::Rect& bounds,
8555 int32_t item_height,
8556 double font_size,
8557 int32_t selected_item,
8558 std::vector<blink::mojom::MenuItemPtr>* menu_items,
8559 bool right_aligned,
8560 bool allow_multiple_selection) {
Alexander Timin5fdeff22020-09-08 09:20:378561 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ShowPopupMenu",
8562 "render_frame_host",
8563 base::trace_event::ToTracedValue(render_frame_host));
Alexander Timin90c20c32020-08-12 15:28:328564 for (auto& observer : observers_.observer_list()) {
Miyoung Shin8f2e1832020-04-27 09:00:028565 if (observer.ShowPopupMenu(render_frame_host, popup_client, bounds,
8566 item_height, font_size, selected_item,
8567 menu_items, right_aligned,
8568 allow_multiple_selection)) {
Miyoung Shin4d947d22020-04-24 04:48:338569 return true;
8570 }
8571 }
8572 return false;
8573}
8574
Francois Doraye6161152018-03-27 22:05:378575void WebContentsImpl::UpdateWebContentsVisibility(Visibility visibility) {
Alexander Timin5fdeff22020-09-08 09:20:378576 OPTIONAL_TRACE_EVENT1("content",
8577 "WebContentsImpl::UpdateWebContentsVisibility",
8578 "visibility", visibility);
Francois Doray3f2afbd2018-04-06 19:18:188579 // Occlusion is disabled when |features::kWebContentsOcclusion| is disabled
8580 // (for power and speed impact assessment) or when
8581 // |switches::kDisableBackgroundingOccludedWindowsForTesting| is specified on
8582 // the command line (to avoid flakiness in browser tests).
8583 const bool occlusion_is_disabled =
8584 !base::FeatureList::IsEnabled(features::kWebContentsOcclusion) ||
Francois Doraye6161152018-03-27 22:05:378585 base::CommandLine::ForCurrentProcess()->HasSwitch(
8586 switches::kDisableBackgroundingOccludedWindowsForTesting);
8587 if (occlusion_is_disabled && visibility == Visibility::OCCLUDED)
8588 visibility = Visibility::VISIBLE;
8589
tapted65ff2ea72016-03-01 23:39:008590 if (!did_first_set_visible_) {
Francois Doraye6161152018-03-27 22:05:378591 if (visibility == Visibility::VISIBLE) {
8592 // A WebContents created with CreateParams::initially_hidden = false
8593 // starts with GetVisibility() == Visibility::VISIBLE even though it is
8594 // not really visible. Call WasShown() when it becomes visible for real as
8595 // the page load mechanism and some WebContentsObserver rely on that.
tapted65ff2ea72016-03-01 23:39:008596 WasShown();
Francois Dorayfe4a1772018-02-17 04:17:098597 did_first_set_visible_ = true;
tapted65ff2ea72016-03-01 23:39:008598 }
Francois Doraye6161152018-03-27 22:05:378599
8600 // Trust the initial visibility of the WebContents and do not switch it to
8601 // HIDDEN or OCCLUDED before it becomes VISIBLE for real. Doing so would
8602 // result in destroying resources that would immediately be recreated (e.g.
8603 // UpdateWebContents(HIDDEN) can be called when a WebContents is added to a
8604 // hidden window that is about to be shown).
8605
tapted65ff2ea72016-03-01 23:39:008606 return;
8607 }
Francois Doraye6161152018-03-27 22:05:378608
8609 if (visibility == visibility_)
tapted65ff2ea72016-03-01 23:39:008610 return;
8611
Collin Baker989e0882019-11-01 01:27:178612 UpdateVisibilityAndNotifyPageAndView(visibility);
tapted65ff2ea72016-03-01 23:39:008613}
8614
aelias5252baa2016-04-10 01:18:028615void WebContentsImpl::UpdateOverridingUserAgent() {
Alexander Timin5fdeff22020-09-08 09:20:378616 OPTIONAL_TRACE_EVENT0("content",
8617 "WebContentsImpl::UpdateOverridingUserAgent");
mlamouri5cd9ae82017-02-18 11:05:098618 NotifyPreferencesChanged();
aelias5252baa2016-04-10 01:18:028619}
8620
avid53461d2016-02-25 17:15:048621void WebContentsImpl::SetJavaScriptDialogManagerForTesting(
8622 JavaScriptDialogManager* dialog_manager) {
Alexander Timin5fdeff22020-09-08 09:20:378623 OPTIONAL_TRACE_EVENT0(
8624 "content", "WebContentsImpl::SetJavaScriptDialogManagerForTesting");
avid53461d2016-02-25 17:15:048625 dialog_manager_ = dialog_manager;
8626}
8627
Julie Jeongeun Kim7d0986172019-12-04 03:17:258628void WebContentsImpl::RemoveReceiverSet(const std::string& interface_name) {
Alexander Timin5fdeff22020-09-08 09:20:378629 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RemoveReceiverSet",
8630 "interface_name", interface_name);
Julie Jeongeun Kim7d0986172019-12-04 03:17:258631 auto it = receiver_sets_.find(interface_name);
8632 if (it != receiver_sets_.end())
8633 receiver_sets_.erase(it);
rockotf62002a2016-09-15 00:08:598634}
8635
nzolghadrd87a308d2016-12-07 15:45:568636bool WebContentsImpl::AddDomainInfoToRapporSample(rappor::Sample* sample) {
Alexander Timin5fdeff22020-09-08 09:20:378637 OPTIONAL_TRACE_EVENT0("content",
8638 "WebContentsImpl::AddDomainInfoToRapporSample");
nzolghadrbbffc6c2017-05-25 17:56:398639 // Here we associate this metric to the main frame URL regardless of what
8640 // caused it.
nzolghadrd87a308d2016-12-07 15:45:568641 sample->SetStringField("Domain", ::rappor::GetDomainAndRegistrySampleFromGURL(
8642 GetLastCommittedURL()));
nzolghadrd87a308d2016-12-07 15:45:568643 return true;
8644}
8645
falken52a56e32016-12-08 05:02:408646void WebContentsImpl::ShowInsecureLocalhostWarningIfNeeded() {
Alexander Timin5fdeff22020-09-08 09:20:378647 OPTIONAL_TRACE_EVENT0(
8648 "content", "WebContentsImpl::ShowInsecureLocalhostWarningIfNeeded");
falken52a56e32016-12-08 05:02:408649 bool allow_localhost = base::CommandLine::ForCurrentProcess()->HasSwitch(
8650 switches::kAllowInsecureLocalhost);
8651 if (!allow_localhost)
8652 return;
8653
8654 content::NavigationEntry* entry = GetController().GetLastCommittedEntry();
Rob Wuf79b3ba2018-01-14 01:54:318655 if (!entry || !net::IsLocalhost(entry->GetURL()))
falken52a56e32016-12-08 05:02:408656 return;
8657
8658 content::SSLStatus ssl_status = entry->GetSSL();
Matt Mueller936511442019-09-03 18:15:128659 if (!net::IsCertStatusError(ssl_status.cert_status))
falken52a56e32016-12-08 05:02:408660 return;
8661
8662 GetMainFrame()->AddMessageToConsole(
Abhijeet Kandalkara5928a0a2019-03-13 05:04:428663 blink::mojom::ConsoleMessageLevel::kWarning,
falken52a56e32016-12-08 05:02:408664 base::StringPrintf("This site does not have a valid SSL "
8665 "certificate! Without SSL, your site's and "
8666 "visitors' data is vulnerable to theft and "
8667 "tampering. Get a valid SSL certificate before"
8668 " releasing your website to the public."));
8669}
8670
ekaramadf6750aa2017-06-06 18:29:428671bool WebContentsImpl::IsShowingContextMenuOnPage() const {
8672 return showing_context_menu_;
8673}
8674
Min Qina904f3302018-02-13 23:33:348675download::DownloadUrlParameters::RequestHeadersType
8676WebContentsImpl::ParseDownloadHeaders(const std::string& headers) {
Alexander Timin5fdeff22020-09-08 09:20:378677 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ParseDownloadHeaders",
8678 "headers", headers);
Min Qina904f3302018-02-13 23:33:348679 download::DownloadUrlParameters::RequestHeadersType request_headers;
Megan Jablonski2f6a4c52017-07-10 23:01:258680 for (const base::StringPiece& key_value : base::SplitStringPiece(
8681 headers, "\r\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) {
8682 std::vector<std::string> pair = base::SplitString(
8683 key_value, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
8684 if (2ul == pair.size())
8685 request_headers.push_back(make_pair(pair[0], pair[1]));
8686 }
8687 return request_headers;
8688}
8689
lukasza6f8ac622017-06-06 03:10:208690void WebContentsImpl::SetOpenerForNewContents(FrameTreeNode* opener,
8691 bool opener_suppressed) {
Alexander Timin5fdeff22020-09-08 09:20:378692 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetOpenerForNewContents");
lukasza6f8ac622017-06-06 03:10:208693 if (opener) {
8694 FrameTreeNode* new_root = GetFrameTree()->root();
8695
8696 // For the "original opener", track the opener's main frame instead, because
8697 // if the opener is a subframe, the opener tracking could be easily bypassed
8698 // by spawning from a subframe and deleting the subframe.
8699 // https://crbug.com/705316
8700 new_root->SetOriginalOpener(opener->frame_tree()->root());
Wolfgang Beyerd8809db2020-09-30 15:29:398701 new_root->SetOpenerDevtoolsFrameToken(opener->devtools_frame_token());
lukasza6f8ac622017-06-06 03:10:208702
8703 if (!opener_suppressed) {
8704 new_root->SetOpener(opener);
8705 created_with_opener_ = true;
8706 }
8707 }
8708}
8709
Mounir Lamouri0f5bdf52019-04-04 16:32:358710void WebContentsImpl::MediaMutedStatusChanged(const MediaPlayerId& id,
8711 bool muted) {
Alexander Timin5fdeff22020-09-08 09:20:378712 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::MediaMutedStatusChanged",
8713 "muted", muted);
Alexander Timin90c20c32020-08-12 15:28:328714 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8715 observer->MediaMutedStatusChanged(id, muted);
8716 });
Becca Hughes9f6fd4b82017-06-15 10:01:408717}
8718
EhsanK2075c7e2017-08-21 02:42:398719void WebContentsImpl::SetVisibilityForChildViews(bool visible) {
Alexander Timin5fdeff22020-09-08 09:20:378720 OPTIONAL_TRACE_EVENT1("content",
8721 "WebContentsImpl::SetVisibilityForChildViews",
8722 "visible", visible);
EhsanK2075c7e2017-08-21 02:42:398723 GetMainFrame()->SetVisibilityForChildViews(visible);
8724}
8725
Alison Maher7f366dc62020-03-03 19:46:008726void WebContentsImpl::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) {
Alexander Timin5fdeff22020-09-08 09:20:378727 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnNativeThemeUpdated");
Alison Maher7f366dc62020-03-03 19:46:008728 DCHECK(native_theme_observer_.IsObserving(observed_theme));
8729
8730 bool using_dark_colors = observed_theme->ShouldUseDarkColors();
8731 ui::NativeTheme::PreferredColorScheme preferred_color_scheme =
8732 observed_theme->GetPreferredColorScheme();
8733 bool preferences_changed = false;
8734
8735 if (using_dark_colors_ != using_dark_colors) {
8736 using_dark_colors_ = using_dark_colors;
8737 preferences_changed = true;
8738 }
8739 if (preferred_color_scheme_ != preferred_color_scheme) {
8740 preferred_color_scheme_ = preferred_color_scheme;
8741 preferences_changed = true;
8742 }
8743
8744 if (preferences_changed)
8745 NotifyPreferencesChanged();
8746}
8747
Dave Tapuska58a099e2020-06-08 21:48:408748blink::mojom::FrameWidgetInputHandler*
8749WebContentsImpl::GetFocusedFrameWidgetInputHandler() {
8750 auto* focused_render_widget_host =
8751 GetFocusedRenderWidgetHost(GetMainFrame()->GetRenderWidgetHost());
8752 if (!focused_render_widget_host)
Dave Tapuskae782bea2019-07-09 16:21:518753 return nullptr;
Dave Tapuska58a099e2020-06-08 21:48:408754 return focused_render_widget_host->GetFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:518755}
8756
Alexander Timine3ec4192020-04-20 16:39:408757ukm::SourceId WebContentsImpl::GetCurrentPageUkmSourceId() {
8758 return GetMainFrame()->GetPageUkmSourceId();
8759}
8760
Yuzu Saijo232076f2020-05-29 07:14:028761std::set<RenderViewHostImpl*>
8762WebContentsImpl::GetRenderViewHostsIncludingBackForwardCached() {
8763 std::set<RenderViewHostImpl*> render_view_hosts;
8764
8765 // Add RenderViewHostImpls outside of BackForwardCache.
8766 for (auto& render_view_host : frame_tree_.render_view_hosts()) {
8767 render_view_hosts.insert(render_view_host.second);
8768 }
8769
8770 // Add RenderViewHostImpls in BackForwardCache.
8771 const auto& entries = GetController().GetBackForwardCache().GetEntries();
8772 for (const auto& entry : entries) {
8773 std::set<RenderViewHostImpl*> bfcached_hosts = entry->render_view_hosts;
8774 render_view_hosts.insert(bfcached_hosts.begin(), bfcached_hosts.end());
8775 }
8776
8777 return render_view_hosts;
8778}
8779
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:508780void WebContentsImpl::RenderFrameHostStateChanged(
8781 RenderFrameHost* render_frame_host,
8782 LifecycleState old_state,
8783 LifecycleState new_state) {
Alexander Timin5fdeff22020-09-08 09:20:378784 OPTIONAL_TRACE_EVENT2(
8785 "content", "WebContentsImpl::RenderFrameHostStateChanged",
8786 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host),
8787 "states",
8788 base::trace_event::TracedValue::Build(
8789 {{"old", base::trace_event::ValueToString(old_state)},
8790 {"new", base::trace_event::ValueToString(new_state)}}));
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:508791 if (render_frame_host->GetParent())
8792 return;
8793
8794 if (old_state == LifecycleState::kActive &&
8795 new_state != LifecycleState::kActive) {
8796 // TODO(sreejakshetty): Remove this reset when ColorChooser becomes
8797 // per-frame.
8798 // Close the color chooser popup when RenderFrameHost changes state from
8799 // kActive.
8800 color_chooser_.reset();
8801 }
8802}
8803
danakjc5ce67602020-09-23 20:06:578804void WebContentsImpl::GetFrameSequenceNumbersForDebugging(
8805 RenderFrameHostImpl* render_frame_host,
8806 int64_t& item_sequence_number,
8807 int64_t& document_sequence_number) {
8808 NavigationEntryImpl* entry =
8809 controller_.GetEntryWithUniqueID(render_frame_host->nav_entry_id());
8810 if (!entry)
8811 return;
8812
8813 FrameNavigationEntry* frame_entry =
8814 entry->GetFrameEntry(render_frame_host->frame_tree_node());
8815 if (frame_entry) {
8816 item_sequence_number = frame_entry->item_sequence_number();
8817 document_sequence_number = frame_entry->document_sequence_number();
8818 }
8819}
8820
[email protected]8ff00d72012-10-23 19:12:218821} // namespace content