blob: f99748c1cb375c2d4f4cd60c56e7941c468d52dc [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),
alexmosc9e76ec2016-05-16 22:59:37823 fullscreen_widget_process_id_(ChildProcessHost::kInvalidUniqueID),
[email protected]5dcaf8e2013-12-28 01:31:42824 fullscreen_widget_routing_id_(MSG_ROUTING_NONE),
[email protected]0b431992014-06-24 00:08:03825 fullscreen_widget_had_focus_at_shutdown_(false),
[email protected]34ff1cfc2014-08-20 06:16:05826 force_disable_overscroll_content_(false),
[email protected]95640212014-07-26 18:14:30827 last_dialog_suppressed_(false),
waffles1c12bf402016-02-10 17:45:48828 accessibility_mode_(
Dominic Mazzoni21fb0282019-02-13 18:32:47829 GetContentClient()->browser()->GetAXModeForBrowserContext(
830 browser_context)),
avayvodcc85bbd2015-08-28 19:11:15831 audio_stream_monitor_(this),
Thomas Guilbert882c4cec2019-02-14 05:55:45832 media_web_contents_observer_(
833 std::make_unique<MediaWebContentsObserver>(this)),
mcnee336ea2c2017-05-23 22:50:59834#if !defined(OS_ANDROID)
mcnee432e47d2015-11-09 19:37:46835 page_scale_factor_is_one_(true),
mcnee336ea2c2017-05-23 22:50:59836#endif // !defined(OS_ANDROID)
qinmin72e8bd02016-10-21 19:35:37837 is_overlay_content_(false),
ekaramadf6750aa2017-06-06 18:29:42838 showing_context_menu_(false),
W. James MacLean62198672019-06-04 16:46:10839 text_autosizer_page_info_({0, 0, 1.f}),
shivanigithubcceeacf2020-03-06 20:00:27840 native_theme_observer_(this) {
Alexander Timin5fdeff22020-09-08 09:20:37841 TRACE_EVENT0("content", "WebContentsImpl::WebContentsImpl");
danakjf4b9e942019-11-29 15:43:04842 frame_tree_.SetFrameRemoveListener(base::BindRepeating(
843 &WebContentsImpl::OnFrameRemoved, base::Unretained(this)));
brettw4b461082016-11-19 18:55:16844#if BUILDFLAG(ENABLE_PLUGINS)
Fergal Daly55b6d722020-09-11 07:56:33845 pepper_playback_observer_ = std::make_unique<PepperPlaybackObserver>(this);
zqzhang181047e62016-07-01 13:37:17846#endif
blundelle75a8f92017-03-27 08:11:17847
Becca Hughes86334622018-07-09 21:29:38848#if defined(OS_ANDROID)
Elly Fong-Jonescdd7ae82019-02-20 23:26:33849 display_cutout_host_impl_ = std::make_unique<DisplayCutoutHostImpl>(this);
Becca Hughes86334622018-07-09 21:29:38850#endif
John Delaney732721e92020-02-07 23:11:27851
Alison Maher7f366dc62020-03-03 19:46:00852 ui::NativeTheme* native_theme = ui::NativeTheme::GetInstanceForWeb();
853 native_theme_observer_.Add(native_theme);
854 using_dark_colors_ = native_theme->ShouldUseDarkColors();
855 preferred_color_scheme_ = native_theme->GetPreferredColorScheme();
856
Mike Wassermanb213b9352020-04-16 00:32:34857 screen_change_monitor_ =
858 std::make_unique<ScreenChangeMonitor>(base::BindRepeating(
859 &WebContentsImpl::OnScreensChange, base::Unretained(this)));
860
John Delaney732721e92020-02-07 23:11:27861 // ConversionHost takes a weak ref on |this|, so it must be created outside of
862 // the initializer list.
Charlie Harrison405f6212020-04-14 21:57:32863 if (base::FeatureList::IsEnabled(features::kConversionMeasurement)) {
864 conversion_host_ = std::make_unique<ConversionHost>(this);
865 }
[email protected]332af7732009-03-11 13:21:35866}
initial.commit09911bf2008-07-26 23:55:29867
[email protected]b172aee2012-04-10 17:05:26868WebContentsImpl::~WebContentsImpl() {
Alexander Timin5fdeff22020-09-08 09:20:37869 TRACE_EVENT0("content", "WebContentsImpl::~WebContentsImpl");
870
creisba91ba82017-05-12 22:56:19871 // Imperfect sanity check against double free, given some crashes unexpectedly
872 // observed in the wild.
873 CHECK(!is_being_destroyed_);
874
875 // We generally keep track of is_being_destroyed_ to let other features know
876 // to avoid certain actions during destruction.
[email protected]420ae012009-04-24 05:16:32877 is_being_destroyed_ = true;
878
creis97867aa2017-02-17 18:39:45879 // A WebContents should never be deleted while it is notifying observers,
creisba91ba82017-05-12 22:56:19880 // since this will lead to a use-after-free as it continues to notify later
creis97867aa2017-02-17 18:39:45881 // observers.
Alexander Timin90c20c32020-08-12 15:28:32882 CHECK(!observers_.is_notifying_observers());
creis97867aa2017-02-17 18:39:45883
Avi Drissman33972942020-06-19 14:16:01884 FullscreenContentsSet(GetBrowserContext())->erase(this);
885
kenrb2a565f82015-09-02 20:24:59886 rwh_input_event_router_.reset();
887
Julie Jeongeun Kim7d0986172019-12-04 03:17:25888 for (auto& entry : receiver_sets_)
889 entry.second->CloseAllReceivers();
rockotf62002a2016-09-15 00:08:59890
avallee0206f782016-07-28 18:55:33891 WebContentsImpl* outermost = GetOutermostWebContents();
avallee9993fca2016-11-17 06:16:50892 if (this != outermost && ContainsOrIsFocusedWebContents()) {
avallee0206f782016-07-28 18:55:33893 // If the current WebContents is in focus, unset it.
avallee9993fca2016-11-17 06:16:50894 outermost->SetAsFocusedWebContentsIfNecessary();
avallee0206f782016-07-28 18:55:33895 }
896
Nick Carterd73635b2018-03-13 18:31:41897 if (mouse_lock_widget_)
James Hollyerd5c9de462020-03-10 19:02:45898 mouse_lock_widget_->RejectMouseLockOrUnlockIfNecessary(
899 blink::mojom::PointerLockResult::kElementDestroyed);
Nick Carterd73635b2018-03-13 18:31:41900
dcheng72be33c2016-01-21 04:11:31901 for (FrameTreeNode* node : frame_tree_.Nodes()) {
902 // Delete all RFHs pending shutdown, which will lead the corresponding RVHs
903 // to be shutdown and be deleted as well.
dcheng57e39e22016-01-21 00:25:38904 node->render_manager()->ClearRFHsPendingShutdown();
dcheng57e39e22016-01-21 00:25:38905 node->render_manager()->ClearWebUIInstances();
dcheng72be33c2016-01-21 04:11:31906 }
carlosk35f35af2015-12-01 10:55:40907
dcheng57e39e22016-01-21 00:25:38908 for (RenderWidgetHostImpl* widget : created_widgets_)
909 widget->DetachDelegate();
[email protected]b24b68a2012-09-24 21:57:26910 created_widgets_.clear();
911
[email protected]3ab9cb82011-06-03 18:02:07912 // Clear out any JavaScript state.
avi5d3b8692016-10-12 22:00:46913 if (dialog_manager_) {
avi6879fcf2017-01-21 05:27:53914 dialog_manager_->CancelDialogs(this, /*reset_state=*/true);
avi5d3b8692016-10-12 22:00:46915 }
[email protected]3ab9cb82011-06-03 18:02:07916
Joel Hockey85b379d2017-12-11 10:42:13917 color_chooser_.reset();
Rakina Zata Amni16196122018-11-14 02:14:00918 find_request_manager_.reset();
[email protected]da8543762012-03-20 08:52:20919
[email protected]420ae012009-04-24 05:16:32920 NotifyDisconnected();
[email protected]420ae012009-04-24 05:16:32921
[email protected]ca13a442012-04-17 14:00:12922 // Notify any observer that have a reference on this WebContents.
[email protected]8ff00d72012-10-23 19:12:21923 NotificationService::current()->Notify(
924 NOTIFICATION_WEB_CONTENTS_DESTROYED,
925 Source<WebContents>(this),
926 NotificationService::NoDetails());
[email protected]420ae012009-04-24 05:16:32927
Arthur Sonzogni5a9a88c2018-10-18 13:16:00928 // Destroy all subframes now. This notifies observers.
929 GetMainFrame()->ResetChildren();
[email protected]df0c843f2014-05-23 20:37:23930 GetRenderManager()->ResetProxyHosts();
[email protected]c06c58c2014-03-12 20:31:59931
clamy0e119882015-07-31 16:12:33932 // Manually call the observer methods for the root frame tree node. It is
933 // necessary to manually delete all objects tracking navigations
934 // (NavigationHandle, NavigationRequest) for observers to be properly
935 // notified of these navigations stopping before the WebContents is
936 // destroyed.
[email protected]df0c843f2014-05-23 20:37:23937 RenderFrameHostManager* root = GetRenderManager();
naskob21fe4872015-02-24 14:15:56938
Lowell Manners20250112019-10-18 15:06:15939 GetController().GetBackForwardCache().Shutdown();
940
naskob21fe4872015-02-24 14:15:56941 root->current_frame_host()->SetRenderFrameCreated(false);
clamyfc3850d2018-02-23 14:35:28942 root->current_frame_host()->ResetNavigationRequests();
clamy0e119882015-07-31 16:12:33943
Arthur Hemeryc3380172018-01-22 14:00:17944 // Do not update state as the WebContents is being destroyed.
Arthur Hemery241b9392019-10-24 11:08:41945 frame_tree_.root()->ResetNavigationRequest(true);
Arthur Hemeryc3380172018-01-22 14:00:17946 if (root->speculative_frame_host()) {
danakjf2342432019-05-15 21:46:09947 root->speculative_frame_host()->DeleteRenderFrame(
948 FrameDeleteIntention::kSpeculativeMainFrameForShutdown);
Arthur Hemeryc3380172018-01-22 14:00:17949 root->speculative_frame_host()->SetRenderFrameCreated(false);
clamyfc3850d2018-02-23 14:35:28950 root->speculative_frame_host()->ResetNavigationRequests();
clamy0e119882015-07-31 16:12:33951 }
[email protected]f273ee52013-10-18 16:05:27952
brettw4b461082016-11-19 18:55:16953#if BUILDFLAG(ENABLE_PLUGINS)
zqzhang181047e62016-07-01 13:37:17954 // Call this before WebContentsDestroyed() is broadcasted since
955 // AudioFocusManager will be destroyed after that.
956 pepper_playback_observer_.reset();
957#endif // defined(ENABLED_PLUGINS)
958
Chris Hamiltondf0d72cd2018-05-29 16:23:53959 // If audio is playing then notify external observers of the audio stream
960 // disappearing.
961 if (is_currently_audible_) {
962 is_currently_audible_ = false;
Alexander Timin90c20c32020-08-12 15:28:32963 observers_.ForEachObserver([&](WebContentsObserver* observer) {
964 observer->OnAudioStateChanged(false);
965 });
Chris Hamiltondf0d72cd2018-05-29 16:23:53966 if (GetOuterWebContents())
967 GetOuterWebContents()->OnAudioStateChanged();
968 }
969
Alexander Timin90c20c32020-08-12 15:28:32970 observers_.ForEachObserver([&](WebContentsObserver* observer) {
971 observer->FrameDeleted(root->current_frame_host());
972 });
973 observers_.ForEachObserver([&](WebContentsObserver* observer) {
974 observer->RenderViewDeleted(root->current_host());
975 });
Kevin McNee576bb5d82019-05-29 16:47:51976#if defined(OS_ANDROID)
977 // For simplicity, destroy the Java WebContents before we notify of the
978 // destruction of the WebContents.
979 ClearWebContentsAndroid();
980#endif
981
Alexander Timin90c20c32020-08-12 15:28:32982 observers_.ForEachObserver(
983 [&](WebContentsObserver* observer) { observer->WebContentsDestroyed(); });
Becca Hughesd11d6502018-07-31 17:01:28984 if (display_cutout_host_impl_)
985 display_cutout_host_impl_->WebContentsDestroyed();
986
Alexander Timin90c20c32020-08-12 15:28:32987 observers_.ForEachObserver(
988 [&](WebContentsObserver* observer) { observer->ResetWebContents(); });
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28989 SetDelegate(nullptr);
[email protected]b5a1d11c2011-02-17 03:09:42990}
991
erikchen50735fd2018-05-05 15:08:33992std::unique_ptr<WebContentsImpl> WebContentsImpl::CreateWithOpener(
[email protected]54944cde2012-12-09 09:24:59993 const WebContents::CreateParams& params,
Ian Clelland5cbaaf82017-11-27 22:00:03994 RenderFrameHostImpl* opener_rfh) {
Alexander Timin5fdeff22020-09-08 09:20:37995 OPTIONAL_TRACE_EVENT1("browser", "WebContentsImpl::CreateWithOpener",
996 "opener", base::trace_event::ToTracedValue(opener_rfh));
Ian Clelland5cbaaf82017-11-27 22:00:03997 FrameTreeNode* opener = nullptr;
998 if (opener_rfh)
999 opener = opener_rfh->frame_tree_node();
erikchen50735fd2018-05-05 15:08:331000 std::unique_ptr<WebContentsImpl> new_contents(
1001 new WebContentsImpl(params.browser_context));
lukasza6f8ac622017-06-06 03:10:201002 new_contents->SetOpenerForNewContents(opener, params.opener_suppressed);
alexmose201c7cd2015-06-10 17:14:211003
alexmosaedfc6f2016-01-21 23:57:381004 // If the opener is sandboxed, a new popup must inherit the opener's sandbox
1005 // flags, and these flags take effect immediately. An exception is if the
1006 // opener's sandbox flags lack the PropagatesToAuxiliaryBrowsingContexts
1007 // bit (which is controlled by the "allow-popups-to-escape-sandbox" token).
1008 // See https://html.spec.whatwg.org/#attr-iframe-sandbox.
lukasza6f8ac622017-06-06 03:10:201009 FrameTreeNode* new_root = new_contents->GetFrameTree()->root();
alexmosaedfc6f2016-01-21 23:57:381010 if (opener) {
arthursonzognib93a4472020-04-10 07:38:001011 network::mojom::WebSandboxFlags opener_flags =
Antonio Gomes7096ac02020-02-14 14:29:541012 opener_rfh->active_sandbox_flags();
arthursonzognib93a4472020-04-10 07:38:001013 const network::mojom::WebSandboxFlags inherit_flag =
1014 network::mojom::WebSandboxFlags::kPropagatesToAuxiliaryBrowsingContexts;
Ehsan Karamad39407082019-02-19 23:38:191015 bool sandbox_propagates_to_auxilary_context =
1016 (opener_flags & inherit_flag) == inherit_flag;
1017 if (sandbox_propagates_to_auxilary_context)
Charlie Hue1b77ac2019-12-13 21:30:171018 new_root->SetPendingFramePolicy({opener_flags,
1019 {} /* container_policy */,
1020 {} /* required_document_policy */});
arthursonzognib93a4472020-04-10 07:38:001021 if (opener_flags == network::mojom::WebSandboxFlags::kNone ||
Ehsan Karamad39407082019-02-19 23:38:191022 sandbox_propagates_to_auxilary_context) {
1023 // TODO(ekaramad, iclelland): Do not propagate feature policies from non-
1024 // sandboxed disowned openers (rel=noopener).
1025 // If the current page is not sandboxed, or if the sandbox is to propagate
1026 // to the popups then opener's feature policy will apply to the new popup
1027 // as well.
1028 new_root->SetOpenerFeaturePolicyState(
Ehsan Karamad34d10682019-02-26 20:55:041029 opener_rfh->feature_policy()->GetFeatureState());
alexmosaedfc6f2016-01-21 23:57:381030 }
arthursonzogni034bb9c2020-10-01 08:29:561031
1032 new_root->SetInitialPopupURL(params.initial_popup_url);
1033 new_root->SetPopupCreatorOrigin(opener_rfh->GetLastCommittedOrigin());
alexmosaedfc6f2016-01-21 23:57:381034 }
1035
mark a. foltzef394fce2017-10-21 09:11:021036 // Apply starting sandbox flags.
Luna Luc3fdacdf2017-11-08 04:48:531037 blink::FramePolicy frame_policy(new_root->pending_frame_policy());
mark a. foltzef394fce2017-10-21 09:11:021038 frame_policy.sandbox_flags |= params.starting_sandbox_flags;
1039 new_root->SetPendingFramePolicy(frame_policy);
Charlie Hu5ffc0152019-12-06 15:59:531040 new_root->CommitFramePolicy(frame_policy);
mark a. foltzef394fce2017-10-21 09:11:021041
alexmose201c7cd2015-06-10 17:14:211042 // This may be true even when opener is null, such as when opening blocked
1043 // popups.
alexmos090fae8e2015-05-28 17:09:281044 if (params.created_with_opener)
1045 new_contents->created_with_opener_ = true;
1046
Sean Toppingbbc4a2bd2019-01-30 02:16:141047 WebContentsImpl* outer_web_contents = nullptr;
[email protected]4858e432014-06-23 18:14:171048 if (params.guest_delegate) {
[email protected]83100cd2014-05-10 11:50:061049 // This makes |new_contents| act as a guest.
1050 // For more info, see comment above class BrowserPluginGuest.
Albert J. Wongc55cc64d2018-10-12 02:50:041051 BrowserPluginGuest::CreateInWebContents(new_contents.get(),
1052 params.guest_delegate);
Sean Toppingbbc4a2bd2019-01-30 02:16:141053 outer_web_contents = static_cast<WebContentsImpl*>(
1054 params.guest_delegate->GetOwnerWebContents());
[email protected]83100cd2014-05-10 11:50:061055 }
mark a. foltzef394fce2017-10-21 09:11:021056
[email protected]54944cde2012-12-09 09:24:591057 new_contents->Init(params);
Sean Toppingbbc4a2bd2019-01-30 02:16:141058 if (outer_web_contents)
1059 outer_web_contents->InnerWebContentsCreated(new_contents.get());
[email protected]d1198fd2012-08-13 22:50:191060 return new_contents;
1061}
1062
[email protected]95640212014-07-26 18:14:301063// static
1064std::vector<WebContentsImpl*> WebContentsImpl::GetAllWebContents() {
Alexander Timin5fdeff22020-09-08 09:20:371065 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1066 "WebContentsImpl::GetAllWebContents");
[email protected]95640212014-07-26 18:14:301067 std::vector<WebContentsImpl*> result;
dcheng59716272016-04-09 05:19:081068 std::unique_ptr<RenderWidgetHostIterator> widgets(
[email protected]95640212014-07-26 18:14:301069 RenderWidgetHostImpl::GetRenderWidgetHosts());
[email protected]95640212014-07-26 18:14:301070 while (RenderWidgetHost* rwh = widgets->GetNextHost()) {
[email protected]95640212014-07-26 18:14:301071 RenderViewHost* rvh = RenderViewHost::From(rwh);
1072 if (!rvh)
1073 continue;
1074 WebContents* web_contents = WebContents::FromRenderViewHost(rvh);
1075 if (!web_contents)
1076 continue;
avidf38c952015-10-27 13:45:131077 if (web_contents->GetRenderViewHost() != rvh)
1078 continue;
1079 // Because a WebContents can only have one current RVH at a time, there will
1080 // be no duplicate WebContents here.
1081 result.push_back(static_cast<WebContentsImpl*>(web_contents));
[email protected]95640212014-07-26 18:14:301082 }
1083 return result;
1084}
1085
clamya16aa8172015-05-26 13:07:251086// static
1087WebContentsImpl* WebContentsImpl::FromFrameTreeNode(
paulmeyerfeafc2d2017-04-25 21:46:401088 const FrameTreeNode* frame_tree_node) {
Alexander Timin5fdeff22020-09-08 09:20:371089 OPTIONAL_TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1090 "WebContentsImpl::FromFrameTreeNode", "frame_tree_node",
1091 frame_tree_node);
clamya16aa8172015-05-26 13:07:251092 return static_cast<WebContentsImpl*>(
1093 WebContents::FromRenderFrameHost(frame_tree_node->current_frame_host()));
1094}
1095
clamy0d32d6d2015-11-24 11:16:261096// static
Patrick Monette275a6f92b2020-01-09 21:05:041097WebContents* WebContentsImpl::FromRenderFrameHostID(
1098 GlobalFrameRoutingId render_frame_host_id) {
Alexander Timin5fdeff22020-09-08 09:20:371099 OPTIONAL_TRACE_EVENT2(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1100 "WebContentsImpl::FromRenderFrameHostID", "process_id",
1101 render_frame_host_id.child_id, "frame_id",
1102 render_frame_host_id.frame_routing_id);
Patrick Monette275a6f92b2020-01-09 21:05:041103 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI) ||
1104 !BrowserThread::IsThreadInitialized(BrowserThread::UI));
Patrick Monette7364e6972020-01-09 22:56:021105 RenderFrameHost* render_frame_host =
1106 RenderFrameHost::FromID(render_frame_host_id);
1107 if (!render_frame_host)
1108 return nullptr;
1109
1110 return WebContents::FromRenderFrameHost(render_frame_host);
Patrick Monette275a6f92b2020-01-09 21:05:041111}
1112
1113// static
clamy0d32d6d2015-11-24 11:16:261114WebContents* WebContentsImpl::FromRenderFrameHostID(int render_process_host_id,
1115 int render_frame_host_id) {
Patrick Monette7364e6972020-01-09 22:56:021116 return FromRenderFrameHostID(
1117 GlobalFrameRoutingId(render_process_host_id, render_frame_host_id));
clamy0d32d6d2015-11-24 11:16:261118}
1119
paulmeyerfeafc2d2017-04-25 21:46:401120// static
1121WebContentsImpl* WebContentsImpl::FromOuterFrameTreeNode(
1122 const FrameTreeNode* frame_tree_node) {
Alexander Timin5fdeff22020-09-08 09:20:371123 OPTIONAL_TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1124 "WebContentsImpl::FromOuterFrameTreeNode",
1125 "frame_tree_node", frame_tree_node);
paulmeyerfeafc2d2017-04-25 21:46:401126 return WebContentsImpl::FromFrameTreeNode(frame_tree_node)
1127 ->node_.GetInnerWebContentsInFrame(frame_tree_node);
1128}
1129
[email protected]b0936d22013-11-28 06:47:361130RenderFrameHostManager* WebContentsImpl::GetRenderManagerForTesting() {
[email protected]fa944cb82013-11-15 17:51:211131 return GetRenderManager();
[email protected]765187182012-01-11 23:59:281132}
1133
nicka0ac8382016-12-15 23:59:231134bool WebContentsImpl::OnMessageReceived(RenderViewHostImpl* render_view_host,
[email protected]7bb761892012-07-20 09:32:471135 const IPC::Message& message) {
Alexander Timin5fdeff22020-09-08 09:20:371136 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnMessageReceived",
1137 "render_view_host", render_view_host);
Alexander Timin90c20c32020-08-12 15:28:321138 for (auto& observer : observers_.observer_list()) {
Lukasz Anforowicz89f2c1b2017-08-30 21:36:461139 // TODO(nick, creis): https://crbug.com/758026: Replace all uses of this
1140 // variant of OnMessageReceived with the version that takes a
1141 // RenderFrameHost, and then delete it.
nicka0ac8382016-12-15 23:59:231142 if (observer.OnMessageReceived(message))
1143 return true;
[email protected]64ffefa2014-05-10 12:06:331144 }
[email protected]403415a2011-01-10 18:57:531145
Henrique Ferreiroba535472020-04-21 11:38:361146#if BUILDFLAG(ENABLE_PLUGINS)
[email protected]724159a2010-12-30 01:11:181147 bool handled = true;
nicka0ac8382016-12-15 23:59:231148 IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(WebContentsImpl, message, render_view_host)
nicka0ac8382016-12-15 23:59:231149 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission,
1150 OnRequestPpapiBrokerPermission)
nicka0ac8382016-12-15 23:59:231151 IPC_MESSAGE_UNHANDLED(handled = false)
1152 IPC_END_MESSAGE_MAP()
nicka0ac8382016-12-15 23:59:231153 return handled;
Henrique Ferreiroba535472020-04-21 11:38:361154#else
1155 return false;
1156#endif
nicka0ac8382016-12-15 23:59:231157}
1158
1159bool WebContentsImpl::OnMessageReceived(RenderFrameHostImpl* render_frame_host,
1160 const IPC::Message& message) {
Alexander Timin5fdeff22020-09-08 09:20:371161 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnMessageReceived",
1162 "render_frame_host",
1163 base::trace_event::ToTracedValue(render_frame_host));
1164
Alexander Timin90c20c32020-08-12 15:28:321165 for (auto& observer : observers_.observer_list()) {
nicka0ac8382016-12-15 23:59:231166 if (observer.OnMessageReceived(message, render_frame_host))
1167 return true;
1168 }
1169
1170 bool handled = true;
brettw4b461082016-11-19 18:55:161171#if BUILDFLAG(ENABLE_PLUGINS)
Hiroki Nakagawa761b9b02020-07-13 11:12:021172 IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(WebContentsImpl, message, render_frame_host)
emaxxe70f5e12015-05-29 11:26:001173 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceCreated,
1174 OnPepperInstanceCreated)
1175 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceDeleted,
1176 OnPepperInstanceDeleted)
tommyclie6633ca72014-10-31 00:40:421177 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung, OnPepperPluginHung)
zqzhang181047e62016-07-01 13:37:171178 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperStartsPlayback,
1179 OnPepperStartsPlayback)
1180 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperStopsPlayback,
1181 OnPepperStopsPlayback)
tommyclie6633ca72014-10-31 00:40:421182 IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed, OnPluginCrashed)
[email protected]724159a2010-12-30 01:11:181183 IPC_MESSAGE_UNHANDLED(handled = false)
[email protected]e44d1342014-05-16 21:29:331184 IPC_END_MESSAGE_MAP()
Hiroki Nakagawa761b9b02020-07-13 11:12:021185#else
1186 handled = false;
1187#endif
[email protected]724159a2010-12-30 01:11:181188
[email protected]724159a2010-12-30 01:11:181189 return handled;
1190}
1191
[email protected]d1198fd2012-08-13 22:50:191192NavigationControllerImpl& WebContentsImpl::GetController() {
[email protected]f5fa20e2011-12-21 22:35:561193 return controller_;
1194}
1195
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411196BrowserContext* WebContentsImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:551197 return controller_.GetBrowserContext();
[email protected]627e0512011-12-21 22:55:301198}
1199
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411200const GURL& WebContentsImpl::GetURL() {
Peter Boström101d7672018-12-15 00:43:591201 return GetVisibleURL();
[email protected]be1f56ab2011-12-22 06:55:311202}
1203
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411204const GURL& WebContentsImpl::GetVisibleURL() {
[email protected]c854a7e2013-05-21 16:42:241205 // We may not have a navigation entry yet.
[email protected]59167c22013-06-03 18:07:321206 NavigationEntry* entry = controller_.GetVisibleEntry();
[email protected]c854a7e2013-05-21 16:42:241207 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
1208}
1209
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411210const GURL& WebContentsImpl::GetLastCommittedURL() {
[email protected]c854a7e2013-05-21 16:42:241211 // We may not have a navigation entry yet.
1212 NavigationEntry* entry = controller_.GetLastCommittedEntry();
1213 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
1214}
1215
[email protected]8ff00d72012-10-23 19:12:211216WebContentsDelegate* WebContentsImpl::GetDelegate() {
[email protected]be1f56ab2011-12-22 06:55:311217 return delegate_;
1218}
1219
[email protected]8ff00d72012-10-23 19:12:211220void WebContentsImpl::SetDelegate(WebContentsDelegate* delegate) {
Alexander Timin5fdeff22020-09-08 09:20:371221 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetDelegate", "delegate",
1222 delegate);
[email protected]be1f56ab2011-12-22 06:55:311223 // TODO(cbentzel): remove this debugging code?
1224 if (delegate == delegate_)
1225 return;
1226 if (delegate_)
1227 delegate_->Detach(this);
1228 delegate_ = delegate;
[email protected]a6b73c62013-02-11 23:05:081229 if (delegate_) {
[email protected]be1f56ab2011-12-22 06:55:311230 delegate_->Attach(this);
[email protected]a6b73c62013-02-11 23:05:081231 // Ensure the visible RVH reflects the new delegate's preferences.
[email protected]86f98a22013-03-20 14:35:001232 if (view_)
[email protected]e85165c642014-06-10 14:34:311233 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
Joel Einbinder848001c2017-09-19 21:39:311234 if (GetRenderViewHost())
1235 RenderFrameDevToolsAgentHost::WebContentsCreated(this);
[email protected]a6b73c62013-02-11 23:05:081236 }
[email protected]be1f56ab2011-12-22 06:55:311237}
1238
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411239RenderFrameHostImpl* WebContentsImpl::GetMainFrame() {
[email protected]94d0cc12013-12-18 00:07:411240 return frame_tree_.root()->current_frame_host();
[email protected]60eca4eb2013-12-06 00:02:161241}
1242
nick53d5cbf2015-04-23 22:50:141243RenderFrameHostImpl* WebContentsImpl::GetFocusedFrame() {
1244 FrameTreeNode* focused_node = frame_tree_.GetFocusedFrame();
1245 if (!focused_node)
1246 return nullptr;
1247 return focused_node->current_frame_host();
[email protected]9c9343b2014-03-08 02:56:071248}
1249
rob3e2a0732016-01-06 21:22:091250RenderFrameHostImpl* WebContentsImpl::FindFrameByFrameTreeNodeId(
creisf71a2632017-05-04 19:03:501251 int frame_tree_node_id,
1252 int process_id) {
Alexander Timin5fdeff22020-09-08 09:20:371253 OPTIONAL_TRACE_EVENT2(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1254 "WebContentsImpl::FindFrameByFrameTreeNodeId",
1255 "frame_tree_node_id", frame_tree_node_id, "process_id",
1256 process_id);
creisf71a2632017-05-04 19:03:501257 FrameTreeNode* frame = frame_tree_.FindByID(frame_tree_node_id);
1258
1259 // Sanity check that this is in the caller's expected process. Otherwise a
1260 // recent cross-process navigation may have led to a privilege change that the
1261 // caller is not expecting.
1262 if (!frame ||
1263 frame->current_frame_host()->GetProcess()->GetID() != process_id)
1264 return nullptr;
1265
1266 return frame->current_frame_host();
1267}
1268
1269RenderFrameHostImpl* WebContentsImpl::UnsafeFindFrameByFrameTreeNodeId(
rob3e2a0732016-01-06 21:22:091270 int frame_tree_node_id) {
Alexander Timin5fdeff22020-09-08 09:20:371271 OPTIONAL_TRACE_EVENT1("content",
1272 "WebContentsImpl::UnsafeFindFrameByFrameTreeNodeId",
1273 "frame_tree_node_id", frame_tree_node_id);
creisf71a2632017-05-04 19:03:501274 // Beware using this! The RenderFrameHost may have changed since the caller
1275 // obtained frame_tree_node_id.
rob3e2a0732016-01-06 21:22:091276 FrameTreeNode* frame = frame_tree_.FindByID(frame_tree_node_id);
1277 return frame ? frame->current_frame_host() : nullptr;
1278}
1279
[email protected]a86c0e962013-12-17 17:10:391280void WebContentsImpl::ForEachFrame(
Lei Zhangebcc6302018-01-12 19:46:451281 const base::RepeatingCallback<void(RenderFrameHost*)>& on_frame) {
Alexander Timin5fdeff22020-09-08 09:20:371282 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1283 "WebContentsImpl::ForEachFrame");
dcheng57e39e22016-01-21 00:25:381284 for (FrameTreeNode* node : frame_tree_.Nodes()) {
1285 on_frame.Run(node->current_frame_host());
1286 }
[email protected]a86c0e962013-12-17 17:10:391287}
1288
dchengafb53e22016-02-04 08:11:081289std::vector<RenderFrameHost*> WebContentsImpl::GetAllFrames() {
Xuehui Xieb2300ae42020-06-09 20:25:051290 return GetAllFramesImpl(frame_tree_, /*include_pending=*/false);
1291}
1292
1293std::vector<RenderFrameHost*> WebContentsImpl::GetAllFramesIncludingPending() {
1294 return GetAllFramesImpl(frame_tree_, /*include_pending=*/true);
dchengafb53e22016-02-04 08:11:081295}
1296
lukaszacbdf52e2016-01-15 21:19:511297int WebContentsImpl::SendToAllFrames(IPC::Message* message) {
Alexander Timin5fdeff22020-09-08 09:20:371298 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SendToAllFrames");
Xuehui Xieb2300ae42020-06-09 20:25:051299 return SendToAllFramesImpl(frame_tree_, /*include_pending=*/false, message);
1300}
lukasza1a9ab2422016-03-02 18:47:251301
Xuehui Xieb2300ae42020-06-09 20:25:051302int WebContentsImpl::SendToAllFramesIncludingPending(IPC::Message* message) {
Alexander Timin5fdeff22020-09-08 09:20:371303 OPTIONAL_TRACE_EVENT0("content",
1304 "WebContentsImpl::SentToAllFramesIncludingPending");
Xuehui Xieb2300ae42020-06-09 20:25:051305 return SendToAllFramesImpl(frame_tree_, /*include_pending=*/true, message);
[email protected]a86c0e962013-12-17 17:10:391306}
1307
lfgdb5c4ed2016-03-04 23:09:071308void WebContentsImpl::SendPageMessage(IPC::Message* msg) {
Alexander Timin5fdeff22020-09-08 09:20:371309 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SendPageMessage");
alexmos136fd6e62016-08-15 20:58:411310 frame_tree_.root()->render_manager()->SendPageMessage(msg, nullptr);
lfgdb5c4ed2016-03-04 23:09:071311}
1312
Gyuyoung Kim877e86d2020-07-21 04:01:021313void WebContentsImpl::ExecutePageBroadcastMethod(
1314 PageBroadcastMethodCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:371315 OPTIONAL_TRACE_EVENT0("content",
1316 "WebContentsImpl::ExecutePageBroadcastMethod");
Gyuyoung Kim877e86d2020-07-21 04:01:021317 frame_tree_.root()->render_manager()->ExecutePageBroadcastMethod(callback);
1318}
1319
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411320RenderViewHostImpl* WebContentsImpl::GetRenderViewHost() {
[email protected]fa944cb82013-11-15 17:51:211321 return GetRenderManager()->current_host();
[email protected]be1f56ab2011-12-22 06:55:311322}
1323
creis89a0f782015-05-27 16:13:171324void WebContentsImpl::CancelActiveAndPendingDialogs() {
Alexander Timin5fdeff22020-09-08 09:20:371325 OPTIONAL_TRACE_EVENT0("content",
1326 "WebContentsImpl::CancelActiveAndPendingDialogs");
Evan Stade753fc202020-07-13 18:09:541327 if (dialog_manager_) {
avi6879fcf2017-01-21 05:27:531328 dialog_manager_->CancelDialogs(this, /*reset_state=*/false);
Evan Stade753fc202020-07-13 18:09:541329 }
creis89a0f782015-05-27 16:13:171330 if (browser_plugin_embedder_)
1331 browser_plugin_embedder_->CancelGuestDialogs();
1332}
1333
naskoc0fceff2015-04-30 15:53:521334void WebContentsImpl::ClosePage() {
Alexander Timin5fdeff22020-09-08 09:20:371335 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ClosePage");
naskoc0fceff2015-04-30 15:53:521336 GetRenderViewHost()->ClosePage();
1337}
1338
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411339RenderWidgetHostView* WebContentsImpl::GetRenderWidgetHostView() {
[email protected]fa944cb82013-11-15 17:51:211340 return GetRenderManager()->GetRenderWidgetHostView();
[email protected]be1f56ab2011-12-22 06:55:311341}
1342
lfg265a2672016-04-23 03:11:021343RenderWidgetHostView* WebContentsImpl::GetTopLevelRenderWidgetHostView() {
1344 if (GetOuterWebContents())
1345 return GetOuterWebContents()->GetTopLevelRenderWidgetHostView();
1346 return GetRenderManager()->GetRenderWidgetHostView();
1347}
1348
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411349RenderWidgetHostView* WebContentsImpl::GetFullscreenRenderWidgetHostView() {
vmpstr6d9996c82017-02-23 00:43:251350 if (auto* widget_host = GetFullscreenRenderWidgetHost())
ekaramadaeb3c5c2016-11-09 03:22:351351 return widget_host->GetView();
1352 return nullptr;
[email protected]4aebbca2013-09-17 22:26:491353}
1354
[email protected]8ff00d72012-10-23 19:12:211355WebContentsView* WebContentsImpl::GetView() const {
[email protected]be1f56ab2011-12-22 06:55:311356 return view_.get();
1357}
1358
Mike Wasserman5a3cc61d2020-08-27 21:12:031359void WebContentsImpl::OnScreensChange(bool is_multi_screen_changed) {
Alexander Timin5fdeff22020-09-08 09:20:371360 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnScreensChange",
1361 "is_multi_screen_changed", is_multi_screen_changed);
Mike Wassermandb8f4f02020-10-06 01:18:371362 // Allow fullscreen requests shortly after user-generated screens changes.
1363 transient_allow_fullscreen_.Activate();
Mike Wasserman5a3cc61d2020-08-27 21:12:031364 // Send |is_multi_screen_changed| events to all visible frames, but limit
1365 // other events to frames with the Window Placement permission. This obviates
1366 // the most pressing need for sites to poll isMultiScreen(), which is exposed
1367 // without explicit permission, while also protecting privacy.
1368 // TODO(crbug.com/1109989): Postpone events; refine utility/privacy balance.
Mike Wassermanb213b9352020-04-16 00:32:341369 for (FrameTreeNode* node : frame_tree_.Nodes()) {
1370 RenderFrameHostImpl* rfh = node->current_frame_host();
Mike Wasserman5a3cc61d2020-08-27 21:12:031371 if ((is_multi_screen_changed &&
1372 rfh->GetVisibilityState() == PageVisibilityState::kVisible) ||
Mike Wassermandb8f4f02020-10-06 01:18:371373 IsWindowPlacementGranted(rfh)) {
Mike Wasserman5a3cc61d2020-08-27 21:12:031374 rfh->GetAssociatedLocalFrame()->OnScreensChange();
1375 }
Mike Wassermanb213b9352020-04-16 00:32:341376 }
1377}
1378
leon.han552e9de2017-02-09 14:37:301379void WebContentsImpl::OnScreenOrientationChange() {
Alexander Timin5fdeff22020-09-08 09:20:371380 OPTIONAL_TRACE_EVENT0("content",
1381 "WebContentsImpl::OnScreenOrientationChange");
leon.han552e9de2017-02-09 14:37:301382 DCHECK(screen_orientation_provider_);
Lan Weif81c6e7c2020-02-12 16:46:091383 DidChangeScreenOrientation();
Becca Hughese9e27952018-06-25 17:08:271384 screen_orientation_provider_->OnOrientationChange();
leon.hane4db177a2017-02-07 14:19:161385}
1386
Alan Cutter92d59252019-03-29 02:32:331387base::Optional<SkColor> WebContentsImpl::GetThemeColor() {
Carlos Caballero1215f882019-10-29 15:58:431388 return GetRenderViewHost()->theme_color();
yusufod41c5f92015-03-06 00:14:281389}
1390
Alan Cutterd73a15d92020-08-21 07:12:451391base::Optional<SkColor> WebContentsImpl::GetBackgroundColor() {
1392 return GetRenderViewHost()->background_color();
1393}
1394
Doug Turner63f3c7b2017-07-29 05:10:011395void WebContentsImpl::SetAccessibilityMode(ui::AXMode mode) {
Alexander Timin5fdeff22020-09-08 09:20:371396 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetAccessibilityMode",
1397 "mode", mode.ToString(), "previous_mode",
1398 accessibility_mode_.ToString());
1399
[email protected]95640212014-07-26 18:14:301400 if (mode == accessibility_mode_)
1401 return;
1402
dmazzonif8a31042016-12-03 00:52:131403 // Don't allow accessibility to be enabled for WebContents that are never
danakj77eb7e82020-01-09 19:38:461404 // user-visible, like background pages.
1405 if (IsNeverComposited())
dmazzonif8a31042016-12-03 00:52:131406 return;
1407
[email protected]95640212014-07-26 18:14:301408 accessibility_mode_ = mode;
dcheng57e39e22016-01-21 00:25:381409
1410 for (FrameTreeNode* node : frame_tree_.Nodes()) {
dmazzonif8a31042016-12-03 00:52:131411 UpdateAccessibilityModeOnFrame(node->current_frame_host());
clamy610c63b32017-12-22 15:05:181412 // Also update accessibility mode on the speculative RenderFrameHost for
1413 // this FrameTreeNode, if one exists.
Alex Moshchuk3d8a1f392017-10-24 19:01:261414 RenderFrameHost* speculative_frame_host =
1415 node->render_manager()->speculative_frame_host();
1416 if (speculative_frame_host)
1417 UpdateAccessibilityModeOnFrame(speculative_frame_host);
dcheng57e39e22016-01-21 00:25:381418 }
[email protected]95640212014-07-26 18:14:301419}
1420
Doug Turner63f3c7b2017-07-29 05:10:011421void WebContentsImpl::AddAccessibilityMode(ui::AXMode mode) {
1422 ui::AXMode new_mode(accessibility_mode_);
dougtcd3dad732017-03-14 03:26:231423 new_mode |= mode;
1424 SetAccessibilityMode(new_mode);
[email protected]95640212014-07-26 18:14:301425}
1426
Avi Drissman1e620f32018-03-16 13:57:291427// Helper class used by WebContentsImpl::RequestAXTreeSnapshot.
1428// Handles the callbacks from parallel snapshot requests to each frame,
1429// and feeds the results to an AXTreeCombiner, which converts them into a
1430// single combined accessibility tree.
1431class WebContentsImpl::AXTreeSnapshotCombiner
1432 : public base::RefCounted<AXTreeSnapshotCombiner> {
1433 public:
1434 explicit AXTreeSnapshotCombiner(AXTreeSnapshotCallback callback)
1435 : callback_(std::move(callback)) {}
1436
1437 AXTreeSnapshotCallback AddFrame(bool is_root) {
1438 // Adds a reference to |this|.
1439 return base::BindOnce(&AXTreeSnapshotCombiner::ReceiveSnapshot, this,
1440 is_root);
1441 }
1442
1443 void ReceiveSnapshot(bool is_root, const ui::AXTreeUpdate& snapshot) {
1444 combiner_.AddTree(snapshot, is_root);
1445 }
1446
1447 private:
1448 friend class base::RefCounted<AXTreeSnapshotCombiner>;
1449
1450 // This is called automatically after the last call to ReceiveSnapshot
1451 // when there are no more references to this object.
1452 ~AXTreeSnapshotCombiner() {
1453 combiner_.Combine();
1454 std::move(callback_).Run(combiner_.combined());
1455 }
1456
1457 ui::AXTreeCombiner combiner_;
1458 AXTreeSnapshotCallback callback_;
1459};
1460
1461void WebContentsImpl::RequestAXTreeSnapshot(AXTreeSnapshotCallback callback,
1462 ui::AXMode ax_mode) {
Alexander Timin5fdeff22020-09-08 09:20:371463 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RequestAXTreeSnapshot",
1464 "mode", ax_mode.ToString());
dmazzonid95ae842016-04-12 21:17:391465 // Send a request to each of the frames in parallel. Each one will return
1466 // an accessibility tree snapshot, and AXTreeSnapshotCombiner will combine
1467 // them into a single tree and call |callback| with that result, then
1468 // delete |combiner|.
Avi Drissman1e620f32018-03-16 13:57:291469 FrameTreeNode* root_node = frame_tree_.root();
tzik58faa742018-08-01 10:54:181470 auto combiner =
1471 base::MakeRefCounted<AXTreeSnapshotCombiner>(std::move(callback));
Avi Drissman1e620f32018-03-16 13:57:291472
tzik58faa742018-08-01 10:54:181473 RecursiveRequestAXTreeSnapshotOnFrame(root_node, combiner.get(), ax_mode);
Avi Drissman1e620f32018-03-16 13:57:291474}
1475
1476void WebContentsImpl::RecursiveRequestAXTreeSnapshotOnFrame(
1477 FrameTreeNode* root_node,
1478 AXTreeSnapshotCombiner* combiner,
1479 ui::AXMode ax_mode) {
Alexander Timin5fdeff22020-09-08 09:20:371480 OPTIONAL_TRACE_EVENT0(
1481 "content", "WebContentsImpl::RecursiveRequestAXTreeSnapshotOnFrame");
dmazzonid95ae842016-04-12 21:17:391482 for (FrameTreeNode* frame_tree_node : frame_tree_.Nodes()) {
Avi Drissman1e620f32018-03-16 13:57:291483 WebContentsImpl* inner_contents =
1484 node_.GetInnerWebContentsInFrame(frame_tree_node);
1485 if (inner_contents) {
1486 inner_contents->RecursiveRequestAXTreeSnapshotOnFrame(root_node, combiner,
1487 ax_mode);
1488 } else {
1489 bool is_root = frame_tree_node == root_node;
1490 frame_tree_node->current_frame_host()->RequestAXTreeSnapshot(
1491 combiner->AddFrame(is_root), ax_mode);
1492 }
dmazzonid95ae842016-04-12 21:17:391493 }
dmazzoni83ba5c82015-04-14 07:11:511494}
1495
Becca Hughes3b5a43482018-07-17 22:31:551496void WebContentsImpl::NotifyViewportFitChanged(
1497 blink::mojom::ViewportFit value) {
Alexander Timin5fdeff22020-09-08 09:20:371498 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::NotifyViewportFitChanged",
1499 "value", static_cast<int>(value));
Alexander Timin90c20c32020-08-12 15:28:321500 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1501 observer->ViewportFitChanged(value);
1502 });
Becca Hughes3b5a43482018-07-17 22:31:551503}
1504
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411505FindRequestManager* WebContentsImpl::GetFindRequestManagerForTesting() {
Ehsan Karamad6beb2ea2018-11-25 18:15:131506 return GetFindRequestManager();
1507}
1508
mcnee336ea2c2017-05-23 22:50:591509#if !defined(OS_ANDROID)
akabac6bd1212018-06-25 20:10:481510void WebContentsImpl::UpdateZoom() {
Alexander Timin5fdeff22020-09-08 09:20:371511 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::UpdateZoom");
akabac6bd1212018-06-25 20:10:481512 RenderWidgetHostImpl* rwh = GetRenderViewHost()->GetWidget();
1513 if (rwh->GetView())
1514 rwh->SynchronizeVisualProperties();
wjmaclean64951902016-04-29 20:59:121515}
1516
wjmaclean64951902016-04-29 20:59:121517
1518void WebContentsImpl::UpdateZoomIfNecessary(const std::string& scheme,
akabac6bd1212018-06-25 20:10:481519 const std::string& host) {
Alexander Timin5fdeff22020-09-08 09:20:371520 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::UpdateZoomIfNecessary",
1521 "scheme", scheme, "host", host);
wjmaclean64951902016-04-29 20:59:121522 NavigationEntry* entry = GetController().GetLastCommittedEntry();
1523 if (!entry)
1524 return;
1525
1526 GURL url = HostZoomMap::GetURLFromEntry(entry);
1527 if (host != net::GetHostOrSpecFromURL(url) ||
1528 (!scheme.empty() && !url.SchemeIs(scheme))) {
1529 return;
1530 }
1531
akabac6bd1212018-06-25 20:10:481532 UpdateZoom();
wjmaclean64951902016-04-29 20:59:121533}
mcnee336ea2c2017-05-23 22:50:591534#endif // !defined(OS_ANDROID)
wjmaclean64951902016-04-29 20:59:121535
Julie Jeongeun Kim7d0986172019-12-04 03:17:251536base::OnceClosure WebContentsImpl::AddReceiverSet(
rockotf62002a2016-09-15 00:08:591537 const std::string& interface_name,
Julie Jeongeun Kim7d0986172019-12-04 03:17:251538 WebContentsReceiverSet* receiver_set) {
Alexander Timin5fdeff22020-09-08 09:20:371539 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::AddReceiverSet",
1540 "interface_name", interface_name);
rockotf62002a2016-09-15 00:08:591541 auto result =
Julie Jeongeun Kim7d0986172019-12-04 03:17:251542 receiver_sets_.insert(std::make_pair(interface_name, receiver_set));
rockotf62002a2016-09-15 00:08:591543 DCHECK(result.second);
Julie Jeongeun Kim7d0986172019-12-04 03:17:251544 return base::BindOnce(&WebContentsImpl::RemoveReceiverSet,
danakjf4b9e942019-11-29 15:43:041545 weak_factory_.GetWeakPtr(), interface_name);
rockotf62002a2016-09-15 00:08:591546}
1547
Julie Jeongeun Kim7d0986172019-12-04 03:17:251548WebContentsReceiverSet* WebContentsImpl::GetReceiverSet(
rockot8bbad222017-03-22 04:34:051549 const std::string& interface_name) {
Julie Jeongeun Kim7d0986172019-12-04 03:17:251550 auto it = receiver_sets_.find(interface_name);
1551 if (it == receiver_sets_.end())
rockot8bbad222017-03-22 04:34:051552 return nullptr;
1553 return it->second;
1554}
1555
John Delaney732721e92020-02-07 23:11:271556void WebContentsImpl::RemoveReceiverSetForTesting(
1557 const std::string& interface_name) {
Alexander Timin5fdeff22020-09-08 09:20:371558 OPTIONAL_TRACE_EVENT1("content",
1559 "WebContentsImpl::RemoveReceiverSetForTesting",
1560 "interface_name", interface_name);
John Delaney732721e92020-02-07 23:11:271561 RemoveReceiverSet(interface_name);
1562}
1563
paulmeyerfeafc2d2017-04-25 21:46:401564std::vector<WebContentsImpl*> WebContentsImpl::GetWebContentsAndAllInner() {
1565 std::vector<WebContentsImpl*> all_contents(1, this);
1566
1567 for (size_t i = 0; i != all_contents.size(); ++i) {
1568 for (auto* inner_contents : all_contents[i]->GetInnerWebContents()) {
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:161569 all_contents.push_back(static_cast<WebContentsImpl*>(inner_contents));
paulmeyerfeafc2d2017-04-25 21:46:401570 }
1571 }
1572
1573 return all_contents;
1574}
1575
Sam McNally145fb172017-05-10 00:13:231576void WebContentsImpl::NotifyManifestUrlChanged(
Yuzu Saijo0c263c702020-06-08 03:41:241577 RenderFrameHost* rfh,
Sam McNally145fb172017-05-10 00:13:231578 const base::Optional<GURL>& manifest_url) {
Alexander Timin5fdeff22020-09-08 09:20:371579 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::NotifyManifestUrlChanged",
1580 "render_frame_host",
1581 base::trace_event::ToTracedValue(rfh), "manifest_url",
1582 base::trace_event::ValueToString(manifest_url));
Alexander Timin90c20c32020-08-12 15:28:321583 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1584 observer->DidUpdateWebManifestURL(rfh, manifest_url);
1585 });
Sam McNally145fb172017-05-10 00:13:231586}
1587
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411588WebUI* WebContentsImpl::GetWebUI() {
Nasko Oskov2f7d2112019-10-29 03:26:571589 WebUI* committed_web_ui = GetCommittedWebUI();
1590 if (committed_web_ui)
1591 return committed_web_ui;
1592
1593 if (GetRenderManager()->speculative_frame_host())
1594 return GetRenderManager()->speculative_frame_host()->web_ui();
1595
1596 return nullptr;
[email protected]be1f56ab2011-12-22 06:55:311597}
1598
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411599WebUI* WebContentsImpl::GetCommittedWebUI() {
carlosk35f35af2015-12-01 10:55:401600 return frame_tree_.root()->current_frame_host()->web_ui();
[email protected]d5f942ba2008-09-26 19:30:341601}
1602
Maks Orlovich73f374d2020-04-02 12:46:131603void WebContentsImpl::SetUserAgentOverride(
1604 const blink::UserAgentOverride& ua_override,
1605 bool override_in_new_tabs) {
Alexander Timin5fdeff22020-09-08 09:20:371606 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetUserAgentOverride",
1607 "ua_override", ua_override.ua_string_override,
1608 "override_in_new_tabs", override_in_new_tabs);
Maks Orlovich73f374d2020-04-02 12:46:131609 DCHECK(!ua_override.ua_metadata_override.has_value() ||
1610 !ua_override.ua_string_override.empty());
1611
1612 if (GetUserAgentOverride() == ua_override)
[email protected]bf70edce2012-06-20 22:32:221613 return;
1614
Changwan Ryuc1134a82018-03-07 02:10:141615 should_override_user_agent_in_new_tabs_ = override_in_new_tabs;
1616
Maks Orlovich73f374d2020-04-02 12:46:131617 renderer_preferences_.user_agent_override = ua_override;
[email protected]bf70edce2012-06-20 22:32:221618
Bruce Long1e3e1f542019-10-16 17:56:281619 // Send the new override string to all renderers in the current page.
1620 SyncRendererPrefs();
[email protected]bf70edce2012-06-20 22:32:221621
1622 // Reload the page if a load is currently in progress to avoid having
1623 // different parts of the page loaded using different user agents.
Scott Violete1d58cc2020-04-28 23:07:171624 // No need to reload if the current entry matches that of the
1625 // NavigationRequest supplied to DidStartNavigation() as NavigationRequest
1626 // handles it.
[email protected]6286a372013-10-09 04:03:271627 NavigationEntry* entry = controller_.GetVisibleEntry();
Scott Violete1d58cc2020-04-28 23:07:171628 if (IsLoading() && entry != nullptr && entry->GetIsOverridingUserAgent() &&
1629 (!frame_tree_.root()->navigation_request() ||
1630 frame_tree_.root()->navigation_request()->ua_change_requires_reload())) {
toyoshim6142d96f2016-12-19 09:07:251631 controller_.Reload(ReloadType::BYPASSING_CACHE, true);
Scott Violete1d58cc2020-04-28 23:07:171632 }
[email protected]8d0f3312012-08-18 01:47:531633
Alexander Timin90c20c32020-08-12 15:28:321634 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1635 observer->UserAgentOverrideSet(ua_override);
1636 });
[email protected]86ef6a392012-05-11 22:03:111637}
1638
Scott Violet2a6c5bff2020-04-29 23:59:061639void WebContentsImpl::SetRendererInitiatedUserAgentOverrideOption(
1640 NavigationController::UserAgentOverrideOption option) {
Alexander Timin5fdeff22020-09-08 09:20:371641 OPTIONAL_TRACE_EVENT0(
1642 "content",
1643 "WebContentsImpl::SetRendererInitiatedUserAgentOverrideOption");
Scott Violet2a6c5bff2020-04-29 23:59:061644 renderer_initiated_user_agent_override_option_ = option;
1645}
1646
Maks Orlovich73f374d2020-04-02 12:46:131647const blink::UserAgentOverride& WebContentsImpl::GetUserAgentOverride() {
[email protected]bf70edce2012-06-20 22:32:221648 return renderer_preferences_.user_agent_override;
[email protected]86ef6a392012-05-11 22:03:111649}
1650
Scott Violet2a6c5bff2020-04-29 23:59:061651bool WebContentsImpl::ShouldOverrideUserAgentForRendererInitiatedNavigation() {
1652 NavigationEntryImpl* current_entry = controller_.GetLastCommittedEntry();
1653 if (!current_entry)
1654 return should_override_user_agent_in_new_tabs_;
1655
1656 switch (renderer_initiated_user_agent_override_option_) {
1657 case NavigationController::UA_OVERRIDE_INHERIT:
1658 return current_entry->GetIsOverridingUserAgent();
1659 case NavigationController::UA_OVERRIDE_TRUE:
1660 return true;
1661 case NavigationController::UA_OVERRIDE_FALSE:
1662 return false;
1663 default:
1664 break;
1665 }
1666 return false;
Changwan Ryuc1134a82018-03-07 02:10:141667}
1668
dmazzonidd3d51a72016-12-14 18:41:011669void WebContentsImpl::EnableWebContentsOnlyAccessibilityMode() {
Alexander Timin5fdeff22020-09-08 09:20:371670 OPTIONAL_TRACE_EVENT0(
1671 "content", "WebContentsImpl::EnableWebContentsOnlyAccessibilityMode");
Dominic Mazzonid9fda172019-03-07 17:12:071672 // If accessibility is already enabled, we'll need to force a reset
1673 // in order to ensure new observers of accessibility events get the
1674 // full accessibility tree from scratch.
1675 bool need_reset = GetAccessibilityMode().has_mode(ui::AXMode::kWebContents);
1676
1677 ui::AXMode desired_mode =
1678 GetContentClient()->browser()->GetAXModeForBrowserContext(
1679 GetBrowserContext());
1680 desired_mode |= ui::kAXModeWebContentsOnly;
1681 AddAccessibilityMode(desired_mode);
1682
1683 if (need_reset) {
dchengafb53e22016-02-04 08:11:081684 for (RenderFrameHost* rfh : GetAllFrames())
1685 ResetAccessibility(rfh);
dchengafb53e22016-02-04 08:11:081686 }
[email protected]95640212014-07-26 18:14:301687}
1688
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411689bool WebContentsImpl::IsWebContentsOnlyAccessibilityModeForTesting() {
Doug Turner63f3c7b2017-07-29 05:10:011690 return accessibility_mode_ == ui::kAXModeWebContentsOnly;
[email protected]95640212014-07-26 18:14:301691}
1692
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411693bool WebContentsImpl::IsFullAccessibilityModeForTesting() {
Doug Turner63f3c7b2017-07-29 05:10:011694 return accessibility_mode_ == ui::kAXModeComplete;
[email protected]95640212014-07-26 18:14:301695}
1696
Becca Hughes6daf5662018-06-27 16:50:541697#if defined(OS_ANDROID)
1698
1699void WebContentsImpl::SetDisplayCutoutSafeArea(gfx::Insets insets) {
Alexander Timin5fdeff22020-09-08 09:20:371700 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetDisplayCutoutSafeArea");
Becca Hughes86334622018-07-09 21:29:381701 if (display_cutout_host_impl_)
1702 display_cutout_host_impl_->SetDisplayCutoutSafeArea(insets);
Becca Hughes6daf5662018-06-27 16:50:541703}
1704
1705#endif
1706
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411707const base::string16& WebContentsImpl::GetTitle() {
Nasko Oskov2f7d2112019-10-29 03:26:571708 WebUI* our_web_ui =
1709 GetRenderManager()->speculative_frame_host()
1710 ? GetRenderManager()->speculative_frame_host()->web_ui()
1711 : GetRenderManager()->current_frame_host()->web_ui();
[email protected]7ade2732011-02-10 00:13:581712 if (our_web_ui) {
[email protected]96d185d2009-04-24 03:28:541713 // Don't override the title in view source mode.
Carlos IL4dea8902020-05-26 15:14:291714 NavigationEntry* entry = controller_.GetVisibleEntry();
[email protected]96d185d2009-04-24 03:28:541715 if (!(entry && entry->IsViewSourceMode())) {
[email protected]e0112912011-02-02 22:54:351716 // Give the Web UI the chance to override our title.
[email protected]fcf75d42013-12-03 20:11:261717 const base::string16& title = our_web_ui->GetOverriddenTitle();
[email protected]96d185d2009-04-24 03:28:541718 if (!title.empty())
1719 return title;
1720 }
1721 }
1722
1723 // We use the title for the last committed entry rather than a pending
1724 // navigation entry. For example, when the user types in a URL, we want to
1725 // keep the old page's title until the new load has committed and we get a new
1726 // title.
Carlos IL4dea8902020-05-26 15:14:291727 NavigationEntry* entry = controller_.GetLastCommittedEntry();
[email protected]59167c22013-06-03 18:07:321728
creis072b61f2015-09-28 20:52:241729 // We make an exception for initial navigations. We only want to use the title
1730 // from the visible entry if:
1731 // 1. The pending entry has been explicitly assigned a title to display.
1732 // 2. The user is doing a history navigation in a new tab (e.g., Ctrl+Back),
1733 // which case there is a pending entry index other than -1.
1734 //
1735 // Otherwise, we want to stick with the last committed entry's title during
1736 // new navigations, which have pending entries at index -1 with no title.
1737 if (controller_.IsInitialNavigation() &&
1738 ((controller_.GetVisibleEntry() &&
1739 !controller_.GetVisibleEntry()->GetTitle().empty()) ||
1740 controller_.GetPendingEntryIndex() != -1)) {
1741 entry = controller_.GetVisibleEntry();
[email protected]9eeafc012013-11-25 23:49:471742 }
[email protected]59167c22013-06-03 18:07:321743
[email protected]45d0ef7f2011-01-05 13:46:231744 if (entry) {
jshin1fb76462016-04-05 22:13:031745 return entry->GetTitleForDisplay();
[email protected]45d0ef7f2011-01-05 13:46:231746 }
[email protected]987fc3a2011-05-26 14:18:091747
1748 // |page_title_when_no_navigation_entry_| is finally used
1749 // if no title cannot be retrieved.
1750 return page_title_when_no_navigation_entry_;
[email protected]96d185d2009-04-24 03:28:541751}
1752
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411753SiteInstanceImpl* WebContentsImpl::GetSiteInstance() {
[email protected]fa944cb82013-11-15 17:51:211754 return GetRenderManager()->current_host()->GetSiteInstance();
[email protected]96d185d2009-04-24 03:28:541755}
1756
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411757bool WebContentsImpl::IsLoading() {
Carlos ILd51e7702020-05-07 18:51:391758 return frame_tree_.IsLoading();
[email protected]3c9e1872010-11-18 16:17:491759}
1760
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411761double WebContentsImpl::GetLoadProgress() {
Peter Boström18a40fa2018-10-31 19:03:501762 return frame_tree_.load_progress();
1763}
1764
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411765bool WebContentsImpl::IsLoadingToDifferentDocument() {
clamy44e84ce2016-02-22 15:38:251766 return IsLoading() && is_load_to_different_document_;
[email protected]6dfed692014-05-22 04:18:031767}
1768
Alexander Timindd0fa0c52019-11-06 13:03:371769bool WebContentsImpl::IsDocumentOnLoadCompletedInMainFrame() {
1770 return GetRenderViewHost()->IsDocumentOnLoadCompletedInMainFrame();
1771}
1772
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411773bool WebContentsImpl::IsWaitingForResponse() {
Peter Boströma9a27f6e2018-11-21 13:12:191774 NavigationRequest* ongoing_navigation_request =
1775 frame_tree_.root()->navigation_request();
1776
1777 // An ongoing navigation request means we're waiting for a response.
1778 return ongoing_navigation_request != nullptr;
[email protected]be1f56ab2011-12-22 06:55:311779}
1780
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411781const net::LoadStateWithParam& WebContentsImpl::GetLoadState() {
[email protected]be1f56ab2011-12-22 06:55:311782 return load_state_;
1783}
1784
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411785const base::string16& WebContentsImpl::GetLoadStateHost() {
[email protected]be1f56ab2011-12-22 06:55:311786 return load_state_host_;
1787}
1788
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411789uint64_t WebContentsImpl::GetUploadSize() {
[email protected]be1f56ab2011-12-22 06:55:311790 return upload_size_;
1791}
1792
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411793uint64_t WebContentsImpl::GetUploadPosition() {
[email protected]be1f56ab2011-12-22 06:55:311794 return upload_position_;
1795}
1796
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411797const std::string& WebContentsImpl::GetEncoding() {
Alexander Timine5f20e22019-10-09 23:22:351798 return GetMainFrame()->GetEncoding();
[email protected]be1f56ab2011-12-22 06:55:311799}
1800
Charles Zhaod72f99d2018-09-17 14:18:271801bool WebContentsImpl::WasDiscarded() {
1802 return GetFrameTree()->root()->was_discarded();
1803}
1804
Shubhie Panickerddf2a4e2018-03-06 00:09:061805void WebContentsImpl::SetWasDiscarded(bool was_discarded) {
1806 GetFrameTree()->root()->set_was_discarded();
1807}
1808
Collin Bakerc5259962019-11-14 17:51:581809void WebContentsImpl::IncrementCapturerCount(const gfx::Size& capture_size,
1810 bool stay_hidden) {
Alexander Timin5fdeff22020-09-08 09:20:371811 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::IncrementCapturerCount");
[email protected]5a652232013-02-12 06:15:251812 DCHECK(!is_being_destroyed_);
Xianzhu Wang724e08f2020-09-01 21:35:071813 if (stay_hidden) {
1814 // A hidden capture should not have side effect on the web contents, so it
1815 // should not pass a non-empty |capture_size| which will cause side effect.
1816 DCHECK(capture_size.IsEmpty());
Collin Bakerc5259962019-11-14 17:51:581817 ++hidden_capturer_count_;
Xianzhu Wang724e08f2020-09-01 21:35:071818 } else {
Collin Bakerc5259962019-11-14 17:51:581819 ++visible_capturer_count_;
Xianzhu Wang724e08f2020-09-01 21:35:071820 }
[email protected]222f5822014-02-05 23:40:491821
1822 // Note: This provides a hint to upstream code to size the views optimally
1823 // for quality (e.g., to avoid scaling).
1824 if (!capture_size.IsEmpty() && preferred_size_for_capture_.IsEmpty()) {
1825 preferred_size_for_capture_ = capture_size;
1826 OnPreferredSizeChanged(preferred_size_);
1827 }
ccameron8807c38f2015-01-17 00:29:191828
Collin Bakerc5259962019-11-14 17:51:581829 UpdateVisibilityAndNotifyPageAndView(GetVisibility());
[email protected]54597982013-02-06 01:59:551830}
1831
Collin Bakerc5259962019-11-14 17:51:581832void WebContentsImpl::DecrementCapturerCount(bool stay_hidden) {
Alexander Timin5fdeff22020-09-08 09:20:371833 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DecrementCapturerCount");
Collin Bakerc5259962019-11-14 17:51:581834 if (stay_hidden)
1835 --hidden_capturer_count_;
1836 else
1837 --visible_capturer_count_;
1838 DCHECK_GE(hidden_capturer_count_, 0);
1839 DCHECK_GE(visible_capturer_count_, 0);
[email protected]54597982013-02-06 01:59:551840
[email protected]5a652232013-02-12 06:15:251841 if (is_being_destroyed_)
1842 return;
1843
Francois Doray24fc62c2017-12-11 17:27:331844 if (!IsBeingCaptured()) {
[email protected]222f5822014-02-05 23:40:491845 const gfx::Size old_size = preferred_size_for_capture_;
1846 preferred_size_for_capture_ = gfx::Size();
1847 OnPreferredSizeChanged(old_size);
[email protected]54597982013-02-06 01:59:551848 }
Collin Bakerc5259962019-11-14 17:51:581849
1850 UpdateVisibilityAndNotifyPageAndView(GetVisibility());
[email protected]be1f56ab2011-12-22 06:55:311851}
1852
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411853bool WebContentsImpl::IsBeingCaptured() {
Collin Bakerc5259962019-11-14 17:51:581854 return visible_capturer_count_ + hidden_capturer_count_ > 0;
[email protected]f2bd40812013-07-20 04:30:441855}
1856
Xianzhu Wangc61434c2020-08-21 19:17:301857bool WebContentsImpl::IsBeingVisiblyCaptured() {
1858 return visible_capturer_count_ > 0;
1859}
1860
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411861bool WebContentsImpl::IsAudioMuted() {
Guido Urdanetaf8372942019-11-15 09:47:211862 return audio_stream_factory_ && audio_stream_factory_->IsMuted();
miu50f97892014-09-22 22:49:521863}
1864
1865void WebContentsImpl::SetAudioMuted(bool mute) {
Alexander Timin5fdeff22020-09-08 09:20:371866 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetAudioMuted", "mute",
1867 mute);
miu50f97892014-09-22 22:49:521868 DVLOG(1) << "SetAudioMuted(mute=" << mute << "), was " << IsAudioMuted()
1869 << " for WebContentsImpl@" << this;
1870
1871 if (mute == IsAudioMuted())
1872 return;
1873
Guido Urdanetaf8372942019-11-15 09:47:211874 GetAudioStreamFactory()->SetMuted(mute);
miu50f97892014-09-22 22:49:521875
Alexander Timin90c20c32020-08-12 15:28:321876 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1877 observer->DidUpdateAudioMutingState(mute);
1878 });
Jan Rucka442c83f2017-08-08 13:27:541879 // Notification for UI updates in response to the changed muting state.
Collin Bakeraf540cf2019-09-20 20:54:161880 NotifyNavigationStateChanged(INVALIDATE_TYPE_AUDIO);
Jan Rucka442c83f2017-08-08 13:27:541881}
1882
1883bool WebContentsImpl::IsCurrentlyAudible() {
Chris Hamiltondf0d72cd2018-05-29 16:23:531884 return is_currently_audible_;
miu50f97892014-09-22 22:49:521885}
1886
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411887bool WebContentsImpl::IsConnectedToBluetoothDevice() {
ortunodf4d7982016-04-08 02:33:351888 return bluetooth_connected_device_count_ > 0;
ortuno32e7db3c2016-03-29 16:14:201889}
1890
Ovidio Henriquez76696f62020-07-08 03:06:591891bool WebContentsImpl::IsScanningForBluetoothDevices() {
1892 return bluetooth_scanning_sessions_count_ > 0;
1893}
1894
Lucas Furukawa Gadani4b4eed02019-06-04 23:12:041895bool WebContentsImpl::IsConnectedToSerialPort() {
Reilly Grant5e7c79b22019-04-09 17:26:201896 return serial_active_frame_count_ > 0;
1897}
1898
Matt Reynoldse8c6c1f2019-11-02 09:53:531899bool WebContentsImpl::IsConnectedToHidDevice() {
1900 return hid_active_frame_count_ > 0;
1901}
1902
Marijn Kruisselbrink29051042019-08-06 22:56:551903bool WebContentsImpl::HasNativeFileSystemHandles() {
1904 return native_file_system_handle_count_ > 0;
1905}
Marijn Kruisselbrinkf1714aa22019-07-02 03:45:331906
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411907bool WebContentsImpl::HasPictureInPictureVideo() {
sawtellea7333a82018-05-31 02:36:361908 return has_picture_in_picture_video_;
1909}
1910
1911void WebContentsImpl::SetHasPictureInPictureVideo(
1912 bool has_picture_in_picture_video) {
Alexander Timin5fdeff22020-09-08 09:20:371913 OPTIONAL_TRACE_EVENT1("content",
1914 "WebContentsImpl::SetHasPictureInPictureVideo",
1915 "has_pip_video", has_picture_in_picture_video);
sawtellea7333a82018-05-31 02:36:361916 // If status of |this| is already accurate, there is no need to update.
1917 if (has_picture_in_picture_video == has_picture_in_picture_video_)
1918 return;
1919 has_picture_in_picture_video_ = has_picture_in_picture_video;
1920 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
Alexander Timin90c20c32020-08-12 15:28:321921 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1922 observer->MediaPictureInPictureChanged(has_picture_in_picture_video_);
1923 });
sawtellea7333a82018-05-31 02:36:361924}
1925
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411926bool WebContentsImpl::IsCrashed() {
Dominic Mazzoni73a48322018-05-25 18:14:071927 switch (crashed_status_) {
1928 case base::TERMINATION_STATUS_PROCESS_CRASHED:
1929 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
1930 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED:
1931 case base::TERMINATION_STATUS_OOM:
1932 case base::TERMINATION_STATUS_LAUNCH_FAILED:
Darin Fisher6cf20e782020-08-07 22:25:361933#if defined(OS_CHROMEOS) || BUILDFLAG(IS_LACROS)
Dominic Mazzoni73a48322018-05-25 18:14:071934 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM:
oshima620225722015-06-04 19:45:271935#endif
Dominic Mazzoni73a48322018-05-25 18:14:071936#if defined(OS_ANDROID)
1937 case base::TERMINATION_STATUS_OOM_PROTECTED:
1938#endif
Will Harris07925d12019-10-31 03:03:051939#if defined(OS_WIN)
1940 case base::TERMINATION_STATUS_INTEGRITY_FAILURE:
1941#endif
Dominic Mazzoni73a48322018-05-25 18:14:071942 return true;
1943 case base::TERMINATION_STATUS_NORMAL_TERMINATION:
1944 case base::TERMINATION_STATUS_STILL_RUNNING:
1945 return false;
1946 case base::TERMINATION_STATUS_MAX_ENUM:
1947 NOTREACHED();
1948 return false;
1949 }
1950
1951 NOTREACHED();
1952 return false;
[email protected]3c9e1872010-11-18 16:17:491953}
1954
[email protected]b172aee2012-04-10 17:05:261955void WebContentsImpl::SetIsCrashed(base::TerminationStatus status,
1956 int error_code) {
Alexander Timin5fdeff22020-09-08 09:20:371957 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetIsCrashed", "status",
1958 static_cast<int>(status), "old_status",
1959 static_cast<int>(crashed_status_));
[email protected]443b80e2010-12-14 00:42:231960 if (status == crashed_status_)
[email protected]d5f942ba2008-09-26 19:30:341961 return;
1962
[email protected]443b80e2010-12-14 00:42:231963 crashed_status_ = status;
1964 crashed_error_code_ = error_code;
[email protected]8ff00d72012-10-23 19:12:211965 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
[email protected]d5f942ba2008-09-26 19:30:341966}
1967
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411968base::TerminationStatus WebContentsImpl::GetCrashedStatus() {
[email protected]be1f56ab2011-12-22 06:55:311969 return crashed_status_;
1970}
1971
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411972int WebContentsImpl::GetCrashedErrorCode() {
afakhry98241832016-03-11 19:27:471973 return crashed_error_code_;
1974}
1975
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411976bool WebContentsImpl::IsBeingDestroyed() {
[email protected]be1f56ab2011-12-22 06:55:311977 return is_being_destroyed_;
1978}
1979
[email protected]7f924832014-08-09 05:57:221980void WebContentsImpl::NotifyNavigationStateChanged(
1981 InvalidateTypes changed_flags) {
Alexander Timin5fdeff22020-09-08 09:20:371982 TRACE_EVENT1("content,navigation",
1983 "WebContentsImpl::NotifyNavigationStateChanged", "changed_flags",
1984 static_cast<int>(changed_flags));
dalecurtis88c240072015-12-09 02:11:181985 // Notify the media observer of potential audibility changes.
Collin Bakeraf540cf2019-09-20 20:54:161986 if (changed_flags & INVALIDATE_TYPE_AUDIO) {
mlamouri44e4ef42016-01-20 18:42:271987 media_web_contents_observer_->MaybeUpdateAudibleState();
dalecurtisbc6572e12014-09-12 19:22:301988 }
1989
[email protected]d5f942ba2008-09-26 19:30:341990 if (delegate_)
1991 delegate_->NavigationStateChanged(this, changed_flags);
wjmaclean1dabf3e32016-05-13 23:34:441992
1993 if (GetOuterWebContents())
1994 GetOuterWebContents()->NotifyNavigationStateChanged(changed_flags);
[email protected]d5f942ba2008-09-26 19:30:341995}
1996
W. James MacLean6f34b042019-07-12 19:25:301997RenderFrameHostImpl* WebContentsImpl::GetFocusedFrameFromFocusedDelegate() {
1998 FrameTreeNode* focused_node =
1999 GetFocusedWebContents()->frame_tree_.GetFocusedFrame();
2000 return focused_node ? focused_node->current_frame_host() : nullptr;
2001}
2002
David Black9cca3592019-11-06 23:02:222003void WebContentsImpl::OnVerticalScrollDirectionChanged(
2004 viz::VerticalScrollDirection scroll_direction) {
Alexander Timin5fdeff22020-09-08 09:20:372005 OPTIONAL_TRACE_EVENT1("content",
2006 "WebContentsImpl::OnVerticalScrollDirectionChanged",
2007 "scroll_direction", static_cast<int>(scroll_direction));
Alexander Timin90c20c32020-08-12 15:28:322008 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2009 observer->DidChangeVerticalScrollDirection(scroll_direction);
2010 });
David Black9cca3592019-11-06 23:02:222011}
2012
Chris Hamiltondf0d72cd2018-05-29 16:23:532013void WebContentsImpl::OnAudioStateChanged() {
2014 // This notification can come from any embedded contents or from this
2015 // WebContents' stream monitor. Aggregate these signals to get the actual
2016 // state.
Jeremy Roman03ce13ce2020-05-29 22:16:572017 //
2018 // Note that guests may not be attached as inner contents, and so may need to
2019 // be checked separately.
Chris Hamiltondf0d72cd2018-05-29 16:23:532020 bool is_currently_audible =
2021 audio_stream_monitor_.IsCurrentlyAudible() ||
2022 (browser_plugin_embedder_ &&
Jeremy Roman03ce13ce2020-05-29 22:16:572023 browser_plugin_embedder_->AreAnyGuestsCurrentlyAudible()) ||
2024 AnyInnerWebContents(this, [](WebContents* inner_contents) {
2025 return inner_contents->IsCurrentlyAudible();
2026 });
Alexander Timin5fdeff22020-09-08 09:20:372027 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnAudioStateChanged",
2028 "is_currently_audible", is_currently_audible,
2029 "was_audible", is_currently_audible_);
Chris Hamiltondf0d72cd2018-05-29 16:23:532030 if (is_currently_audible == is_currently_audible_)
2031 return;
2032
2033 // Update internal state.
2034 is_currently_audible_ = is_currently_audible;
2035 was_ever_audible_ = was_ever_audible_ || is_currently_audible_;
2036
Gyuyoung Kim877e86d2020-07-21 04:01:022037 ExecutePageBroadcastMethod(base::BindRepeating(
2038 [](bool is_currently_audible, RenderViewHostImpl* rvh) {
2039 if (auto& broadcast = rvh->GetAssociatedPageBroadcast())
2040 broadcast->AudioStateChanged(is_currently_audible);
2041 },
2042 is_currently_audible_));
altimind8bd26c2016-11-04 11:44:542043
altiminec87fd1f2016-11-17 20:22:492044 // Notification for UI updates in response to the changed audio state.
Collin Bakeraf540cf2019-09-20 20:54:162045 NotifyNavigationStateChanged(INVALIDATE_TYPE_AUDIO);
Jan Rucka442c83f2017-08-08 13:27:542046
Chris Hamiltondf0d72cd2018-05-29 16:23:532047 // Ensure that audio state changes propagate from innermost to outermost
2048 // WebContents.
2049 if (GetOuterWebContents())
2050 GetOuterWebContents()->OnAudioStateChanged();
Tommy Steimel18360512017-11-01 00:38:192051
Alexander Timin90c20c32020-08-12 15:28:322052 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2053 observer->OnAudioStateChanged(is_currently_audible_);
2054 });
altimind8bd26c2016-11-04 11:44:542055}
2056
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:412057base::TimeTicks WebContentsImpl::GetLastActiveTime() {
[email protected]9a890452014-02-13 22:21:022058 return last_active_time_;
[email protected]3e324142012-06-25 18:26:332059}
2060
[email protected]9e2e4632012-07-27 16:38:412061void WebContentsImpl::WasShown() {
Alexander Timin5fdeff22020-09-08 09:20:372062 TRACE_EVENT0("content", "WebContentsImpl::WasShown");
Collin Baker989e0882019-11-01 01:27:172063 UpdateVisibilityAndNotifyPageAndView(Visibility::VISIBLE);
[email protected]be1f56ab2011-12-22 06:55:312064}
2065
[email protected]b172aee2012-04-10 17:05:262066void WebContentsImpl::WasHidden() {
Alexander Timin5fdeff22020-09-08 09:20:372067 TRACE_EVENT0("content", "WebContentsImpl::WasHidden");
Collin Baker989e0882019-11-01 01:27:172068 UpdateVisibilityAndNotifyPageAndView(Visibility::HIDDEN);
[email protected]375fa1b2012-05-22 22:05:372069}
2070
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:412071bool WebContentsImpl::HasRecentInteractiveInputEvent() {
Daniel Cheng90196c82018-04-25 21:49:142072 static constexpr base::TimeDelta kMaxInterval =
2073 base::TimeDelta::FromSeconds(5);
2074 base::TimeDelta delta =
2075 ui::EventTimeForNow() - last_interactive_input_event_time_;
2076 // Note: the expectation is that the caller is typically expecting an input
2077 // event, e.g. validating that a WebUI message that requires a gesture is
Daniel Chenge81030b32019-07-17 20:20:232078 // actually attached to a gesture.
Daniel Cheng90196c82018-04-25 21:49:142079 return delta <= kMaxInterval;
2080}
2081
Avi Drissman738ea192018-08-29 20:24:162082void WebContentsImpl::SetIgnoreInputEvents(bool ignore_input_events) {
Alexander Timin5fdeff22020-09-08 09:20:372083 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetIgnoreInputEvents",
2084 "ignore_input_events", ignore_input_events);
Avi Drissman738ea192018-08-29 20:24:162085 ignore_input_events_ = ignore_input_events;
2086}
2087
Bo Liu168c8642017-08-28 18:26:022088#if defined(OS_ANDROID)
Bo Liu16dd7b8322018-05-02 21:19:502089void WebContentsImpl::SetMainFrameImportance(
2090 ChildProcessImportance importance) {
Alexander Timin5fdeff22020-09-08 09:20:372091 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetMainFrameImportance",
2092 "importance", static_cast<int>(importance));
Bo Liu16dd7b8322018-05-02 21:19:502093 GetMainFrame()->GetRenderWidgetHost()->SetImportance(importance);
Bo Liu7c6779e92017-08-16 02:02:282094}
Bo Liu168c8642017-08-28 18:26:022095#endif
Bo Liu7c6779e92017-08-16 02:02:282096
ccameron8807c38f2015-01-17 00:29:192097void WebContentsImpl::WasOccluded() {
Alexander Timin5fdeff22020-09-08 09:20:372098 TRACE_EVENT0("content", "WebContentsImpl::WasOccluded");
Collin Baker989e0882019-11-01 01:27:172099 UpdateVisibilityAndNotifyPageAndView(Visibility::OCCLUDED);
ccameron8807c38f2015-01-17 00:29:192100}
2101
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:412102Visibility WebContentsImpl::GetVisibility() {
Francois Doraye6161152018-03-27 22:05:372103 return visibility_;
Francois Dorayfe4a1772018-02-17 04:17:092104}
2105
Rakina Zata Amni26e8d8a2020-08-05 06:06:062106bool WebContentsImpl::NeedToFireBeforeUnloadOrUnloadEvents() {
Alexander Timinc7bee322020-05-19 17:54:342107 if (!notify_disconnection_)
Alex Moshchuk6fcaca752018-07-14 02:13:592108 return false;
2109
2110 // Don't fire if the main frame's RenderViewHost indicates that beforeunload
2111 // and unload have already executed (e.g., after receiving a ClosePage ACK)
2112 // or should be ignored.
2113 if (GetRenderViewHost()->SuddenTerminationAllowed())
2114 return false;
2115
Alex Moshchukc78dbc722019-10-31 20:00:502116 // Check whether any frame in the frame tree needs to run beforeunload or
Rakina Zata Amni26e8d8a2020-08-05 06:06:062117 // unload-time event handlers.
Alex Moshchukc78dbc722019-10-31 20:00:502118 for (FrameTreeNode* node : frame_tree_.Nodes()) {
2119 RenderFrameHostImpl* rfh = node->current_frame_host();
2120
Rakina Zata Amni26e8d8a2020-08-05 06:06:062121 // No need to run beforeunload/unload-time events if the RenderFrame isn't
2122 // live.
Alex Moshchukc78dbc722019-10-31 20:00:502123 if (!rfh->IsRenderFrameLive())
2124 continue;
Rakina Zata Amni26e8d8a2020-08-05 06:06:062125 bool should_run_before_unload_handler =
Dave Tapuska97d22ab2019-12-03 17:56:362126 rfh->GetSuddenTerminationDisablerState(
Rakina Zata Amni26e8d8a2020-08-05 06:06:062127 blink::mojom::SuddenTerminationDisablerType::kBeforeUnloadHandler);
2128 bool should_run_unload_handler = rfh->GetSuddenTerminationDisablerState(
2129 blink::mojom::SuddenTerminationDisablerType::kUnloadHandler);
2130 bool should_run_page_hide_handler = rfh->GetSuddenTerminationDisablerState(
2131 blink::mojom::SuddenTerminationDisablerType::kPageHideHandler);
2132 auto* rvh = static_cast<RenderViewHostImpl*>(rfh->GetRenderViewHost());
2133 // If the tab is already hidden, we should not run visibilitychange
2134 // handlers.
2135 bool is_page_visible = rvh->GetPageLifecycleStateManager()
2136 ->CalculatePageLifecycleState()
2137 ->visibility == PageVisibilityState::kVisible;
2138
2139 bool should_run_visibility_change_handler =
2140 is_page_visible && rfh->GetSuddenTerminationDisablerState(
2141 blink::mojom::SuddenTerminationDisablerType::
2142 kVisibilityChangeHandler);
2143 if (should_run_before_unload_handler || should_run_unload_handler ||
2144 should_run_page_hide_handler || should_run_visibility_change_handler) {
Alex Moshchukc78dbc722019-10-31 20:00:502145 return true;
2146 }
Aditya Keerthi34f37e62019-03-08 15:54:532147 }
Alex Moshchuk6fcaca752018-07-14 02:13:592148
Alex Moshchukc78dbc722019-10-31 20:00:502149 return false;
[email protected]be1f56ab2011-12-22 06:55:312150}
2151
Chris Hamilton3b3e315d2018-09-19 13:16:212152void WebContentsImpl::DispatchBeforeUnload(bool auto_cancel) {
Alexander Timin5fdeff22020-09-08 09:20:372153 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DispatchBeforeUnload",
2154 "auto_cancel", auto_cancel);
Chris Hamilton3b3e315d2018-09-19 13:16:212155 auto before_unload_type =
2156 auto_cancel ? RenderFrameHostImpl::BeforeUnloadType::DISCARD
2157 : RenderFrameHostImpl::BeforeUnloadType::TAB_CLOSE;
2158 GetMainFrame()->DispatchBeforeUnload(before_unload_type, false);
[email protected]1c3f80bd2014-04-08 23:02:062159}
2160
W. James MacLean2539adb32019-12-13 00:40:442161bool WebContentsImpl::IsInnerWebContentsForGuest() {
2162 return !!browser_plugin_guest_;
2163}
2164
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502165void WebContentsImpl::AttachInnerWebContents(
2166 std::unique_ptr<WebContents> inner_web_contents,
W. James MacLean62883982019-11-12 20:39:002167 RenderFrameHost* render_frame_host,
2168 bool is_full_page) {
Alexander Timin5fdeff22020-09-08 09:20:372169 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::AttachInnerWebContents",
2170 "inner_web_contents", inner_web_contents.get(),
2171 "is_full_page", is_full_page);
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502172 WebContentsImpl* inner_web_contents_impl =
2173 static_cast<WebContentsImpl*>(inner_web_contents.get());
2174 DCHECK(!inner_web_contents_impl->node_.outer_web_contents());
2175 auto* render_frame_host_impl =
2176 static_cast<RenderFrameHostImpl*>(render_frame_host);
Fergal Daly445af932020-06-02 06:37:232177 DCHECK_EQ(&frame_tree_, render_frame_host_impl->frame_tree());
Lucas Furukawa Gadani105de1e812018-05-31 19:38:392178
Yuzu Saijo3f86fb22020-06-11 03:51:102179 // Mark |render_frame_host_impl| as outer delegate frame.
2180 render_frame_host_impl->SetIsOuterDelegateFrame(true);
2181
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502182 RenderFrameHostManager* inner_render_manager =
2183 inner_web_contents_impl->GetRenderManager();
2184 RenderFrameHostImpl* inner_main_frame =
2185 inner_render_manager->current_frame_host();
2186 RenderViewHostImpl* inner_render_view_host =
2187 inner_render_manager->current_host();
2188 auto* outer_render_manager =
2189 render_frame_host_impl->frame_tree_node()->render_manager();
lfg91a79e12016-04-01 23:52:192190
Lucas Furukawa Gadani105de1e812018-05-31 19:38:392191 // When attaching a WebContents as an inner WebContents, we need to replace
2192 // the Webcontents' view with a WebContentsViewChildFrame.
Fergal Daly55b6d722020-09-11 07:56:332193 inner_web_contents_impl->view_ = std::make_unique<WebContentsViewChildFrame>(
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502194 inner_web_contents_impl,
2195 GetContentClient()->browser()->GetWebContentsViewDelegate(
2196 inner_web_contents_impl),
Fergal Daly55b6d722020-09-11 07:56:332197 &inner_web_contents_impl->render_view_host_delegate_view_);
Lucas Furukawa Gadani105de1e812018-05-31 19:38:392198
lfg91a79e12016-04-01 23:52:192199 // When the WebContents being initialized has an opener, the browser side
2200 // Render{View,Frame}Host must be initialized and the RenderWidgetHostView
2201 // created. This is needed because the usual initialization happens during
2202 // the first navigation, but when attaching a new window we don't navigate
2203 // before attaching. If the browser side is already initialized, the calls
2204 // below will just early return.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502205 inner_render_manager->InitRenderView(inner_render_view_host, nullptr);
2206 inner_main_frame->Init();
2207 if (!inner_render_manager->GetRenderWidgetHostView()) {
2208 inner_web_contents_impl->CreateRenderWidgetHostViewForRenderManager(
2209 inner_render_view_host);
2210 }
lfg91a79e12016-04-01 23:52:192211
Adithya Srinivasane6e7f842019-12-16 18:41:362212 inner_web_contents_impl->RecursivelyUnregisterFrameSinkIds();
2213
lazyboy6ec48b2a2015-06-29 15:18:142214 // Create a link to our outer WebContents.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502215 node_.AttachInnerWebContents(std::move(inner_web_contents),
2216 render_frame_host_impl);
lazyboy6ec48b2a2015-06-29 15:18:142217
lazyboy6ec48b2a2015-06-29 15:18:142218 // Create a proxy in top-level RenderFrameHostManager, pointing to the
2219 // SiteInstance of the outer WebContents. The proxy will be used to send
2220 // postMessage to the inner WebContents.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502221 auto* proxy = inner_render_manager->CreateOuterDelegateProxy(
2222 render_frame_host_impl->GetSiteInstance());
lazyboy6ec48b2a2015-06-29 15:18:142223
Lucas Furukawa Gadani99125822019-01-03 15:41:492224 // When attaching a GuestView as an inner WebContents, there should already be
2225 // a live RenderFrame, which has to be swapped. When attaching a portal, there
2226 // will not be a live RenderFrame before creating the proxy.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502227 if (render_frame_host_impl->IsRenderFrameLive()) {
2228 inner_render_manager->SwapOuterDelegateFrame(render_frame_host_impl, proxy);
Lucas Furukawa Gadani99125822019-01-03 15:41:492229
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502230 inner_web_contents_impl->ReattachToOuterWebContentsFrame();
Lucas Furukawa Gadani99125822019-01-03 15:41:492231 }
ekaramadadd882292016-06-08 15:22:562232
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502233 if (frame_tree_.GetFocusedFrame() ==
2234 render_frame_host_impl->frame_tree_node()) {
2235 inner_web_contents_impl->SetFocusedFrame(
2236 inner_web_contents_impl->frame_tree_.root(),
2237 render_frame_host_impl->GetSiteInstance());
avallee7529b2a2017-04-26 11:37:512238 }
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502239 outer_render_manager->set_attach_complete();
W. James MacLean62883982019-11-12 20:39:002240
2241 // If the inner WebContents is full frame, give it focus.
2242 if (is_full_page) {
2243 // There should only ever be one inner WebContents when |is_full_page| is
2244 // true, and it is the one we just attached.
2245 DCHECK_EQ(1u, node_.GetInnerWebContents().size());
2246 inner_web_contents_impl->SetAsFocusedWebContentsIfNecessary();
2247 }
Chris Hamilton16b5d1d2020-06-04 00:08:122248
Alexander Timin90c20c32020-08-12 15:28:322249 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2250 observer->InnerWebContentsAttached(inner_web_contents_impl,
2251 render_frame_host, is_full_page);
2252 });
Mario Sanchez Prada989aeb7a2020-10-13 09:42:562253
2254 // Make sure that the inner web contents and its outer delegate get properly
2255 // linked via the embedding token now that inner web contents are attached.
2256 inner_main_frame->PropagateEmbeddingTokenToParentFrame();
lazyboy6ec48b2a2015-06-29 15:18:142257}
2258
Lucas Furukawa Gadani99125822019-01-03 15:41:492259std::unique_ptr<WebContents> WebContentsImpl::DetachFromOuterWebContents() {
Alexander Timin5fdeff22020-09-08 09:20:372260 OPTIONAL_TRACE_EVENT0("content",
2261 "WebContentsImpl::DetachFromOuterWebContents");
Chris Hamilton16b5d1d2020-06-04 00:08:122262 auto* outer_web_contents = GetOuterWebContents();
2263 DCHECK(outer_web_contents);
Yuzu Saijo3f86fb22020-06-11 03:51:102264 GetMainFrame()->ParentOrOuterDelegateFrame()->SetIsOuterDelegateFrame(false);
Chris Hamilton16b5d1d2020-06-04 00:08:122265
Adithya Srinivasane6e7f842019-12-16 18:41:362266 RecursivelyUnregisterFrameSinkIds();
Lucas Gadanid29952582020-06-09 21:24:002267
2268 // Each RenderViewHost has a RenderWidgetHost which can have a
2269 // RenderWidgetHostView, and it needs to be re-created with the appropriate
2270 // platform view. It is important to re-create all child views, not only the
2271 // current one, since the view can be swapped due to a cross-origin
2272 // navigation.
2273 std::set<RenderViewHostImpl*> render_view_hosts;
2274 for (auto& render_view_host : GetFrameTree()->render_view_hosts()) {
2275 if (render_view_host.second->GetWidget() &&
2276 render_view_host.second->GetWidget()->GetView()) {
2277 DCHECK(render_view_host.second->GetWidget()
2278 ->GetView()
2279 ->IsRenderWidgetHostViewChildFrame());
2280 render_view_hosts.insert(render_view_host.second);
Kevin McNee6471a702020-01-27 18:23:072281 }
2282 }
Lucas Gadanid29952582020-06-09 21:24:002283
2284 for (auto* render_view_host : render_view_hosts)
2285 render_view_host->GetWidget()->GetView()->Destroy();
2286
Lucas Furukawa Gadani99125822019-01-03 15:41:492287 GetRenderManager()->DeleteOuterDelegateProxy(
2288 node_.OuterContentsFrameTreeNode()
2289 ->current_frame_host()
2290 ->GetSiteInstance());
2291 view_.reset(CreateWebContentsView(
2292 this, GetContentClient()->browser()->GetWebContentsViewDelegate(this),
2293 &render_view_host_delegate_view_));
danakjfc5184932019-09-12 18:08:322294 view_->CreateView(nullptr);
Lucas Furukawa Gadani99125822019-01-03 15:41:492295 std::unique_ptr<WebContents> web_contents =
2296 node_.DisconnectFromOuterWebContents();
2297 DCHECK_EQ(web_contents.get(), this);
2298 node_.SetFocusedWebContents(this);
Lucas Gadanid29952582020-06-09 21:24:002299
2300 for (auto* render_view_host : render_view_hosts)
2301 CreateRenderWidgetHostViewForRenderManager(render_view_host);
2302
Adithya Srinivasane6e7f842019-12-16 18:41:362303 RecursivelyRegisterFrameSinkIds();
Adithya Srinivasan6f0f67b2019-12-19 01:26:462304 // TODO(adithyas): |browser_plugin_embedder_ax_tree_id| should either not be
2305 // used for portals, or it should get a different name.
2306 GetMainFrame()->set_browser_plugin_embedder_ax_tree_id(ui::AXTreeIDUnknown());
2307 GetMainFrame()->UpdateAXTreeData();
Chris Hamilton16b5d1d2020-06-04 00:08:122308
2309 // Invoke on the *outer* web contents observers for symmetry.
Alexander Timin90c20c32020-08-12 15:28:322310 outer_web_contents->observers_.ForEachObserver(
2311 [&](WebContentsObserver* observer) {
2312 observer->InnerWebContentsDetached(this);
2313 });
Chris Hamilton16b5d1d2020-06-04 00:08:122314
Lucas Furukawa Gadani99125822019-01-03 15:41:492315 return web_contents;
2316}
2317
W. James MacLean2dc75ed42019-03-06 14:31:092318void WebContentsImpl::RecursivelyRegisterFrameSinkIds() {
Alexander Timin5fdeff22020-09-08 09:20:372319 OPTIONAL_TRACE_EVENT0("content",
2320 "WebContentsImpl::RecursivelyRegisterFrameSinkIds");
Adithya Srinivasane6e7f842019-12-16 18:41:362321 for (auto* view : GetRenderWidgetHostViewsInWebContentsTree()) {
2322 auto* rwhvb = static_cast<RenderWidgetHostViewBase*>(view);
2323 if (rwhvb->IsRenderWidgetHostViewChildFrame())
2324 static_cast<RenderWidgetHostViewChildFrame*>(view)->RegisterFrameSinkId();
2325 }
2326}
W. James MacLean2dc75ed42019-03-06 14:31:092327
Adithya Srinivasane6e7f842019-12-16 18:41:362328void WebContentsImpl::RecursivelyUnregisterFrameSinkIds() {
Alexander Timin5fdeff22020-09-08 09:20:372329 OPTIONAL_TRACE_EVENT0("content",
2330 "WebContentsImpl::RecursivelyUnregisterFrameSinkIds");
Adithya Srinivasane6e7f842019-12-16 18:41:362331 for (auto* view : GetRenderWidgetHostViewsInWebContentsTree()) {
2332 auto* rwhvb = static_cast<RenderWidgetHostViewBase*>(view);
2333 if (rwhvb->IsRenderWidgetHostViewChildFrame()) {
2334 static_cast<RenderWidgetHostViewChildFrame*>(view)
2335 ->UnregisterFrameSinkId();
2336 }
W. James MacLean2dc75ed42019-03-06 14:31:092337 }
2338}
2339
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:142340void WebContentsImpl::ReattachToOuterWebContentsFrame() {
Alexander Timin5fdeff22020-09-08 09:20:372341 OPTIONAL_TRACE_EVENT0("content",
2342 "WebContentsImpl::ReattachToOuterWebContentsFrame");
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:142343 DCHECK(node_.outer_web_contents());
2344 auto* render_manager = GetRenderManager();
2345 auto* parent_frame =
2346 node_.OuterContentsFrameTreeNode()->current_frame_host()->GetParent();
2347 render_manager->SetRWHViewForInnerContents(
2348 render_manager->GetRenderWidgetHostView());
2349
W. James MacLean2dc75ed42019-03-06 14:31:092350 RecursivelyRegisterFrameSinkIds();
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:142351
2352 // Set up the the guest's AX tree to point back at the embedder's AX tree.
2353 GetMainFrame()->set_browser_plugin_embedder_ax_tree_id(
2354 parent_frame->GetAXTreeID());
2355 GetMainFrame()->UpdateAXTreeData();
2356}
2357
Lucas Gadani972985622020-05-28 20:52:512358void WebContentsImpl::DidActivatePortal(
2359 WebContentsImpl* predecessor_web_contents,
2360 base::TimeTicks activation_time) {
Alexander Timin5fdeff22020-09-08 09:20:372361 TRACE_EVENT2("content", "WebContentsImpl::DidActivatePortal", "predecessor",
2362 predecessor_web_contents, "activation_time", activation_time);
Lucas Gadani972985622020-05-28 20:52:512363 DCHECK(predecessor_web_contents);
Kevin McNeef8eb64c2020-04-21 21:36:062364 NotifyInsidePortal(false);
Alexander Timin90c20c32020-08-12 15:28:322365 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2366 observer->DidActivatePortal(predecessor_web_contents, activation_time);
2367 });
Lucas Gadani972985622020-05-28 20:52:512368 GetDelegate()->WebContentsBecamePortal(predecessor_web_contents);
Kevin McNeef8eb64c2020-04-21 21:36:062369}
2370
Adithya Srinivasan11af2c52019-12-16 22:52:552371void WebContentsImpl::NotifyInsidePortal(bool inside_portal) {
Alexander Timin5fdeff22020-09-08 09:20:372372 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::NotifyInsidePortal",
2373 "inside_portal", inside_portal);
Gyuyoung Kim1c029712020-07-22 09:21:062374 ExecutePageBroadcastMethod(base::BindRepeating(
2375 [](bool inside_portal, RenderViewHostImpl* rvh) {
2376 if (auto& broadcast = rvh->GetAssociatedPageBroadcast())
2377 broadcast->SetInsidePortal(inside_portal);
2378 },
2379 inside_portal));
Adithya Srinivasan11af2c52019-12-16 22:52:552380}
2381
dalecurtis6c58ed02016-10-28 23:02:372382void WebContentsImpl::DidChangeVisibleSecurityState() {
Alexander Timin5fdeff22020-09-08 09:20:372383 OPTIONAL_TRACE_EVENT0("content",
2384 "WebContentsImpl::DidChangeVisibleSecurityState");
Emily Starkc663b0242019-04-26 19:34:452385 if (delegate_)
dalecurtis6c58ed02016-10-28 23:02:372386 delegate_->VisibleSecurityStateChanged(this);
Alexander Timin90c20c32020-08-12 15:28:322387 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2388 observer->DidChangeVisibleSecurityState();
2389 });
dalecurtis6c58ed02016-10-28 23:02:372390}
2391
Gyuyoung Kim1ac4ca782020-09-11 03:32:512392const blink::web_pref::WebPreferences WebContentsImpl::ComputeWebPreferences() {
Alexander Timin5fdeff22020-09-08 09:20:372393 OPTIONAL_TRACE_EVENT0("browser", "WebContentsImpl::ComputeWebPreferences");
2394
Gyuyoung Kim1ac4ca782020-09-11 03:32:512395 blink::web_pref::WebPreferences prefs;
Rakina Zata Amni4029b6d2020-07-28 02:36:202396
2397 const base::CommandLine& command_line =
2398 *base::CommandLine::ForCurrentProcess();
2399
2400 SetSlowWebPreferences(command_line, &prefs);
2401
2402 prefs.web_security_enabled =
2403 !command_line.HasSwitch(switches::kDisableWebSecurity);
2404
2405 prefs.remote_fonts_enabled =
2406 !command_line.HasSwitch(switches::kDisableRemoteFonts);
2407 prefs.application_cache_enabled =
2408 base::FeatureList::IsEnabled(blink::features::kAppCache);
2409 prefs.local_storage_enabled =
2410 !command_line.HasSwitch(switches::kDisableLocalStorage);
2411 prefs.databases_enabled =
2412 !command_line.HasSwitch(switches::kDisableDatabases);
2413
2414 prefs.webgl1_enabled = !command_line.HasSwitch(switches::kDisable3DAPIs) &&
2415 !command_line.HasSwitch(switches::kDisableWebGL);
2416 prefs.webgl2_enabled = !command_line.HasSwitch(switches::kDisable3DAPIs) &&
2417 !command_line.HasSwitch(switches::kDisableWebGL) &&
2418 !command_line.HasSwitch(switches::kDisableWebGL2);
2419
2420 prefs.pepper_3d_enabled = !command_line.HasSwitch(switches::kDisablePepper3d);
2421
2422 prefs.flash_3d_enabled = !command_line.HasSwitch(switches::kDisableFlash3d);
2423 prefs.flash_stage3d_enabled =
2424 !command_line.HasSwitch(switches::kDisableFlashStage3d);
2425 prefs.flash_stage3d_baseline_enabled =
2426 !command_line.HasSwitch(switches::kDisableFlashStage3d);
2427
2428 prefs.allow_file_access_from_file_urls =
2429 command_line.HasSwitch(switches::kAllowFileAccessFromFiles);
2430
2431 prefs.accelerated_2d_canvas_enabled =
2432 !command_line.HasSwitch(switches::kDisableAccelerated2dCanvas);
2433 prefs.new_canvas_2d_api_enabled =
Rakina Zata Amniea8d0c22020-07-30 17:22:502434 command_line.HasSwitch(switches::kEnableNewCanvas2DAPI) ||
2435 base::FeatureList::IsEnabled(features::kEnableNewCanvas2DAPI);
Rakina Zata Amni4029b6d2020-07-28 02:36:202436 prefs.antialiased_2d_canvas_disabled =
2437 command_line.HasSwitch(switches::kDisable2dCanvasAntialiasing);
2438 prefs.antialiased_clips_2d_canvas_enabled =
2439 !command_line.HasSwitch(switches::kDisable2dCanvasClipAntialiasing);
2440
2441 prefs.disable_ipc_flooding_protection =
2442 command_line.HasSwitch(switches::kDisableIpcFloodingProtection) ||
2443 command_line.HasSwitch(switches::kDisablePushStateThrottle);
2444
2445 prefs.accelerated_video_decode_enabled =
2446 !command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode);
2447
2448 std::string autoplay_policy = media::GetEffectiveAutoplayPolicy(command_line);
2449 if (autoplay_policy == switches::autoplay::kNoUserGestureRequiredPolicy) {
Gyuyoung Kim1ac4ca782020-09-11 03:32:512450 prefs.autoplay_policy =
Gyuyoung Kimf6c02a262020-10-13 01:36:132451 blink::mojom::AutoplayPolicy::kNoUserGestureRequired;
Rakina Zata Amni4029b6d2020-07-28 02:36:202452 } else if (autoplay_policy ==
2453 switches::autoplay::kUserGestureRequiredPolicy) {
Gyuyoung Kimf6c02a262020-10-13 01:36:132454 prefs.autoplay_policy = blink::mojom::AutoplayPolicy::kUserGestureRequired;
Rakina Zata Amni4029b6d2020-07-28 02:36:202455 } else if (autoplay_policy ==
2456 switches::autoplay::kDocumentUserActivationRequiredPolicy) {
Gyuyoung Kim1ac4ca782020-09-11 03:32:512457 prefs.autoplay_policy =
Gyuyoung Kimf6c02a262020-10-13 01:36:132458 blink::mojom::AutoplayPolicy::kDocumentUserActivationRequired;
Rakina Zata Amni4029b6d2020-07-28 02:36:202459 } else {
2460 NOTREACHED();
2461 }
2462
2463 prefs.dont_send_key_events_to_javascript =
2464 base::FeatureList::IsEnabled(features::kDontSendKeyEventsToJavascript);
2465
2466// TODO(dtapuska): Enable barrel button selection drag support on Android.
2467// crbug.com/758042
2468#if defined(OS_WIN)
2469 prefs.barrel_button_for_drag_enabled =
2470 base::FeatureList::IsEnabled(features::kDirectManipulationStylus);
2471#endif // defined(OS_WIN)
2472
Rakina Zata Amni4029b6d2020-07-28 02:36:202473 prefs.enable_scroll_animator =
2474 command_line.HasSwitch(switches::kEnableSmoothScrolling) ||
2475 (!command_line.HasSwitch(switches::kDisableSmoothScrolling) &&
2476 gfx::Animation::ScrollAnimationsEnabledBySystem());
2477
2478 prefs.prefers_reduced_motion = gfx::Animation::PrefersReducedMotion();
2479
2480 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
2481 GetRenderViewHost()->GetProcess()->GetID())) {
2482 prefs.loads_images_automatically = true;
2483 prefs.javascript_enabled = true;
2484 }
2485
2486 prefs.viewport_enabled = command_line.HasSwitch(switches::kEnableViewport);
2487
2488 if (IsOverridingUserAgent())
2489 prefs.viewport_meta_enabled = false;
2490
2491 prefs.main_frame_resizes_are_orientation_changes =
2492 command_line.HasSwitch(switches::kMainFrameResizesAreOrientationChanges);
2493
2494 prefs.spatial_navigation_enabled =
2495 command_line.HasSwitch(switches::kEnableSpatialNavigation);
2496
2497 if (IsSpatialNavigationDisabled())
2498 prefs.spatial_navigation_enabled = false;
2499
Rakina Zata Amni4029b6d2020-07-28 02:36:202500 prefs.disable_reading_from_canvas =
2501 command_line.HasSwitch(switches::kDisableReadingFromCanvas);
2502
2503 prefs.strict_mixed_content_checking =
2504 command_line.HasSwitch(switches::kEnableStrictMixedContentChecking);
2505
2506 prefs.strict_powerful_feature_restrictions = command_line.HasSwitch(
2507 switches::kEnableStrictPowerfulFeatureRestrictions);
2508
2509 const std::string blockable_mixed_content_group =
2510 base::FieldTrialList::FindFullName("BlockableMixedContent");
2511 prefs.strictly_block_blockable_mixed_content =
2512 blockable_mixed_content_group == "StrictlyBlockBlockableMixedContent";
2513
2514 const std::string plugin_mixed_content_status =
2515 base::FieldTrialList::FindFullName("PluginMixedContentStatus");
2516 prefs.block_mixed_plugin_content =
2517 plugin_mixed_content_status == "BlockableMixedContent";
2518
2519 prefs.v8_cache_options = GetV8CacheOptions();
2520
2521 prefs.user_gesture_required_for_presentation = !command_line.HasSwitch(
2522 switches::kDisableGestureRequirementForPresentation);
2523
2524 if (HideDownloadUI())
2525 prefs.hide_download_ui = true;
2526
2527 // `media_controls_enabled` is `true` by default.
2528 if (HasPersistentVideo())
2529 prefs.media_controls_enabled = false;
2530
2531#if defined(OS_ANDROID)
2532 display::Display display = display::Screen::GetScreen()->GetPrimaryDisplay();
2533 gfx::Size size = display.GetSizeInPixel();
2534 int min_width = size.width() < size.height() ? size.width() : size.height();
2535 prefs.device_scale_adjustment = GetDeviceScaleAdjustment(
2536 static_cast<int>(min_width / display.device_scale_factor()));
2537#endif // OS_ANDROID
2538
2539 GetContentClient()->browser()->OverrideWebkitPrefs(GetRenderViewHost(),
2540 &prefs);
2541 return prefs;
2542}
2543
2544void WebContentsImpl::SetSlowWebPreferences(
2545 const base::CommandLine& command_line,
Gyuyoung Kim1ac4ca782020-09-11 03:32:512546 blink::web_pref::WebPreferences* prefs) {
Alexander Timin5fdeff22020-09-08 09:20:372547 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetSlowWebPreferences");
2548
Rakina Zata Amni4029b6d2020-07-28 02:36:202549 if (web_preferences_.get()) {
2550#define SET_FROM_CACHE(prefs, field) prefs->field = web_preferences_->field
2551
2552 SET_FROM_CACHE(prefs, touch_event_feature_detection_enabled);
2553 SET_FROM_CACHE(prefs, available_pointer_types);
2554 SET_FROM_CACHE(prefs, available_hover_types);
2555 SET_FROM_CACHE(prefs, primary_pointer_type);
2556 SET_FROM_CACHE(prefs, primary_hover_type);
2557 SET_FROM_CACHE(prefs, pointer_events_max_touch_points);
2558 SET_FROM_CACHE(prefs, number_of_cpu_cores);
2559
2560#if defined(OS_ANDROID)
2561 SET_FROM_CACHE(prefs, video_fullscreen_orientation_lock_enabled);
2562 SET_FROM_CACHE(prefs, video_rotate_to_fullscreen_enabled);
2563#endif
2564
2565#undef SET_FROM_CACHE
2566 } else {
2567 // Every prefs->field modified below should have a SET_FROM_CACHE entry
2568 // above.
2569
2570 // On Android, Touch event feature detection is enabled by default,
2571 // Otherwise default is disabled.
2572 std::string touch_enabled_default_switch =
2573 switches::kTouchEventFeatureDetectionDisabled;
2574#if defined(OS_ANDROID)
2575 touch_enabled_default_switch = switches::kTouchEventFeatureDetectionEnabled;
2576#endif // defined(OS_ANDROID)
2577 const std::string touch_enabled_switch =
2578 command_line.HasSwitch(switches::kTouchEventFeatureDetection)
2579 ? command_line.GetSwitchValueASCII(
2580 switches::kTouchEventFeatureDetection)
2581 : touch_enabled_default_switch;
2582
2583 prefs->touch_event_feature_detection_enabled =
2584 (touch_enabled_switch == switches::kTouchEventFeatureDetectionAuto)
2585 ? (ui::GetTouchScreensAvailability() ==
2586 ui::TouchScreensAvailability::ENABLED)
2587 : (touch_enabled_switch.empty() ||
2588 touch_enabled_switch ==
2589 switches::kTouchEventFeatureDetectionEnabled);
2590
2591 std::tie(prefs->available_pointer_types, prefs->available_hover_types) =
2592 ui::GetAvailablePointerAndHoverTypes();
2593 prefs->primary_pointer_type =
2594 ui::GetPrimaryPointerType(prefs->available_pointer_types);
2595 prefs->primary_hover_type =
2596 ui::GetPrimaryHoverType(prefs->available_hover_types);
2597
2598 prefs->pointer_events_max_touch_points = ui::MaxTouchPoints();
2599
2600 prefs->number_of_cpu_cores = base::SysInfo::NumberOfProcessors();
2601
2602#if defined(OS_ANDROID)
2603 const bool device_is_phone =
2604 ui::GetDeviceFormFactor() == ui::DEVICE_FORM_FACTOR_PHONE;
2605 prefs->video_fullscreen_orientation_lock_enabled = device_is_phone;
2606 prefs->video_rotate_to_fullscreen_enabled = device_is_phone;
2607#endif
2608 }
2609}
2610
2611void WebContentsImpl::OnWebPreferencesChanged() {
Alexander Timin5fdeff22020-09-08 09:20:372612 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnWebPreferencesChanged");
2613
Rakina Zata Amni4029b6d2020-07-28 02:36:202614 // This is defensive code to avoid infinite loops due to code run inside
2615 // SetWebPreferences() accidentally updating more preferences and thus
2616 // calling back into this code. See crbug.com/398751 for one past example.
2617 if (updating_web_preferences_)
2618 return;
2619 updating_web_preferences_ = true;
2620 SetWebPreferences(ComputeWebPreferences());
2621#if defined(OS_ANDROID)
2622 for (FrameTreeNode* node : frame_tree_.Nodes()) {
2623 RenderFrameHostImpl* rfh = node->current_frame_host();
2624 if (rfh->is_local_root()) {
2625 if (auto* rwh = rfh->GetRenderWidgetHost())
2626 rwh->SetForceEnableZoom(web_preferences_->force_enable_zoom);
2627 }
2628 }
2629#endif
2630 updating_web_preferences_ = false;
2631}
2632
Ahmed Fakhryd70bf37b2018-04-04 17:07:242633void WebContentsImpl::NotifyPreferencesChanged() {
Alexander Timin5fdeff22020-09-08 09:20:372634 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::NotifyPreferencesChanged");
2635
Rakina Zata Amni347b70902020-07-22 10:49:042636 // Recompute the WebPreferences based on the current state of the WebContents,
Rakina Zata Amni4029b6d2020-07-28 02:36:202637 // etc. Note that OnWebPreferencesChanged will also call SetWebPreferences and
2638 // send the updated WebPreferences to all RenderViews for this WebContents.
2639 OnWebPreferencesChanged();
Ahmed Fakhryd70bf37b2018-04-04 17:07:242640}
2641
Bruce Long1e3e1f542019-10-16 17:56:282642void WebContentsImpl::SyncRendererPrefs() {
Alexander Timin5fdeff22020-09-08 09:20:372643 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SyncRendererPrefs");
2644
Peter Marshall2dc74e92020-07-29 20:02:302645 blink::mojom::RendererPreferences renderer_preferences = GetRendererPrefs();
Bruce Long1e3e1f542019-10-16 17:56:282646 RenderViewHostImpl::GetPlatformSpecificPrefs(&renderer_preferences);
2647 SendPageMessage(
2648 new PageMsg_SetRendererPrefs(MSG_ROUTING_NONE, renderer_preferences));
2649}
2650
Alexander Timin1cc31f42020-05-12 16:26:012651void WebContentsImpl::OnCookiesAccessed(NavigationHandle* navigation,
2652 const CookieAccessDetails& details) {
Alexander Timin5fdeff22020-09-08 09:20:372653 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnCookiesAccessed",
2654 "navigation_handle", navigation);
Alexander Timin90c20c32020-08-12 15:28:322655 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2656 observer->OnCookiesAccessed(navigation, details);
2657 });
Alexander Timin1cc31f42020-05-12 16:26:012658}
2659
2660void WebContentsImpl::OnCookiesAccessed(RenderFrameHostImpl* rfh,
2661 const CookieAccessDetails& details) {
Alexander Timin5fdeff22020-09-08 09:20:372662 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnCookiesAccessed",
2663 "render_frame_host",
2664 base::trace_event::ToTracedValue(rfh));
Alexander Timin90c20c32020-08-12 15:28:322665 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2666 observer->OnCookiesAccessed(rfh, details);
2667 });
Josh Karlindaba39322019-07-17 23:24:332668}
2669
[email protected]b172aee2012-04-10 17:05:262670void WebContentsImpl::Stop() {
Alexander Timin5fdeff22020-09-08 09:20:372671 TRACE_EVENT0("content", "WebContentsImpl::Stop");
dcheng57e39e22016-01-21 00:25:382672 for (FrameTreeNode* node : frame_tree_.Nodes())
2673 node->StopLoading();
Alexander Timin90c20c32020-08-12 15:28:322674 observers_.ForEachObserver(
2675 [&](WebContentsObserver* observer) { observer->NavigationStopped(); });
[email protected]0bfbf882011-12-22 18:19:272676}
2677
Francois Doray47f759d2018-06-11 18:13:512678void WebContentsImpl::SetPageFrozen(bool frozen) {
Alexander Timin5fdeff22020-09-08 09:20:372679 TRACE_EVENT1("content", "WebContentsImpl::SetPageFrozen", "frozen", frozen);
2680
Francois Doray47f759d2018-06-11 18:13:512681 // A visible page is never frozen.
2682 DCHECK_NE(Visibility::VISIBLE, GetVisibility());
2683
Yuzu Saijo4fa1e9a2020-05-20 02:53:262684 for (auto& entry : frame_tree_.render_view_hosts()) {
2685 entry.second->SetIsFrozen(frozen);
2686 }
Fadi Meawada6573e02018-03-10 00:52:112687}
2688
erikchen6c7df7f7a2018-05-03 18:13:592689std::unique_ptr<WebContents> WebContentsImpl::Clone() {
Alexander Timin5fdeff22020-09-08 09:20:372690 TRACE_EVENT0("content", "WebContentsImpl::Clone");
2691
[email protected]14392a52012-05-02 20:28:442692 // We use our current SiteInstance since the cloned entry will use it anyway.
alexmose201c7cd2015-06-10 17:14:212693 // We pass our own opener so that the cloned page can access it if it was set
[email protected]ed245db2012-12-18 08:00:452694 // before.
[email protected]54944cde2012-12-09 09:24:592695 CreateParams create_params(GetBrowserContext(), GetSiteInstance());
Ian Clelland5cbaaf82017-11-27 22:00:032696 FrameTreeNode* opener = frame_tree_.root()->opener();
2697 RenderFrameHostImpl* opener_rfh = nullptr;
2698 if (opener)
2699 opener_rfh = opener->current_frame_host();
erikchen6c7df7f7a2018-05-03 18:13:592700 std::unique_ptr<WebContentsImpl> tc =
erikchen50735fd2018-05-05 15:08:332701 CreateWithOpener(create_params, opener_rfh);
Lucas Furukawa Gadani5553a152019-01-08 18:55:572702 tc->GetController().CopyStateFrom(&controller_, true);
Alexander Timin90c20c32020-08-12 15:28:322703 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2704 observer->DidCloneToNewWebContents(this, tc.get());
2705 });
[email protected]0bfbf882011-12-22 18:19:272706 return tc;
2707}
2708
[email protected]14392a52012-05-02 20:28:442709void WebContentsImpl::Observe(int type,
[email protected]8ff00d72012-10-23 19:12:212710 const NotificationSource& source,
2711 const NotificationDetails& details) {
Alexander Timin5fdeff22020-09-08 09:20:372712 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::Observe", "type", type);
[email protected]14392a52012-05-02 20:28:442713 switch (type) {
[email protected]8ff00d72012-10-23 19:12:212714 case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: {
2715 RenderWidgetHost* host = Source<RenderWidgetHost>(source).ptr();
[email protected]0b431992014-06-24 00:08:032716 RenderWidgetHostView* view = host->GetView();
2717 if (view == GetFullscreenRenderWidgetHostView()) {
2718 // We cannot just call view_->RestoreFocus() here. On some platforms,
2719 // attempting to focus the currently-invisible WebContentsView will be
2720 // flat-out ignored. Therefore, this boolean is used to track whether
2721 // we will request focus after the fullscreen widget has been
2722 // destroyed.
2723 fullscreen_widget_had_focus_at_shutdown_ = (view && view->HasFocus());
2724 } else {
alexmosc2a8cec2016-05-23 22:19:532725 for (auto i = pending_widget_views_.begin();
[email protected]0b431992014-06-24 00:08:032726 i != pending_widget_views_.end(); ++i) {
2727 if (host->GetView() == i->second) {
2728 pending_widget_views_.erase(i);
2729 break;
2730 }
[email protected]bafe6cd2012-05-23 23:09:502731 }
2732 }
2733 break;
2734 }
[email protected]14392a52012-05-02 20:28:442735 default:
2736 NOTREACHED();
2737 }
2738}
2739
[email protected]ec6c05f2013-10-23 18:41:572740WebContents* WebContentsImpl::GetWebContents() {
2741 return this;
2742}
2743
[email protected]54944cde2012-12-09 09:24:592744void WebContentsImpl::Init(const WebContents::CreateParams& params) {
Alexander Timin5fdeff22020-09-08 09:20:372745 TRACE_EVENT0("content", "WebContentsImpl::Init");
2746
[email protected]fa944cb82013-11-15 17:51:212747 // This is set before initializing the render manager since
[email protected]b0936d22013-11-28 06:47:362748 // RenderFrameHostManager::Init calls back into us via its delegate to ask if
[email protected]fa944cb82013-11-15 17:51:212749 // it should be hidden.
Francois Doraye6161152018-03-27 22:05:372750 visibility_ =
2751 params.initially_hidden ? Visibility::HIDDEN : Visibility::VISIBLE;
[email protected]d6fa88f2013-10-18 16:00:432752
Sebastien Marchand28cf23182018-06-20 02:39:352753 if (!params.last_active_time.is_null())
2754 last_active_time_ = params.last_active_time;
2755
dcheng3ce04b62015-10-26 23:30:552756 scoped_refptr<SiteInstance> site_instance = params.site_instance;
2757 if (!site_instance)
2758 site_instance = SiteInstance::Create(params.browser_context);
Lukasz Anforowicz3caa8372018-06-05 17:22:072759 if (params.desired_renderer_state == CreateParams::kNoRendererProcess) {
2760 static_cast<SiteInstanceImpl*>(site_instance.get())
2761 ->PreventAssociationWithSpareProcess();
2762 }
dcheng3ce04b62015-10-26 23:30:552763
Fergal Dalycb0c1fdf2020-03-16 07:13:492764 GetRenderManager()->InitRoot(site_instance.get(),
2765 params.renderer_initiated_creation);
lukasza464d8692016-02-22 19:26:322766
lukasza5140a412016-09-15 21:12:302767 // blink::FrameTree::setName always keeps |unique_name| empty in case of a
2768 // main frame - let's do the same thing here.
2769 std::string unique_name;
lukasza464d8692016-02-22 19:26:322770 frame_tree_.root()->SetFrameName(params.main_frame_name, unique_name);
[email protected]d1198fd2012-08-13 22:50:192771
[email protected]fc2b46b2014-05-03 16:33:452772 WebContentsViewDelegate* delegate =
2773 GetContentClient()->browser()->GetWebContentsViewDelegate(this);
2774
W. James MacLean2539adb32019-12-13 00:40:442775 if (browser_plugin_guest_) {
Fergal Daly55b6d722020-09-11 07:56:332776 view_ = std::make_unique<WebContentsViewChildFrame>(
2777 this, delegate, &render_view_host_delegate_view_);
sky52a39e342016-12-17 17:23:222778 } else {
2779 view_.reset(CreateWebContentsView(this, delegate,
2780 &render_view_host_delegate_view_));
[email protected]d1198fd2012-08-13 22:50:192781 }
[email protected]fc2b46b2014-05-03 16:33:452782 CHECK(render_view_host_delegate_view_);
[email protected]d1198fd2012-08-13 22:50:192783 CHECK(view_.get());
2784
danakjfc5184932019-09-12 18:08:322785 view_->CreateView(params.context);
[email protected]d1198fd2012-08-13 22:50:192786
brettw4b461082016-11-19 18:55:162787#if BUILDFLAG(ENABLE_PLUGINS)
Fergal Daly55b6d722020-09-11 07:56:332788 plugin_content_origin_allowlist_ =
2789 std::make_unique<PluginContentOriginAllowlist>(this);
tommyclieb25b2a2014-11-03 19:45:092790#endif
2791
[email protected]d1198fd2012-08-13 22:50:192792 registrar_.Add(this,
[email protected]8ff00d72012-10-23 19:12:212793 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
2794 NotificationService::AllBrowserContextsAndSources());
[email protected]f28ef9a32014-05-12 16:36:102795
Fergal Daly55b6d722020-09-11 07:56:332796 screen_orientation_provider_ =
2797 std::make_unique<ScreenOrientationProvider>(this);
[email protected]01f83f92014-06-17 14:41:542798
mfomitchev2b8b066a2016-01-28 19:23:152799#if defined(OS_ANDROID)
Oksana Zhuravlova0b634332019-10-28 23:04:222800 DateTimeChooserAndroid::CreateForWebContents(this);
[email protected]583418cc2013-01-17 14:01:102801#endif
fsamuel7310a4262014-12-05 05:06:442802
2803 // BrowserPluginGuest::Init needs to be called after this WebContents has
W. James MacLean6e78da342019-12-13 15:13:232804 // a RenderWidgetHostViewChildFrame. That is, |view_->CreateView| above.
fsamuel7310a4262014-12-05 05:06:442805 if (browser_plugin_guest_)
2806 browser_plugin_guest_->Init();
nickf9acfbe2014-12-23 19:12:372807
Fergal Daly55b6d722020-09-11 07:56:332808 for (auto& i : g_created_callbacks.Get())
2809 i.Run(this);
naskob21fe4872015-02-24 14:15:562810
2811 // If the WebContents creation was renderer-initiated, it means that the
2812 // corresponding RenderView and main RenderFrame have already been created.
2813 // Ensure observers are notified about this.
2814 if (params.renderer_initiated_creation) {
Fergal Dalybb2d6592020-06-02 05:02:332815 GetRenderViewHost()->GetWidget()->set_renderer_initialized(true);
Alex Moshchuk27caae82017-09-11 23:11:182816 GetRenderViewHost()->DispatchRenderViewCreated();
naskob21fe4872015-02-24 14:15:562817 GetRenderManager()->current_frame_host()->SetRenderFrameCreated(true);
2818 }
naskof5940b9f2015-03-02 23:04:052819
lof84501da082016-05-23 21:22:542820 // Create the renderer process in advance if requested.
Lukasz Anforowicz3caa8372018-06-05 17:22:072821 if (params.desired_renderer_state ==
2822 CreateParams::kInitializeAndWarmupRendererProcess) {
lof84501da082016-05-23 21:22:542823 if (!GetRenderManager()->current_frame_host()->IsRenderFrameLive()) {
2824 GetRenderManager()->InitRenderView(GetRenderViewHost(), nullptr);
2825 }
2826 }
2827
naskof5940b9f2015-03-02 23:04:052828 // Ensure that observers are notified of the creation of this WebContents's
2829 // main RenderFrameHost. It must be done here for main frames, since the
2830 // NotifySwappedFromRenderManager expects view_ to already be created and that
2831 // happens after RenderFrameHostManager::Init.
2832 NotifySwappedFromRenderManager(
2833 nullptr, GetRenderManager()->current_frame_host(), true);
Albert J. Wonge76bf0b82019-09-27 07:47:062834
2835 // For WebContents that are never shown, do critical initialization here which
2836 // would normally only happen when the WebContents is shown.
2837 if (params.is_never_visible) {
2838 // This has just been created so there can only be one frame. Thus it is
2839 // safe to initialize the root.
2840 GetMainFrame()->Init();
2841 }
[email protected]d1198fd2012-08-13 22:50:192842}
2843
[email protected]7fff43e2013-05-21 20:21:102844void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl* web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:372845 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnWebContentsDestroyed");
2846
[email protected]7fff43e2013-05-21 20:21:102847 RemoveDestructionObserver(web_contents);
2848
[email protected]ceee8cd2013-03-08 04:59:512849 // Clear a pending contents that has been closed before being shown.
alexmosc2a8cec2016-05-23 22:19:532850 for (auto iter = pending_contents_.begin(); iter != pending_contents_.end();
[email protected]ceee8cd2013-03-08 04:59:512851 ++iter) {
Joel Hockey8c2011b22020-04-30 05:07:192852 if (iter->second.contents.get() != web_contents)
[email protected]ceee8cd2013-03-08 04:59:512853 continue;
erikchenbee5c9622018-04-27 19:30:252854
2855 // Someone else has deleted the WebContents. That should never happen!
2856 // TODO(erikchen): Fix semantics here. https://crbug.com/832879.
Joel Hockey8c2011b22020-04-30 05:07:192857 iter->second.contents.release();
[email protected]ceee8cd2013-03-08 04:59:512858 pending_contents_.erase(iter);
[email protected]ceee8cd2013-03-08 04:59:512859 return;
2860 }
2861 NOTREACHED();
[email protected]14392a52012-05-02 20:28:442862}
2863
[email protected]7fff43e2013-05-21 20:21:102864void WebContentsImpl::AddDestructionObserver(WebContentsImpl* web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:372865 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
2866 "WebContentsImpl::AddDestructionObserver");
2867
Jan Wilken Dörrie73c901e2019-06-12 09:02:322868 if (!base::Contains(destruction_observers_, web_contents)) {
[email protected]7fff43e2013-05-21 20:21:102869 destruction_observers_[web_contents] =
Jeremy Roman04f27c372017-10-27 15:20:552870 std::make_unique<DestructionObserver>(this, web_contents);
[email protected]7fff43e2013-05-21 20:21:102871 }
2872}
2873
2874void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl* web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:372875 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
2876 "WebContentsImpl::RemoveDestructionObserver");
avia8cf81982016-08-12 20:28:462877 destruction_observers_.erase(web_contents);
[email protected]7fff43e2013-05-21 20:21:102878}
2879
[email protected]b172aee2012-04-10 17:05:262880void WebContentsImpl::AddObserver(WebContentsObserver* observer) {
Alexander Timin5fdeff22020-09-08 09:20:372881 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
2882 "WebContentsImpl::AddObserver");
[email protected]be1f56ab2011-12-22 06:55:312883 observers_.AddObserver(observer);
2884}
2885
[email protected]b172aee2012-04-10 17:05:262886void WebContentsImpl::RemoveObserver(WebContentsObserver* observer) {
Alexander Timin5fdeff22020-09-08 09:20:372887 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
2888 "WebContentsImpl::RemoveObserver");
[email protected]be1f56ab2011-12-22 06:55:312889 observers_.RemoveObserver(observer);
2890}
2891
[email protected]948481d2014-06-11 18:32:222892std::set<RenderWidgetHostView*>
2893WebContentsImpl::GetRenderWidgetHostViewsInTree() {
2894 std::set<RenderWidgetHostView*> set;
Carlos IL07f282f2020-05-15 22:58:292895 for (RenderFrameHost* rfh : GetAllFrames()) {
2896 if (RenderWidgetHostView* rwhv = static_cast<RenderFrameHostImpl*>(rfh)
2897 ->frame_tree_node()
2898 ->render_manager()
2899 ->GetRenderWidgetHostView()) {
lfgf949e0e2017-05-10 22:18:112900 set.insert(rwhv);
dchengafb53e22016-02-04 08:11:082901 }
[email protected]948481d2014-06-11 18:32:222902 }
[email protected]de3c5d82014-05-28 22:12:592903 return set;
2904}
2905
Adithya Srinivasane6e7f842019-12-16 18:41:362906std::set<RenderWidgetHostView*>
2907WebContentsImpl::GetRenderWidgetHostViewsInWebContentsTree() {
2908 std::set<RenderWidgetHostView*> result;
2909 GetRenderWidgetHostViewsInWebContentsTree(result);
2910 return result;
2911}
2912
2913void WebContentsImpl::GetRenderWidgetHostViewsInWebContentsTree(
2914 std::set<RenderWidgetHostView*>& result) {
2915 std::set<RenderWidgetHostView*> views = GetRenderWidgetHostViewsInTree();
2916 result.insert(views.begin(), views.end());
2917 for (auto* inner_web_contents : GetInnerWebContents()) {
2918 static_cast<WebContentsImpl*>(inner_web_contents)
2919 ->GetRenderWidgetHostViewsInWebContentsTree(result);
2920 }
2921}
2922
[email protected]b172aee2012-04-10 17:05:262923void WebContentsImpl::Activate() {
Alexander Timin5fdeff22020-09-08 09:20:372924 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Activate");
[email protected]d5f942ba2008-09-26 19:30:342925 if (delegate_)
2926 delegate_->ActivateContents(this);
2927}
2928
avi3e4b8512015-11-11 01:55:492929void WebContentsImpl::LostCapture(RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:372930 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::LostCapture",
2931 "render_widget_host", render_widget_host);
avi3e4b8512015-11-11 01:55:492932 if (!RenderViewHostImpl::From(render_widget_host))
2933 return;
2934
[email protected]63954792011-07-11 04:17:482935 if (delegate_)
2936 delegate_->LostCapture();
2937}
2938
Yue Ru Sun979c4b162019-11-06 16:11:042939ukm::SourceId
2940WebContentsImpl::GetUkmSourceIdForLastCommittedSourceIncludingSameDocument()
2941 const {
2942 return last_committed_source_id_including_same_document_;
2943}
2944
Ahmed Fakhryfaa32d22018-10-05 15:56:162945void WebContentsImpl::SetTopControlsShownRatio(
2946 RenderWidgetHostImpl* render_widget_host,
2947 float ratio) {
Alexander Timin5fdeff22020-09-08 09:20:372948 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetTopControlsShownRatio",
2949 "render_widget_host", render_widget_host, "ratio",
2950 ratio);
Ahmed Fakhryfaa32d22018-10-05 15:56:162951 if (!delegate_)
2952 return;
2953
2954 RenderFrameHostImpl* rfh = GetMainFrame();
2955 if (!rfh || render_widget_host != rfh->GetRenderWidgetHost())
2956 return;
2957
2958 delegate_->SetTopControlsShownRatio(this, ratio);
Ahmed Fakhry58e6ef542018-09-04 18:05:382959}
2960
Ahmed Fakhry58e6ef542018-09-04 18:05:382961void WebContentsImpl::SetTopControlsGestureScrollInProgress(bool in_progress) {
Alexander Timin5fdeff22020-09-08 09:20:372962 OPTIONAL_TRACE_EVENT1(
2963 "content", "WebContentsImpl::SetTopControlsGestureScrollInProgress",
2964 "in_progress", in_progress);
Ahmed Fakhry58e6ef542018-09-04 18:05:382965 if (delegate_)
2966 delegate_->SetTopControlsGestureScrollInProgress(in_progress);
2967}
2968
lazyboy63f5b312015-11-23 20:19:522969void WebContentsImpl::RenderWidgetCreated(
2970 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:372971 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderWidgetCreated",
2972 "render_widget_host", render_widget_host);
lazyboy63f5b312015-11-23 20:19:522973 created_widgets_.insert(render_widget_host);
2974}
2975
[email protected]b24b68a2012-09-24 21:57:262976void WebContentsImpl::RenderWidgetDeleted(
2977 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:372978 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderWidgetDeleted",
2979 "render_widget_host", render_widget_host);
lazyboy63f5b312015-11-23 20:19:522980 // Note that |is_being_destroyed_| can be true at this point as
2981 // ~WebContentsImpl() calls RFHM::ClearRFHsPendingShutdown(), which might lead
2982 // us here.
2983 created_widgets_.erase(render_widget_host);
[email protected]b24b68a2012-09-24 21:57:262984
lazyboy63f5b312015-11-23 20:19:522985 if (is_being_destroyed_)
2986 return;
[email protected]44470a22013-01-24 01:21:542987
2988 if (render_widget_host &&
alexmosc9e76ec2016-05-16 22:59:372989 render_widget_host->GetRoutingID() == fullscreen_widget_routing_id_ &&
2990 render_widget_host->GetProcess()->GetID() ==
2991 fullscreen_widget_process_id_) {
[email protected]4aebbca2013-09-17 22:26:492992 if (delegate_ && delegate_->EmbedsFullscreenWidget())
mlamouri7a78d6fd2015-01-17 13:23:532993 delegate_->ExitFullscreenModeForTab(this);
Alexander Timin90c20c32020-08-12 15:28:322994 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2995 observer->DidDestroyFullscreenWidget();
2996 });
alexmosc9e76ec2016-05-16 22:59:372997 fullscreen_widget_process_id_ = ChildProcessHost::kInvalidUniqueID;
[email protected]44470a22013-01-24 01:21:542998 fullscreen_widget_routing_id_ = MSG_ROUTING_NONE;
[email protected]0b431992014-06-24 00:08:032999 if (fullscreen_widget_had_focus_at_shutdown_)
3000 view_->RestoreFocus();
[email protected]44470a22013-01-24 01:21:543001 }
lfgbee1e0a2016-06-08 21:24:213002
lfg7d4caad2017-03-22 09:01:453003 if (render_widget_host == mouse_lock_widget_)
lfgff8dfc8d2016-10-21 17:42:323004 LostMouseLock(mouse_lock_widget_);
Joe Downing192998b22018-03-22 15:51:363005
Joe Downingc1a57efe2018-05-09 18:23:543006 CancelKeyboardLock(render_widget_host);
[email protected]b24b68a2012-09-24 21:57:263007}
3008
miu9e14e492014-10-25 02:39:043009void WebContentsImpl::RenderWidgetGotFocus(
3010 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:373011 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderWidgetGotFocus",
3012 "render_widget_host", render_widget_host);
calamity7fe55ce2015-04-10 03:59:373013 // Notify the observers if an embedded fullscreen widget was focused.
3014 if (delegate_ && render_widget_host && delegate_->EmbedsFullscreenWidget() &&
3015 render_widget_host->GetView() == GetFullscreenRenderWidgetHostView()) {
Michael Thiessen896405db2017-07-20 17:52:323016 NotifyWebContentsFocused(render_widget_host);
calamity7fe55ce2015-04-10 03:59:373017 }
miu9e14e492014-10-25 02:39:043018}
3019
zijiehe3bee08e22017-05-17 04:14:463020void WebContentsImpl::RenderWidgetLostFocus(
3021 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:373022 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderWidgetLostFocus",
3023 "render_widget_host", render_widget_host);
Michael Thiessen896405db2017-07-20 17:52:323024 // Notify the observers if an embedded fullscreen widget lost focus.
3025 if (delegate_ && render_widget_host && delegate_->EmbedsFullscreenWidget() &&
3026 render_widget_host->GetView() == GetFullscreenRenderWidgetHostView()) {
3027 NotifyWebContentsLostFocus(render_widget_host);
3028 }
zijiehe3bee08e22017-05-17 04:14:463029}
3030
estaded0a0c992015-01-21 14:12:063031void WebContentsImpl::RenderWidgetWasResized(
rouslan2f5993f2015-01-29 00:18:313032 RenderWidgetHostImpl* render_widget_host,
3033 bool width_changed) {
Alexander Timin5fdeff22020-09-08 09:20:373034 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RenderWidgetWasResized",
3035 "render_widget_host", render_widget_host,
3036 "width_changed", width_changed);
creisc014b402015-04-23 16:41:453037 RenderFrameHostImpl* rfh = GetMainFrame();
estadece344ec2015-01-23 00:12:293038 if (!rfh || render_widget_host != rfh->GetRenderWidgetHost())
estaded0a0c992015-01-21 14:12:063039 return;
estaded0a0c992015-01-21 14:12:063040
Alexander Timin90c20c32020-08-12 15:28:323041 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3042 observer->MainFrameWasResized(width_changed);
3043 });
estaded0a0c992015-01-21 14:12:063044}
3045
skyf65d9bb2017-03-24 02:26:393046KeyboardEventProcessingResult WebContentsImpl::PreHandleKeyboardEvent(
3047 const NativeWebKeyboardEvent& event) {
Alexander Timin5fdeff22020-09-08 09:20:373048 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
3049 "WebContentsImpl::PreHandleKeyboardEvent");
W. James MacLeane1187272019-11-12 03:42:483050 auto* outermost_contents = GetOutermostWebContents();
3051 // TODO(wjmaclean): Generalize this to forward all key events to the outermost
3052 // delegate's handler.
Avi Drissman97aef042020-06-30 21:04:483053 if (outermost_contents != this && IsFullscreen() &&
W. James MacLeane1187272019-11-12 03:42:483054 event.windows_key_code == ui::VKEY_ESCAPE) {
3055 // When an inner WebContents has focus and is fullscreen, redirect <esc>
3056 // key events to the outermost WebContents so it can be handled by that
3057 // WebContents' delegate.
3058 if (outermost_contents->PreHandleKeyboardEvent(event) ==
3059 KeyboardEventProcessingResult::HANDLED) {
3060 return KeyboardEventProcessingResult::HANDLED;
3061 }
3062 }
skyf65d9bb2017-03-24 02:26:393063 return delegate_ ? delegate_->PreHandleKeyboardEvent(this, event)
3064 : KeyboardEventProcessingResult::NOT_HANDLED;
[email protected]63954792011-07-11 04:17:483065}
3066
Dave Tapuska344399e2019-09-09 15:18:263067bool WebContentsImpl::HandleMouseEvent(const blink::WebMouseEvent& event) {
Alexander Timin5fdeff22020-09-08 09:20:373068 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
3069 "WebContentsImpl::HandleMouseEvent");
Dave Tapuska344399e2019-09-09 15:18:263070 // Handle mouse button back/forward in the browser process after the render
3071 // process is done with the event. This ensures all renderer-initiated history
3072 // navigations can be treated consistently.
3073 if (event.GetType() == blink::WebInputEvent::Type::kMouseUp) {
3074 WebContentsImpl* outermost = GetOutermostWebContents();
3075 if (event.button == blink::WebPointerProperties::Button::kBack &&
3076 outermost->controller_.CanGoBack()) {
3077 outermost->controller_.GoBack();
3078 return true;
3079 } else if (event.button == blink::WebPointerProperties::Button::kForward &&
3080 outermost->controller_.CanGoForward()) {
3081 outermost->controller_.GoForward();
3082 return true;
3083 }
3084 }
3085 return false;
3086}
3087
Scott Violetd5caa872018-10-16 22:00:513088bool WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
Alexander Timin5fdeff22020-09-08 09:20:373089 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
3090 "WebContentsImpl::HandleKeyboardEvent");
[email protected]0b094002014-08-20 18:28:103091 if (browser_plugin_embedder_ &&
3092 browser_plugin_embedder_->HandleKeyboardEvent(event)) {
Scott Violetd5caa872018-10-16 22:00:513093 return true;
[email protected]0b094002014-08-20 18:28:103094 }
Scott Violetd5caa872018-10-16 22:00:513095 return delegate_ && delegate_->HandleKeyboardEvent(this, event);
[email protected]63954792011-07-11 04:17:483096}
3097
Alexander Timin5fdeff22020-09-08 09:20:373098bool WebContentsImpl::HandleWheelEvent(const blink::WebMouseWheelEvent& event) {
3099 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
3100 "WebContentsImpl::HandleWheelEvent");
Avi Drissman7c57be72020-07-29 20:09:463101#if !defined(OS_MAC)
lanweia93644f2015-01-21 22:00:333102 // On platforms other than Mac, control+mousewheel may change zoom. On Mac,
3103 // this isn't done for two reasons:
[email protected]bccc4472013-04-18 16:37:193104 // -the OS already has a gesture to do this through pinch-zoom
3105 // -if a user starts an inertial scroll, let's go, and presses control
3106 // (i.e. control+tab) then the OS's buffered scroll events will come in
3107 // with control key set which isn't what the user wants
Blink Reformat1c4d759e2017-04-09 16:34:543108 if (delegate_ && event.wheel_ticks_y &&
Ehsan Karamad0f83cb112018-09-06 22:07:363109 event.event_action == blink::WebMouseWheelEvent::EventAction::kPageZoom) {
w.shackleton49bcd392016-01-06 17:38:223110 // Count only integer cumulative scrolls as zoom events; this handles
3111 // smooth scroll and regular scroll device behavior.
Blink Reformat1c4d759e2017-04-09 16:34:543112 zoom_scroll_remainder_ += event.wheel_ticks_y;
w.shackleton49bcd392016-01-06 17:38:223113 int whole_zoom_scroll_remainder_ = std::lround(zoom_scroll_remainder_);
3114 zoom_scroll_remainder_ -= whole_zoom_scroll_remainder_;
3115 if (whole_zoom_scroll_remainder_ != 0) {
3116 delegate_->ContentsZoomChange(whole_zoom_scroll_remainder_ > 0);
3117 }
[email protected]fb3f066e2013-02-12 19:12:523118 return true;
3119 }
[email protected]bccc4472013-04-18 16:37:193120#endif
[email protected]fb3f066e2013-02-12 19:12:523121 return false;
3122}
3123
[email protected]04bce562014-01-30 05:34:543124bool WebContentsImpl::PreHandleGestureEvent(
3125 const blink::WebGestureEvent& event) {
Alexander Timin5fdeff22020-09-08 09:20:373126 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
3127 "WebContentsImpl::PreHandleGestureEvent");
[email protected]28042d32014-02-03 14:10:033128 return delegate_ && delegate_->PreHandleGestureEvent(this, event);
[email protected]04bce562014-01-30 05:34:543129}
3130
kenrb2a565f82015-09-02 20:24:593131RenderWidgetHostInputEventRouter* WebContentsImpl::GetInputEventRouter() {
wjmacleane31234f2015-12-14 17:20:453132 if (!is_being_destroyed_ && GetOuterWebContents())
3133 return GetOuterWebContents()->GetInputEventRouter();
3134
3135 if (!rwh_input_event_router_.get() && !is_being_destroyed_)
Fergal Daly55b6d722020-09-11 07:56:333136 rwh_input_event_router_ =
3137 std::make_unique<RenderWidgetHostInputEventRouter>();
kenrb2a565f82015-09-02 20:24:593138 return rwh_input_event_router_.get();
3139}
3140
alexmos3fcd0ca2015-10-23 18:18:333141void WebContentsImpl::ReplicatePageFocus(bool is_focused) {
Alexander Timin5fdeff22020-09-08 09:20:373142 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ReplicatePageFocus",
3143 "is_focused", is_focused);
alexmos3fcd0ca2015-10-23 18:18:333144 // Focus loss may occur while this WebContents is being destroyed. Don't
3145 // send the message in this case, as the main frame's RenderFrameHost and
3146 // other state has already been cleared.
3147 if (is_being_destroyed_)
3148 return;
3149
3150 frame_tree_.ReplicatePageFocus(is_focused);
3151}
3152
alexmosc4cbacb2015-11-21 01:29:223153RenderWidgetHostImpl* WebContentsImpl::GetFocusedRenderWidgetHost(
3154 RenderWidgetHostImpl* receiving_widget) {
alexmosc4cbacb2015-11-21 01:29:223155 // Events for widgets other than the main frame (e.g., popup menus) should be
3156 // forwarded directly to the widget they arrived on.
3157 if (receiving_widget != GetMainFrame()->GetRenderWidgetHost())
3158 return receiving_widget;
alexmosc4d183e2015-11-06 00:46:523159
paulmeyerfeafc2d2017-04-25 21:46:403160 // If the focused WebContents is a guest WebContents, then get the focused
3161 // frame in the embedder WebContents instead.
W. James MacLean13d834d2019-12-04 16:06:453162 FrameTreeNode* focused_frame =
3163 GetFocusedWebContents()->frame_tree_.GetFocusedFrame();
lfg1453e412017-04-11 00:48:503164
alexmosc4d183e2015-11-06 00:46:523165 if (!focused_frame)
alexmosc4cbacb2015-11-21 01:29:223166 return receiving_widget;
alexmosc4d183e2015-11-06 00:46:523167
alexmos732ca3a2015-12-08 02:01:023168 // The view may be null if a subframe's renderer process has crashed while
3169 // the subframe has focus. Drop the event in that case. Do not give
3170 // it to the main frame, so that the user doesn't unexpectedly type into the
3171 // wrong frame if a focused subframe renderer crashes while they type.
3172 RenderWidgetHostView* view = focused_frame->current_frame_host()->GetView();
3173 if (!view)
3174 return nullptr;
3175
3176 return RenderWidgetHostImpl::From(view->GetRenderWidgetHost());
alexmosc4d183e2015-11-06 00:46:523177}
3178
avallee9993fca2016-11-17 06:16:503179RenderWidgetHostImpl* WebContentsImpl::GetRenderWidgetHostWithPageFocus() {
lfg1453e412017-04-11 00:48:503180 WebContentsImpl* focused_web_contents = GetFocusedWebContents();
3181
lfg1453e412017-04-11 00:48:503182 return focused_web_contents->GetMainFrame()->GetRenderWidgetHost();
avallee9993fca2016-11-17 06:16:503183}
3184
Avi Drissmand1d25652020-03-06 21:28:583185bool WebContentsImpl::CanEnterFullscreenMode() {
Avi Drissman33972942020-06-19 14:16:013186 // It's possible that this WebContents was spawned while blocking UI was on
3187 // the screen, or that it was downstream from a WebContents when UI was
3188 // blocked. Therefore, disqualify it from fullscreen if it or any upstream
3189 // WebContents has an active blocker.
3190 auto openers = GetAllOpeningWebContents(this);
3191 return std::all_of(openers.begin(), openers.end(), [](auto* opener) {
3192 return opener->fullscreen_blocker_count_ == 0;
3193 });
Avi Drissmand1d25652020-03-06 21:28:583194}
3195
Dave Tapuska3ed44192018-05-01 18:53:303196void WebContentsImpl::EnterFullscreenMode(
Mike Wasserman4ca09792020-05-29 17:44:433197 RenderFrameHost* requesting_frame,
Dave Tapuskaa4189512019-10-15 20:27:343198 const blink::mojom::FullscreenOptions& options) {
Alexander Timin5fdeff22020-09-08 09:20:373199 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::EnterFullscreenMode");
Avi Drissmand1d25652020-03-06 21:28:583200 DCHECK(CanEnterFullscreenMode());
3201
mlamouri7a78d6fd2015-01-17 13:23:533202 // This method is being called to enter renderer-initiated fullscreen mode.
3203 // Make sure any existing fullscreen widget is shut down first.
[email protected]4aebbca2013-09-17 22:26:493204 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
avi85a4cef2015-12-18 20:13:373205 if (widget_view) {
3206 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())
3207 ->ShutdownAndDestroyWidget(true);
3208 }
[email protected]4aebbca2013-09-17 22:26:493209
Joe Downing13dd76b2018-04-09 18:32:153210 if (delegate_) {
Mike Wasserman4ca09792020-05-29 17:44:433211 delegate_->EnterFullscreenModeForTab(requesting_frame, options);
mlamouri7a78d6fd2015-01-17 13:23:533212
Joe Downing13dd76b2018-04-09 18:32:153213 if (keyboard_lock_widget_)
3214 delegate_->RequestKeyboardLock(this, esc_key_locked_);
3215 }
3216
Alexander Timin90c20c32020-08-12 15:28:323217 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3218 observer->DidToggleFullscreenModeForTab(IsFullscreen(), false);
3219 });
Avi Drissman33972942020-06-19 14:16:013220 FullscreenContentsSet(GetBrowserContext())->insert(this);
mlamouri7a78d6fd2015-01-17 13:23:533221}
3222
bokanece34a82016-01-28 19:49:463223void WebContentsImpl::ExitFullscreenMode(bool will_cause_resize) {
Alexander Timin5fdeff22020-09-08 09:20:373224 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ExitFullscreenMode",
3225 "will_cause_resize", will_cause_resize);
mlamouri7a78d6fd2015-01-17 13:23:533226 // This method is being called to leave renderer-initiated fullscreen mode.
3227 // Make sure any existing fullscreen widget is shut down first.
3228 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
avi85a4cef2015-12-18 20:13:373229 if (widget_view) {
3230 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())
3231 ->ShutdownAndDestroyWidget(true);
3232 }
mlamouri7a78d6fd2015-01-17 13:23:533233
Joe Downing13dd76b2018-04-09 18:32:153234 if (delegate_) {
mlamouri7a78d6fd2015-01-17 13:23:533235 delegate_->ExitFullscreenModeForTab(this);
[email protected]657c8e02014-03-19 19:18:373236
Joe Downing13dd76b2018-04-09 18:32:153237 if (keyboard_lock_widget_)
3238 delegate_->CancelKeyboardLockRequest(this);
3239 }
3240
bokanece34a82016-01-28 19:49:463241 // The fullscreen state is communicated to the renderer through a resize
3242 // message. If the change in fullscreen state doesn't cause a view resize
3243 // then we must ensure web contents exit the fullscreen state by explicitly
3244 // sending a resize message. This is required for the situation of the browser
3245 // moving the view into a "browser fullscreen" state and then the contents
3246 // entering "tab fullscreen". Exiting the contents "tab fullscreen" then won't
3247 // have the side effect of the view resizing, hence the explicit call here is
3248 // required.
3249 if (!will_cause_resize) {
3250 if (RenderWidgetHostView* rwhv = GetRenderWidgetHostView()) {
3251 if (RenderWidgetHost* render_widget_host = rwhv->GetRenderWidgetHost())
Fady Samuel0b911822018-04-25 13:22:163252 render_widget_host->SynchronizeVisualProperties();
bokanece34a82016-01-28 19:49:463253 }
scheib3dcb6c932015-02-23 10:55:583254 }
3255
Arthur Sonzogni929d29f2018-09-17 14:19:443256 current_fullscreen_frame_ = nullptr;
Becca Hughese9e27952018-06-25 17:08:273257
Alexander Timin90c20c32020-08-12 15:28:323258 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3259 observer->DidToggleFullscreenModeForTab(IsFullscreen(), will_cause_resize);
3260 });
Becca Hughesd11d6502018-07-31 17:01:283261
3262 if (display_cutout_host_impl_)
3263 display_cutout_host_impl_->DidExitFullscreen();
Avi Drissman33972942020-06-19 14:16:013264
3265 FullscreenContentsSet(GetBrowserContext())->erase(this);
[email protected]8a5e0ca2011-08-25 06:30:473266}
3267
Becca Hughesfd5d8f892018-06-14 18:23:363268void WebContentsImpl::FullscreenStateChanged(RenderFrameHost* rfh,
3269 bool is_fullscreen) {
Alexander Timin5fdeff22020-09-08 09:20:373270 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::FullscreenStateChanged",
3271 "render_frame_host", rfh, "is_fullscreen",
3272 is_fullscreen);
Arthur Sonzogni929d29f2018-09-17 14:19:443273 RenderFrameHostImpl* frame = static_cast<RenderFrameHostImpl*>(rfh);
Becca Hughesfd5d8f892018-06-14 18:23:363274
3275 if (is_fullscreen) {
Jan Wilken Dörrie531be7ca2019-06-07 10:05:573276 if (!base::Contains(fullscreen_frames_, frame)) {
Arthur Sonzogni929d29f2018-09-17 14:19:443277 fullscreen_frames_.insert(frame);
3278 FullscreenFrameSetUpdated();
Becca Hughesfd5d8f892018-06-14 18:23:363279 }
Arthur Sonzogni929d29f2018-09-17 14:19:443280 return;
3281 }
Becca Hughesfd5d8f892018-06-14 18:23:363282
Arthur Sonzogni929d29f2018-09-17 14:19:443283 // If |frame| is no longer in fullscreen, remove it and any descendants.
3284 // See https://fullscreen.spec.whatwg.org.
Arthur Sonzogni969a794e2018-10-11 08:56:093285 size_t size_before_deletion = fullscreen_frames_.size();
3286 base::EraseIf(fullscreen_frames_, [&](RenderFrameHostImpl* current) {
3287 return (current == frame || current->IsDescendantOf(frame));
Arthur Sonzogni929d29f2018-09-17 14:19:443288 });
3289
Arthur Sonzogni969a794e2018-10-11 08:56:093290 if (size_before_deletion != fullscreen_frames_.size())
Arthur Sonzogni929d29f2018-09-17 14:19:443291 FullscreenFrameSetUpdated();
3292}
3293
3294void WebContentsImpl::FullscreenFrameSetUpdated() {
Alexander Timin5fdeff22020-09-08 09:20:373295 OPTIONAL_TRACE_EVENT0("content",
3296 "WebContentsImpl::FullscreenFrameSetUpdated");
Arthur Sonzogni929d29f2018-09-17 14:19:443297 if (fullscreen_frames_.empty()) {
3298 current_fullscreen_frame_ = nullptr;
3299 return;
Becca Hughesfd5d8f892018-06-14 18:23:363300 }
3301
Arthur Sonzogni929d29f2018-09-17 14:19:443302 // Find the current fullscreen frame and call the observers.
3303 // If frame A is fullscreen, then frame B goes into inner fullscreen, then B
3304 // exits fullscreen - that will result in A being fullscreen.
3305 RenderFrameHostImpl* new_fullscreen_frame = *std::max_element(
3306 fullscreen_frames_.begin(), fullscreen_frames_.end(), FrameCompareDepth);
Becca Hughesfd5d8f892018-06-14 18:23:363307
Arthur Sonzogni929d29f2018-09-17 14:19:443308 // If we have already notified observers about this frame then we should not
3309 // fire the observers again.
3310 if (new_fullscreen_frame == current_fullscreen_frame_)
3311 return;
3312 current_fullscreen_frame_ = new_fullscreen_frame;
Becca Hughesfd5d8f892018-06-14 18:23:363313
Alexander Timin90c20c32020-08-12 15:28:323314 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3315 observer->DidAcquireFullscreen(new_fullscreen_frame);
3316 });
Arthur Sonzogni929d29f2018-09-17 14:19:443317 if (display_cutout_host_impl_)
3318 display_cutout_host_impl_->DidAcquireFullscreen(new_fullscreen_frame);
Becca Hughesfd5d8f892018-06-14 18:23:363319}
3320
Collin Baker989e0882019-11-01 01:27:173321void WebContentsImpl::UpdateVisibilityAndNotifyPageAndView(
3322 Visibility new_visibility) {
Alexander Timin5fdeff22020-09-08 09:20:373323 OPTIONAL_TRACE_EVENT1("content",
3324 "WebContentsImpl::UpdateVisibilityAndNotifyPageAndView",
3325 "new_visibility", static_cast<int>(new_visibility));
Collin Baker989e0882019-11-01 01:27:173326 // Only hide the page if there are no entities capturing screenshots
Collin Bakerc5259962019-11-14 17:51:583327 // or video (e.g. mirroring). If there are, apply the correct state of
3328 // kHidden or kHiddenButPainting.
3329 PageVisibilityState page_visibility;
3330 if (new_visibility == Visibility::VISIBLE || visible_capturer_count_ > 0)
3331 page_visibility = PageVisibilityState::kVisible;
3332 else if (hidden_capturer_count_ > 0)
3333 page_visibility = PageVisibilityState::kHiddenButPainting;
3334 else
3335 page_visibility = PageVisibilityState::kHidden;
Fergal Daly6de62f52020-10-14 01:56:443336 // If there are entities in Picture-in-Picture mode, don't activate the
3337 // "disable rendering" optimization. A crashed frame might be covered by a sad
3338 // tab. See docs on SadTabHelper exactly when it is or isn't. Either way,
3339 // don't make it visible.
Collin Bakerc5259962019-11-14 17:51:583340 const bool view_is_visible =
Fergal Daly6de62f52020-10-14 01:56:443341 !IsCrashed() && (page_visibility != PageVisibilityState::kHidden ||
3342 HasPictureInPictureVideo());
Collin Baker989e0882019-11-01 01:27:173343
Collin Bakerc5259962019-11-14 17:51:583344 if (page_visibility != PageVisibilityState::kHidden) {
Dana Friedcf3bc8e2019-11-13 20:00:243345 // We cannot show a page or capture video unless there is a valid renderer
3346 // associated with this web contents. The navigation controller for this
3347 // page must be set to active (allowing navigation to complete, a renderer
3348 // and its associated views to be created, etc.) if any of these conditions
3349 // holds.
3350 //
3351 // Previously, it was possible for browser-side code to try to capture video
3352 // from a restored tab (for a variety of reasons, including the browser
3353 // creating preview thumbnails) and the tab would never actually load. By
Collin Bakerc5259962019-11-14 17:51:583354 // keying this behavior off of |page_visibility| instead of just
Dana Friedcf3bc8e2019-11-13 20:00:243355 // |new_visibility| we avoid this case. See crbug.com/1020782 for more
3356 // context.
3357 controller_.SetActive(true);
3358
3359 // This shows the Page before showing the individual RenderWidgets, as
3360 // RenderWidgets will work to produce compositor frames and handle input
3361 // as soon as they are shown. But the Page and other classes do not expect
3362 // to be producing frames when the Page is hidden. So we make sure the Page
3363 // is shown first.
Yuzu Saijo232076f2020-05-29 07:14:023364 for (auto* rvh : GetRenderViewHostsIncludingBackForwardCached()) {
3365 rvh->SetVisibility(page_visibility);
Yuzu Saijobe024af02020-05-11 07:35:563366 }
Collin Baker98457b52019-11-06 21:34:293367 }
Collin Baker989e0882019-11-01 01:27:173368
3369 // |GetRenderWidgetHostView()| can be null if the user middle clicks a link to
3370 // open a tab in the background, then closes the tab before selecting it.
3371 // This is because closing the tab calls WebContentsImpl::Destroy(), which
3372 // removes the |GetRenderViewHost()|; then when we actually destroy the
3373 // window, OnWindowPosChanged() notices and calls WasHidden() (which
3374 // calls us).
3375 if (auto* view = GetRenderWidgetHostView()) {
3376 if (view_is_visible) {
3377 view->Show();
Collin Baker989e0882019-11-01 01:27:173378 } else if (new_visibility == Visibility::HIDDEN) {
3379 view->Hide();
3380 } else {
3381 view->WasOccluded();
3382 }
3383 }
3384
Carlos IL07f282f2020-05-15 22:58:293385 SetVisibilityForChildViews(view_is_visible);
Collin Baker989e0882019-11-01 01:27:173386
3387 // Make sure to call SetVisibilityAndNotifyObservers(VISIBLE) before notifying
3388 // the CrossProcessFrameConnector.
3389 if (new_visibility == Visibility::VISIBLE) {
3390 last_active_time_ = base::TimeTicks::Now();
3391 SetVisibilityAndNotifyObservers(new_visibility);
3392 }
3393
Collin Bakerc5259962019-11-14 17:51:583394 if (page_visibility == PageVisibilityState::kHidden) {
Collin Baker989e0882019-11-01 01:27:173395 // Similar to when showing the page, we only hide the page after
3396 // hiding the individual RenderWidgets.
Yuzu Saijo232076f2020-05-29 07:14:023397 for (auto* rvh : GetRenderViewHostsIncludingBackForwardCached()) {
3398 rvh->SetVisibility(page_visibility);
Yuzu Saijobe024af02020-05-11 07:35:563399 }
3400
Collin Baker989e0882019-11-01 01:27:173401 } else {
3402 for (FrameTreeNode* node : frame_tree_.Nodes()) {
3403 RenderFrameProxyHost* parent = node->render_manager()->GetProxyToParent();
3404 if (!parent)
3405 continue;
3406
3407 parent->cross_process_frame_connector()->DelegateWasShown();
3408 }
3409 }
3410
3411 if (new_visibility != Visibility::VISIBLE)
3412 SetVisibilityAndNotifyObservers(new_visibility);
3413}
3414
Clark DuValla0e42992018-09-17 17:00:113415#if defined(OS_ANDROID)
3416void WebContentsImpl::UpdateUserGestureCarryoverInfo() {
Alexander Timin5fdeff22020-09-08 09:20:373417 OPTIONAL_TRACE_EVENT0("content",
3418 "WebContentsImpl::UpdateUserGestureCarryoverInfo");
Clark DuValla0e42992018-09-17 17:00:113419 if (delegate_)
3420 delegate_->UpdateUserGestureCarryoverInfo(this);
3421}
3422#endif
3423
Avi Drissman97aef042020-06-30 21:04:483424bool WebContentsImpl::IsFullscreen() {
[email protected]199bba6e2012-04-04 16:19:383425 return delegate_ ? delegate_->IsFullscreenForTabOrPending(this) : false;
[email protected]5d5f7af2011-10-01 01:38:123426}
3427
Malay Keshav87c42c02019-01-15 08:37:473428bool WebContentsImpl::ShouldShowStaleContentOnEviction() {
3429 return GetDelegate() && GetDelegate()->ShouldShowStaleContentOnEviction(this);
3430}
3431
danakj45d42452020-04-08 17:24:183432blink::mojom::DisplayMode WebContentsImpl::GetDisplayMode() const {
mikhail.pozdnyakovc0e251b2015-04-15 06:51:123433 return delegate_ ? delegate_->GetDisplayMode(this)
Eric Willigers052f0432019-10-04 04:06:573434 : blink::mojom::DisplayMode::kBrowser;
mikhail.pozdnyakovc0e251b2015-04-15 06:51:123435}
3436
avic3aa8422015-11-09 20:57:223437void WebContentsImpl::RequestToLockMouse(
3438 RenderWidgetHostImpl* render_widget_host,
3439 bool user_gesture,
lfgad8244352016-07-13 16:55:513440 bool last_unlocked_by_target,
3441 bool privileged) {
Alexander Timin5fdeff22020-09-08 09:20:373442 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RequestToLockMouse",
3443 "render_widget_host", render_widget_host, "privileged",
3444 privileged);
lfgf0cd46e2017-01-04 00:05:233445 for (WebContentsImpl* current = this; current;
3446 current = current->GetOuterWebContents()) {
3447 if (current->mouse_lock_widget_) {
James Hollyerd5c9de462020-03-10 19:02:453448 render_widget_host->GotResponseToLockMouseRequest(
3449 blink::mojom::PointerLockResult::kAlreadyLocked);
lfgf0cd46e2017-01-04 00:05:233450 return;
3451 }
[email protected]e9621112011-10-17 05:38:373452 }
avic3aa8422015-11-09 20:57:223453
lfgad8244352016-07-13 16:55:513454 if (privileged) {
lfgf0cd46e2017-01-04 00:05:233455 DCHECK(!GetOuterWebContents());
lfgad8244352016-07-13 16:55:513456 mouse_lock_widget_ = render_widget_host;
James Hollyerd5c9de462020-03-10 19:02:453457 render_widget_host->GotResponseToLockMouseRequest(
3458 blink::mojom::PointerLockResult::kSuccess);
lfgad8244352016-07-13 16:55:513459 return;
3460 }
3461
lfgbee1e0a2016-06-08 21:24:213462 bool widget_in_frame_tree = false;
3463 for (FrameTreeNode* node : frame_tree_.Nodes()) {
3464 if (node->current_frame_host()->GetRenderWidgetHost() ==
3465 render_widget_host) {
3466 widget_in_frame_tree = true;
3467 break;
3468 }
3469 }
3470
3471 if (widget_in_frame_tree && delegate_) {
lfgf0cd46e2017-01-04 00:05:233472 for (WebContentsImpl* current = this; current;
3473 current = current->GetOuterWebContents()) {
3474 current->mouse_lock_widget_ = render_widget_host;
3475 }
3476
avic3aa8422015-11-09 20:57:223477 delegate_->RequestToLockMouse(this, user_gesture, last_unlocked_by_target);
lfgbee1e0a2016-06-08 21:24:213478 } else {
James Hollyerd5c9de462020-03-10 19:02:453479 render_widget_host->GotResponseToLockMouseRequest(
3480 blink::mojom::PointerLockResult::kWrongDocument);
lfgbee1e0a2016-06-08 21:24:213481 }
[email protected]e9621112011-10-17 05:38:373482}
3483
avi3e4b8512015-11-11 01:55:493484void WebContentsImpl::LostMouseLock(RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:373485 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::LostMouseLock",
3486 "render_widget_host", render_widget_host);
lfgbee1e0a2016-06-08 21:24:213487 CHECK(mouse_lock_widget_);
lfgf0cd46e2017-01-04 00:05:233488
3489 if (mouse_lock_widget_->delegate()->GetAsWebContents() != this)
3490 return mouse_lock_widget_->delegate()->LostMouseLock(render_widget_host);
3491
lfgbee1e0a2016-06-08 21:24:213492 mouse_lock_widget_->SendMouseLockLost();
lfgf0cd46e2017-01-04 00:05:233493 for (WebContentsImpl* current = this; current;
3494 current = current->GetOuterWebContents()) {
3495 current->mouse_lock_widget_ = nullptr;
3496 }
avi3e4b8512015-11-11 01:55:493497
[email protected]e9621112011-10-17 05:38:373498 if (delegate_)
3499 delegate_->LostMouseLock();
3500}
3501
lfgad8244352016-07-13 16:55:513502bool WebContentsImpl::HasMouseLock(RenderWidgetHostImpl* render_widget_host) {
3503 // To verify if the mouse is locked, the mouse_lock_widget_ needs to be
3504 // assigned to the widget that requested the mouse lock, and the top-level
3505 // platform RenderWidgetHostView needs to hold the mouse lock from the OS.
Lucas Gadania0ea0172018-09-20 18:31:373506 auto* widget_host = GetTopLevelRenderWidgetHostView();
3507 return mouse_lock_widget_ == render_widget_host && widget_host &&
3508 widget_host->IsMouseLocked();
lfgad8244352016-07-13 16:55:513509}
3510
lfg84763c92017-02-16 18:55:153511RenderWidgetHostImpl* WebContentsImpl::GetMouseLockWidget() {
Lucas Gadania0ea0172018-09-20 18:31:373512 auto* widget_host = GetTopLevelRenderWidgetHostView();
3513 if ((widget_host && widget_host->IsMouseLocked()) ||
lfge2176fb2017-03-26 00:45:473514 (GetFullscreenRenderWidgetHostView() &&
Lucas Gadania0ea0172018-09-20 18:31:373515 GetFullscreenRenderWidgetHostView()->IsMouseLocked())) {
lfg84763c92017-02-16 18:55:153516 return mouse_lock_widget_;
Lucas Gadania0ea0172018-09-20 18:31:373517 }
lfg84763c92017-02-16 18:55:153518
3519 return nullptr;
3520}
3521
Joe Downing192998b22018-03-22 15:51:363522bool WebContentsImpl::RequestKeyboardLock(
Joe Downing13dd76b2018-04-09 18:32:153523 RenderWidgetHostImpl* render_widget_host,
3524 bool esc_key_locked) {
Alexander Timin5fdeff22020-09-08 09:20:373525 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RequestKeyboardLock",
3526 "render_widget_host", render_widget_host,
3527 "esc_key_locked", esc_key_locked);
Joe Downing192998b22018-03-22 15:51:363528 DCHECK(render_widget_host);
Joe Downing192998b22018-03-22 15:51:363529 if (render_widget_host->delegate()->GetAsWebContents() != this) {
3530 NOTREACHED();
3531 return false;
3532 }
3533
3534 // KeyboardLock is only supported when called by the top-level browsing
3535 // context and is not supported in embedded content scenarios.
3536 if (GetOuterWebContents())
3537 return false;
3538
Joe Downing13dd76b2018-04-09 18:32:153539 esc_key_locked_ = esc_key_locked;
Joe Downing192998b22018-03-22 15:51:363540 keyboard_lock_widget_ = render_widget_host;
3541
Joe Downing13dd76b2018-04-09 18:32:153542 if (delegate_)
3543 delegate_->RequestKeyboardLock(this, esc_key_locked_);
Joe Downing192998b22018-03-22 15:51:363544 return true;
3545}
3546
3547void WebContentsImpl::CancelKeyboardLock(
3548 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:373549 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::CancelKeyboardLockRequest",
3550 "render_widget_host", render_widget_host);
Joe Downing192998b22018-03-22 15:51:363551 if (!keyboard_lock_widget_ || render_widget_host != keyboard_lock_widget_)
3552 return;
3553
3554 RenderWidgetHostImpl* old_keyboard_lock_widget = keyboard_lock_widget_;
3555 keyboard_lock_widget_ = nullptr;
3556
Joe Downing13dd76b2018-04-09 18:32:153557 if (delegate_)
3558 delegate_->CancelKeyboardLockRequest(this);
3559
Joe Downing192998b22018-03-22 15:51:363560 old_keyboard_lock_widget->CancelKeyboardLock();
3561}
3562
3563RenderWidgetHostImpl* WebContentsImpl::GetKeyboardLockWidget() {
3564 return keyboard_lock_widget_;
3565}
3566
Dave Tapuskac3344362019-02-20 17:54:283567void WebContentsImpl::OnRenderFrameProxyVisibilityChanged(
3568 blink::mojom::FrameVisibility visibility) {
Alexander Timin5fdeff22020-09-08 09:20:373569 OPTIONAL_TRACE_EVENT1("content",
3570 "WebContentsImpl::OnRenderFrameProxyVisibilityChanged",
3571 "visibility", static_cast<int>(visibility));
Dave Tapuskac3344362019-02-20 17:54:283572 switch (visibility) {
3573 case blink::mojom::FrameVisibility::kRenderedInViewport:
3574 WasShown();
3575 break;
3576 case blink::mojom::FrameVisibility::kNotRendered:
3577 WasHidden();
3578 break;
3579 case blink::mojom::FrameVisibility::kRenderedOutOfViewport:
3580 WasOccluded();
3581 break;
3582 }
ekaramada4f42692016-02-11 19:48:373583}
3584
Albert J. Wong65fe64d2019-09-20 02:48:143585RenderFrameHostDelegate* WebContentsImpl::CreateNewWindow(
csharrison95f01e922017-04-24 18:52:353586 RenderFrameHost* opener,
rockot5c478a72016-09-28 23:14:183587 const mojom::CreateNewWindowParams& params,
Albert J. Wong65fe64d2019-09-20 02:48:143588 bool is_new_browsing_instance,
Sergey Kuznetsov32257a22019-02-11 20:26:503589 bool has_user_gesture,
[email protected]97714c82012-06-06 10:15:133590 SessionStorageNamespace* session_storage_namespace) {
Alexander Timin5fdeff22020-09-08 09:20:373591 TRACE_EVENT2("browser,content,navigation", "WebContentsImpl::CreateNewWindow",
3592 "opener", base::trace_event::ToTracedValue(opener), "params",
3593 base::trace_event::ToTracedValue(params));
csharrison95f01e922017-04-24 18:52:353594 DCHECK(opener);
nick5ae4d2d2017-01-06 01:18:353595
csharrison95f01e922017-04-24 18:52:353596 int render_process_id = opener->GetProcess()->GetID();
csharrison95f01e922017-04-24 18:52:353597
Albert J. Wong65fe64d2019-09-20 02:48:143598 SiteInstance* source_site_instance = opener->GetSiteInstance();
nick5ae4d2d2017-01-06 01:18:353599
Aaron Colwelleb219982020-01-16 02:17:273600 const GURL source_site_url = source_site_instance->GetSiteURL();
[email protected]fdac6ade2013-07-20 01:06:303601 const std::string& partition_id =
Aaron Colwelleb219982020-01-16 02:17:273602 GetContentClient()->browser()->GetStoragePartitionIdForSite(
3603 GetBrowserContext(), source_site_url);
3604 {
3605 StoragePartition* partition = BrowserContext::GetStoragePartitionForSite(
3606 GetBrowserContext(), source_site_url);
3607 DOMStorageContextWrapper* dom_storage_context =
3608 static_cast<DOMStorageContextWrapper*>(
3609 partition->GetDOMStorageContext());
3610 SessionStorageNamespaceImpl* session_storage_namespace_impl =
3611 static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace);
3612 CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context));
3613 }
[email protected]dd6730412013-08-14 15:03:373614
Albert J. Wong1ceccef92019-10-08 08:25:203615 if (delegate_ && delegate_->IsWebContentsCreationOverridden(
3616 source_site_instance, params.window_container_type,
3617 opener->GetLastCommittedURL(), params.frame_name,
3618 params.target_url)) {
3619 return static_cast<WebContentsImpl*>(delegate_->CreateCustomWebContents(
3620 opener, source_site_instance, is_new_browsing_instance,
3621 opener->GetLastCommittedURL(), params.frame_name, params.target_url,
3622 partition_id, session_storage_namespace));
[email protected]dd6730412013-08-14 15:03:373623 }
3624
danakj22b4e8b2019-08-01 23:14:393625 bool renderer_started_hidden =
3626 params.disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB;
3627
Aaron Colwelleb219982020-01-16 02:17:273628 // We usually create the new window in the same BrowsingInstance (group of
3629 // script-related windows), by passing in the current SiteInstance. However,
3630 // if the opener is being suppressed (in a non-guest), we do not provide
3631 // a SiteInstance which causes a new one to get created in its own
3632 // BrowsingInstance.
3633 bool is_guest = BrowserPluginGuest::IsGuest(this);
3634 scoped_refptr<SiteInstance> site_instance =
3635 params.opener_suppressed && !is_guest ? nullptr : source_site_instance;
3636
[email protected]dd6730412013-08-14 15:03:373637 // Create the new web contents. This will automatically create the new
3638 // WebContentsView. In the future, we may want to create the view separately.
[email protected]fc72bb12013-06-02 21:13:463639 CreateParams create_params(GetBrowserContext(), site_instance.get());
nasko48321ca32015-07-02 20:44:123640 create_params.main_frame_name = params.frame_name;
alexmos4cf2aa32015-07-15 23:40:433641 create_params.opener_render_process_id = render_process_id;
csharrison95f01e922017-04-24 18:52:353642 create_params.opener_render_frame_id = opener->GetRoutingID();
[email protected]50d326e2014-05-20 17:59:063643 create_params.opener_suppressed = params.opener_suppressed;
danakj22b4e8b2019-08-01 23:14:393644 create_params.initially_hidden = renderer_started_hidden;
arthursonzogni034bb9c2020-10-01 08:29:563645 create_params.initial_popup_url = params.target_url;
[email protected]50d326e2014-05-20 17:59:063646
Albert J. Wong65fe64d2019-09-20 02:48:143647 // Even though all codepaths leading here are in response to a renderer
3648 // tryng to open a new window, if the new window ends up in a different
3649 // browsing instance, then the RenderViewHost, RenderWidgetHost,
3650 // RenderFrameHost constellation is effectively browser initiated
3651 // the opener's process will not given the routing IDs for the new
3652 // objects.
3653 create_params.renderer_initiated_creation = !is_new_browsing_instance;
Albert J. Wong1ceccef92019-10-08 08:25:203654
Albert J. Wong65fe64d2019-09-20 02:48:143655 std::unique_ptr<WebContentsImpl> new_contents;
[email protected]c4538072013-03-18 02:17:553656 if (!is_guest) {
3657 create_params.context = view_->GetNativeView();
Albert J. Wong65fe64d2019-09-20 02:48:143658 new_contents = WebContentsImpl::Create(create_params);
3659 } else {
3660 new_contents = base::WrapUnique(static_cast<WebContentsImpl*>(
3661 GetBrowserPluginGuest()->CreateNewGuestWindow(create_params)));
[email protected]c4538072013-03-18 02:17:553662 }
Albert J. Wong65fe64d2019-09-20 02:48:143663 auto* new_contents_impl = new_contents.get();
danakje6c01622018-10-05 19:39:263664
3665 new_contents_impl->GetController().SetSessionStorageNamespace(
erikchenbee5c9622018-04-27 19:30:253666 partition_id, session_storage_namespace);
[email protected]d1198fd2012-08-13 22:50:193667
alexmos646fec02015-07-25 00:11:493668 // If the new frame has a name, make sure any SiteInstances that can find
3669 // this named frame have proxies for it. Must be called after
3670 // SetSessionStorageNamespace, since this calls CreateRenderView, which uses
3671 // GetSessionStorageNamespace.
3672 if (!params.frame_name.empty())
danakje6c01622018-10-05 19:39:263673 new_contents_impl->GetRenderManager()->CreateProxiesForNewNamedFrame();
alexmos646fec02015-07-25 00:11:493674
[email protected]c4538072013-03-18 02:17:553675 // Save the window for later if we're not suppressing the opener (since it
[email protected]d70bea92013-04-05 04:23:343676 // will be shown immediately).
3677 if (!params.opener_suppressed) {
3678 if (!is_guest) {
danakje6c01622018-10-05 19:39:263679 WebContentsView* new_view = new_contents_impl->view_.get();
[email protected]bafe6cd2012-05-23 23:09:503680
[email protected]d70bea92013-04-05 04:23:343681 // TODO(brettw): It seems bogus that we have to call this function on the
3682 // newly created object and give it one of its own member variables.
danakj22b4e8b2019-08-01 23:14:393683 RenderWidgetHostView* widget_view = new_view->CreateViewForWidget(
W. James MacLean13d834d2019-12-04 16:06:453684 new_contents_impl->GetRenderViewHost()->GetWidget());
danakj22b4e8b2019-08-01 23:14:393685 if (!renderer_started_hidden) {
3686 // RenderWidgets for frames always initialize as hidden. If the renderer
3687 // created this window as visible, then we show it here.
3688 widget_view->Show();
3689 }
[email protected]d70bea92013-04-05 04:23:343690 }
[email protected]bafe6cd2012-05-23 23:09:503691 // Save the created window associated with the route so we can show it
3692 // later.
Albert J. Wongcb004632018-07-10 22:58:253693 //
3694 // TODO(ajwong): This should be keyed off the RenderFrame routing id or the
3695 // FrameTreeNode id instead of the routing id of the Widget for the main
3696 // frame. https://crbug.com/545684
Fergal Daly052873a82020-03-11 14:45:493697 int32_t main_frame_routing_id = new_contents_impl->GetMainFrame()
3698 ->GetRenderWidgetHost()
3699 ->GetRoutingID();
3700 GlobalRoutingID id(render_process_id, main_frame_routing_id);
Joel Hockey8c2011b22020-04-30 05:07:193701 pending_contents_[id] =
3702 CreatedWindow(std::move(new_contents), params.target_url);
danakje6c01622018-10-05 19:39:263703 AddDestructionObserver(new_contents_impl);
[email protected]bafe6cd2012-05-23 23:09:503704 }
3705
3706 if (delegate_) {
Bryan McQuaded2b93c02017-07-14 22:26:313707 delegate_->WebContentsCreated(this, render_process_id,
3708 opener->GetRoutingID(), params.frame_name,
danakje6c01622018-10-05 19:39:263709 params.target_url, new_contents_impl);
[email protected]bafe6cd2012-05-23 23:09:503710 }
3711
Alexander Timin90c20c32020-08-12 15:28:323712 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3713 observer->DidOpenRequestedURL(new_contents_impl, opener, params.target_url,
3714 params.referrer.To<Referrer>(),
3715 params.disposition, ui::PAGE_TRANSITION_LINK,
3716 false, // started_from_context_menu
3717 true); // renderer_initiated
3718 });
pnolandaae574e2017-03-06 21:04:213719
[email protected]bafe6cd2012-05-23 23:09:503720 if (params.opener_suppressed) {
3721 // When the opener is suppressed, the original renderer cannot access the
3722 // new window. As a result, we need to show and navigate the window here.
[email protected]eda238a12012-09-07 23:44:003723 bool was_blocked = false;
erikchenbee5c9622018-04-27 19:30:253724
[email protected]eda238a12012-09-07 23:44:003725 if (delegate_) {
danakje6c01622018-10-05 19:39:263726 base::WeakPtr<WebContentsImpl> weak_new_contents =
3727 new_contents_impl->weak_factory_.GetWeakPtr();
nick0d558482017-02-13 22:27:223728
danakje6c01622018-10-05 19:39:263729 gfx::Rect initial_rect; // Report an empty initial rect.
Albert J. Wong65fe64d2019-09-20 02:48:143730 delegate_->AddNewContents(this, std::move(new_contents),
Joel Hockey891e88062020-04-30 05:38:443731 params.target_url, params.disposition,
3732 initial_rect, has_user_gesture, &was_blocked);
danakje6c01622018-10-05 19:39:263733 // The delegate may delete |new_contents_impl| during AddNewContents().
nick0d558482017-02-13 22:27:223734 if (!weak_new_contents)
Albert J. Wong65fe64d2019-09-20 02:48:143735 return nullptr;
[email protected]eda238a12012-09-07 23:44:003736 }
erikchenbee5c9622018-04-27 19:30:253737
[email protected]eda238a12012-09-07 23:44:003738 if (!was_blocked) {
Nasko Oskov83a8cf92018-10-19 14:58:563739 std::unique_ptr<NavigationController::LoadURLParams> load_params =
3740 std::make_unique<NavigationController::LoadURLParams>(
3741 params.target_url);
Nasko Oskov93e7c55c2018-12-19 01:59:293742 load_params->initiator_origin = opener->GetLastCommittedOrigin();
Lukasz Anforowiczd2629b42020-08-11 16:07:313743 // Avoiding setting |load_params->source_site_instance| when
3744 // |opener_suppressed| is true, because in that case we do not want to use
3745 // the old SiteInstance and/or BrowsingInstance. See also the test here:
3746 // NewPopupCOOP_SameOriginPolicyAndCrossOriginIframeSetsNoopener.
Leon Han963dc182018-11-06 05:41:483747 load_params->referrer = params.referrer.To<Referrer>();
Nasko Oskov83a8cf92018-10-19 14:58:563748 load_params->transition_type = ui::PAGE_TRANSITION_LINK;
3749 load_params->is_renderer_initiated = true;
Sergey Kuznetsov32257a22019-02-11 20:26:503750 load_params->has_user_gesture = has_user_gesture;
mariakhomenkoa4971c12015-07-21 19:04:373751
3752 if (delegate_ && !is_guest &&
3753 !delegate_->ShouldResumeRequestsForCreatedWindow()) {
Nasko Oskov83a8cf92018-10-19 14:58:563754 // We are in asynchronous add new contents path, delay navigation.
3755 DCHECK(!new_contents_impl->delayed_open_url_params_);
3756 new_contents_impl->delayed_load_url_params_ = std::move(load_params);
mariakhomenkoa4971c12015-07-21 19:04:373757 } else {
Nasko Oskov83a8cf92018-10-19 14:58:563758 new_contents_impl->controller_.LoadURLWithParams(*load_params.get());
Nasko Oskov28ebd5b2018-12-07 22:29:333759 if (!is_guest)
3760 new_contents_impl->Focus();
mariakhomenkoa4971c12015-07-21 19:04:373761 }
[email protected]eda238a12012-09-07 23:44:003762 }
[email protected]bafe6cd2012-05-23 23:09:503763 }
Albert J. Wong65fe64d2019-09-20 02:48:143764 return new_contents_impl;
[email protected]bafe6cd2012-05-23 23:09:503765}
3766
Dave Tapuskad9835622020-03-10 17:32:313767void WebContentsImpl::CreateNewWidget(
Tal Pressman5dcd2382020-08-26 07:13:053768 AgentSchedulingGroupHost& agent_scheduling_group,
3769 int32_t route_id,
Dave Tapuska8499eec2020-03-16 17:54:303770 mojo::PendingAssociatedReceiver<blink::mojom::WidgetHost> blink_widget_host,
3771 mojo::PendingAssociatedRemote<blink::mojom::Widget> blink_widget) {
Tal Pressman5dcd2382020-08-26 07:13:053772 CreateNewWidget(agent_scheduling_group, route_id,
3773 /*is_fullscreen=*/false, std::move(blink_widget_host),
3774 std::move(blink_widget));
[email protected]bafe6cd2012-05-23 23:09:503775}
3776
Julie Jeongeun Kimcaacf9102019-09-12 02:13:053777void WebContentsImpl::CreateNewFullscreenWidget(
Tal Pressman5dcd2382020-08-26 07:13:053778 AgentSchedulingGroupHost& agent_scheduling_group,
3779 int32_t route_id,
Dave Tapuska8499eec2020-03-16 17:54:303780 mojo::PendingAssociatedReceiver<blink::mojom::WidgetHost> blink_widget_host,
3781 mojo::PendingAssociatedRemote<blink::mojom::Widget> blink_widget) {
Tal Pressman5dcd2382020-08-26 07:13:053782 CreateNewWidget(agent_scheduling_group, route_id,
3783 /*is_fullscreen=*/true, std::move(blink_widget_host),
3784 std::move(blink_widget));
[email protected]bafe6cd2012-05-23 23:09:503785}
3786
Dave Tapuskad9835622020-03-10 17:32:313787void WebContentsImpl::CreateNewWidget(
Tal Pressman5dcd2382020-08-26 07:13:053788 AgentSchedulingGroupHost& agent_scheduling_group,
Dave Tapuskad9835622020-03-10 17:32:313789 int32_t route_id,
3790 bool is_fullscreen,
Dave Tapuska8499eec2020-03-16 17:54:303791 mojo::PendingAssociatedReceiver<blink::mojom::WidgetHost> blink_widget_host,
3792 mojo::PendingAssociatedRemote<blink::mojom::Widget> blink_widget) {
Alexander Timin5fdeff22020-09-08 09:20:373793 OPTIONAL_TRACE_EVENT1(
3794 "content", "WebContentsImpl::CreateNewWidget", "params",
3795 base::trace_event::TracedValue::Build(
3796 {{"route_id", route_id}, {"is_fullscreen", is_fullscreen}}));
Tal Pressman5dcd2382020-08-26 07:13:053797 RenderProcessHost* process = agent_scheduling_group.GetProcess();
kenrbb46f86a2015-12-07 07:53:233798 // A message to create a new widget can only come from an active process for
[email protected]a8504022013-12-04 20:23:513799 // this WebContentsImpl instance. If any other process sends the request,
3800 // it is invalid and the process must be terminated.
Tal Pressman5dcd2382020-08-26 07:13:053801 if (!HasMatchingProcess(&frame_tree_, process->GetID())) {
Lukasz Anforowicz6f746282018-01-04 23:24:513802 ReceivedBadMessage(process, bad_message::WCI_NEW_WIDGET_PROCESS_MISMATCH);
[email protected]a8504022013-12-04 20:23:513803 return;
3804 }
3805
Tal Pressman5dcd2382020-08-26 07:13:053806 RenderWidgetHostImpl* widget_host = new RenderWidgetHostImpl(
3807 this, agent_scheduling_group, route_id, IsHidden(),
3808 std::make_unique<FrameTokenMessageQueue>());
Dave Tapuska8499eec2020-03-16 17:54:303809
3810 widget_host->BindWidgetInterfaces(std::move(blink_widget_host),
3811 std::move(blink_widget));
[email protected]cfd80b02014-05-01 17:46:483812 RenderWidgetHostViewBase* widget_view =
3813 static_cast<RenderWidgetHostViewBase*>(
danakj0b246942018-09-17 21:30:273814 view_->CreateViewForChildWidget(widget_host));
[email protected]83918ec2013-01-10 15:37:193815 if (!widget_view)
3816 return;
danakj0b246942018-09-17 21:30:273817 // Fullscreen child widgets are frames, other child widgets are popups, and
3818 // popups should not get activated.
3819 if (!is_fullscreen)
3820 widget_view->SetWidgetType(WidgetType::kPopup);
[email protected]bafe6cd2012-05-23 23:09:503821 // Save the created widget associated with the route so we can show it later.
Tal Pressman5dcd2382020-08-26 07:13:053822 pending_widget_views_[GlobalRoutingID(process->GetID(), route_id)] =
alexmosc2a8cec2016-05-23 22:19:533823 widget_view;
[email protected]bafe6cd2012-05-23 23:09:503824}
3825
Mike Wassermandabad612020-08-13 04:26:273826void WebContentsImpl::ShowCreatedWindow(RenderFrameHost* opener,
nick5ae4d2d2017-01-06 01:18:353827 int main_frame_widget_route_id,
[email protected]bafe6cd2012-05-23 23:09:503828 WindowOpenDisposition disposition,
bokan107a47f2015-02-03 23:23:393829 const gfx::Rect& initial_rect,
[email protected]bafe6cd2012-05-23 23:09:503830 bool user_gesture) {
Alexander Timin5fdeff22020-09-08 09:20:373831 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::ShowCreatedWindow",
3832 "opener", base::trace_event::ToTracedValue(opener),
3833 "main_frame_widget_route_id",
3834 main_frame_widget_route_id);
danakje6c01622018-10-05 19:39:263835 // This method is the renderer requesting an existing top level window to
3836 // show a new top level window that the renderer created. Each top level
3837 // window is associated with a WebContents. In this case it was created
3838 // earlier but showing it was deferred until the renderer requested for it
3839 // to be shown. We find that previously created WebContents here.
3840 // TODO(danakj): Why do we defer this show step until the renderer asks for it
3841 // when it will always do so. What needs to happen in the renderer before we
3842 // reach here?
Mike Wassermandabad612020-08-13 04:26:273843 base::Optional<CreatedWindow> owned_created = GetCreatedWindow(
3844 opener->GetProcess()->GetID(), main_frame_widget_route_id);
Joel Hockey8c2011b22020-04-30 05:07:193845
danakje6c01622018-10-05 19:39:263846 // The browser may have rejected the request to make a new window, or the
3847 // renderer could be sending an invalid route id. Ignore the request then.
Joel Hockey8c2011b22020-04-30 05:07:193848 if (!owned_created || !owned_created->contents)
danakje6c01622018-10-05 19:39:263849 return;
mariakhomenko44bdc4732015-04-29 01:55:383850
Joel Hockey8c2011b22020-04-30 05:07:193851 WebContentsImpl* created = owned_created->contents.get();
3852
danakje6c01622018-10-05 19:39:263853 // This uses the delegate for the WebContents where the window was created
3854 // from, to control how to show the newly created window.
3855 WebContentsDelegate* delegate = GetDelegate();
nick5ae4d2d2017-01-06 01:18:353856
Mike Wassermanb6bc0152020-08-25 22:46:203857 // Individual members of |initial_rect| may be 0 to indicate that the
3858 // window.open() feature string did not specify a value. This code does not
3859 // have the ability to distinguish between an unspecified value and 0.
3860 // Assume that if any single value is non-zero, all values should be used.
3861 // TODO(crbug.com/897300): Plumb values as specified; set defaults here?
3862 gfx::Rect adjusted_rect = initial_rect;
3863 int64_t display_id = display::kInvalidDisplayId;
3864 if (adjusted_rect != gfx::Rect())
3865 display_id = AdjustRequestedWindowBounds(&adjusted_rect, opener);
3866
3867 // Drop fullscreen when opening a WebContents to prohibit deceptive behavior.
3868 // Only drop fullscreen on the specific destination display, if it is known.
3869 // This supports sites using cross-screen window placement capabilities to
3870 // retain fullscreen and open a window on another screen.
3871 ForSecurityDropFullscreen(display_id).RunAndReset();
3872
danakje6c01622018-10-05 19:39:263873 // The delegate can be null in tests, so we must check for it :(.
3874 if (delegate) {
3875 // Mark the web contents as pending resume, then immediately do
3876 // the resume if the delegate wants it.
3877 created->is_resume_pending_ = true;
3878 if (delegate->ShouldResumeRequestsForCreatedWindow())
3879 created->ResumeLoadingCreatedWebContents();
3880
3881 base::WeakPtr<WebContentsImpl> weak_created =
3882 created->weak_factory_.GetWeakPtr();
Joel Hockey8c2011b22020-04-30 05:07:193883 delegate->AddNewContents(this, std::move(owned_created->contents),
Joel Hockey891e88062020-04-30 05:38:443884 std::move(owned_created->target_url), disposition,
Mike Wassermandabad612020-08-13 04:26:273885 adjusted_rect, user_gesture, nullptr);
danakje6c01622018-10-05 19:39:263886 // The delegate may delete |created| during AddNewContents().
3887 if (!weak_created)
3888 return;
[email protected]eda238a12012-09-07 23:44:003889 }
danakje6c01622018-10-05 19:39:263890
3891 RenderWidgetHostImpl* rwh = created->GetMainFrame()->GetRenderWidgetHost();
3892 DCHECK_EQ(main_frame_widget_route_id, rwh->GetRoutingID());
3893 rwh->Send(new WidgetMsg_SetBounds_ACK(rwh->GetRoutingID()));
[email protected]bafe6cd2012-05-23 23:09:503894}
3895
alexmosc2a8cec2016-05-23 22:19:533896void WebContentsImpl::ShowCreatedWidget(int process_id,
Albert J. Wongf6e13ed2018-09-18 15:25:473897 int widget_route_id,
bokan107a47f2015-02-03 23:23:393898 const gfx::Rect& initial_rect) {
Alexander Timin5fdeff22020-09-08 09:20:373899 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::ShowCreatedWidget",
3900 "process_id", process_id, "widget_route_id",
3901 widget_route_id);
[email protected]cfd80b02014-05-01 17:46:483902 RenderWidgetHostViewBase* widget_host_view =
alexmosc2a8cec2016-05-23 22:19:533903 static_cast<RenderWidgetHostViewBase*>(
Dave Tapuska22cafa32020-10-06 11:56:053904 GetCreatedWidget(process_id, widget_route_id));
[email protected]bafe6cd2012-05-23 23:09:503905 if (!widget_host_view)
3906 return;
[email protected]cfd80b02014-05-01 17:46:483907
W. James MacLeanec4125c2019-09-27 18:56:003908 // GetOutermostWebContents() returns |this| if there are no outer WebContents.
W. James MacLean3c5f50462019-10-28 16:24:213909 auto* outer_web_contents = GetOuterWebContents();
3910 auto* outermost_web_contents = GetOutermostWebContents();
W. James MacLeanec4125c2019-09-27 18:56:003911 RenderWidgetHostView* view =
W. James MacLean3c5f50462019-10-28 16:24:213912 outermost_web_contents->GetRenderWidgetHostView();
3913 // It's not entirely obvious why we need the transform only in the case where
3914 // the outer webcontents is not the same as the outermost webcontents. It may
3915 // be due to the fact that oopifs that are children of the mainframe get
3916 // correct values for their screenrects, but deeper cross-process frames do
3917 // not. Hopefully this can be resolved with https://crbug.com/928825.
3918 // Handling these cases separately is needed for http://crbug.com/1015298.
3919 bool needs_transform = this != outermost_web_contents &&
3920 outermost_web_contents != outer_web_contents;
W. James MacLeanec4125c2019-09-27 18:56:003921
3922 gfx::Rect transformed_rect(initial_rect);
3923 RenderWidgetHostView* this_view = GetRenderWidgetHostView();
W. James MacLean3c5f50462019-10-28 16:24:213924 if (needs_transform) {
W. James MacLeanec4125c2019-09-27 18:56:003925 // We need to transform the coordinates of initial_rect.
3926 gfx::Point origin =
3927 this_view->TransformPointToRootCoordSpace(initial_rect.origin());
3928 gfx::Point bottom_right =
3929 this_view->TransformPointToRootCoordSpace(initial_rect.bottom_right());
3930 transformed_rect =
3931 gfx::Rect(origin.x(), origin.y(), bottom_right.x() - origin.x(),
3932 bottom_right.y() - origin.y());
[email protected]cfd80b02014-05-01 17:46:483933 }
3934
Dave Tapuska22cafa32020-10-06 11:56:053935 widget_host_view->InitAsPopup(view, transformed_rect);
[email protected]89054502012-06-03 10:29:243936
yiyixcb1fbc4f2018-03-16 19:54:083937 RenderWidgetHostImpl* render_widget_host_impl = widget_host_view->host();
[email protected]89054502012-06-03 10:29:243938 render_widget_host_impl->Init();
[email protected]bafe6cd2012-05-23 23:09:503939}
3940
Joel Hockey8c2011b22020-04-30 05:07:193941base::Optional<CreatedWindow> WebContentsImpl::GetCreatedWindow(
nick5ae4d2d2017-01-06 01:18:353942 int process_id,
3943 int main_frame_widget_route_id) {
Alexander Timin5fdeff22020-09-08 09:20:373944 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::GetCreatedWindow",
3945 "process_id", process_id, "main_frame_widget_route_id",
3946 main_frame_widget_route_id);
3947
Lukasz Anforowicz09060bdf72018-08-23 15:53:173948 auto key = GlobalRoutingID(process_id, main_frame_widget_route_id);
nick5ae4d2d2017-01-06 01:18:353949 auto iter = pending_contents_.find(key);
[email protected]bafe6cd2012-05-23 23:09:503950
3951 // Certain systems can block the creation of new windows. If we didn't succeed
3952 // in creating one, just return NULL.
alexmosc2a8cec2016-05-23 22:19:533953 if (iter == pending_contents_.end())
Joel Hockey8c2011b22020-04-30 05:07:193954 return base::nullopt;
[email protected]bafe6cd2012-05-23 23:09:503955
Joel Hockey8c2011b22020-04-30 05:07:193956 CreatedWindow result = std::move(iter->second);
3957 WebContentsImpl* new_contents = result.contents.get();
nick5ae4d2d2017-01-06 01:18:353958 pending_contents_.erase(key);
Joel Hockey8c2011b22020-04-30 05:07:193959 RemoveDestructionObserver(new_contents);
[email protected]bafe6cd2012-05-23 23:09:503960
[email protected]d70bea92013-04-05 04:23:343961 // Don't initialize the guest WebContents immediately.
Joel Hockey8c2011b22020-04-30 05:07:193962 if (BrowserPluginGuest::IsGuest(new_contents))
3963 return result;
[email protected]d70bea92013-04-05 04:23:343964
Lukasz Anforowicz5510ed652018-06-06 16:16:193965 if (!new_contents->GetMainFrame()->GetProcess()->IsInitializedAndNotDead() ||
nick5ae4d2d2017-01-06 01:18:353966 !new_contents->GetMainFrame()->GetView()) {
Joel Hockey8c2011b22020-04-30 05:07:193967 return base::nullopt;
nick5ae4d2d2017-01-06 01:18:353968 }
[email protected]bafe6cd2012-05-23 23:09:503969
Joel Hockey8c2011b22020-04-30 05:07:193970 return result;
[email protected]bafe6cd2012-05-23 23:09:503971}
3972
alexmosc2a8cec2016-05-23 22:19:533973RenderWidgetHostView* WebContentsImpl::GetCreatedWidget(int process_id,
3974 int route_id) {
Alexander Timin5fdeff22020-09-08 09:20:373975 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::GetCreatedWidget",
3976 "process_id", process_id, "route_id", route_id);
3977
Lukasz Anforowicz09060bdf72018-08-23 15:53:173978 auto iter = pending_widget_views_.find(GlobalRoutingID(process_id, route_id));
[email protected]bafe6cd2012-05-23 23:09:503979 if (iter == pending_widget_views_.end()) {
3980 DCHECK(false);
alexmosc2a8cec2016-05-23 22:19:533981 return nullptr;
[email protected]bafe6cd2012-05-23 23:09:503982 }
3983
3984 RenderWidgetHostView* widget_host_view = iter->second;
Lukasz Anforowicz09060bdf72018-08-23 15:53:173985 pending_widget_views_.erase(GlobalRoutingID(process_id, route_id));
[email protected]bafe6cd2012-05-23 23:09:503986
3987 RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
Lukasz Anforowicz5510ed652018-06-06 16:16:193988 if (!widget_host->GetProcess()->IsInitializedAndNotDead()) {
[email protected]bafe6cd2012-05-23 23:09:503989 // The view has gone away or the renderer crashed. Nothing to do.
alexmosc2a8cec2016-05-23 22:19:533990 return nullptr;
[email protected]bafe6cd2012-05-23 23:09:503991 }
3992
3993 return widget_host_view;
3994}
3995
[email protected]f13b4202012-06-12 23:53:233996void WebContentsImpl::RequestMediaAccessPermission(
[email protected]33662e52013-01-07 21:31:093997 const MediaStreamRequest& request,
Mark Pilgrim57499082018-06-12 12:38:303998 MediaResponseCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:373999 OPTIONAL_TRACE_EVENT2("content",
4000 "WebContentsImpl::RequestMediaAccessPermission",
4001 "render_process_id", request.render_process_id,
4002 "render_frame_id", request.render_frame_id);
4003
[email protected]d19b84b2014-03-14 11:52:374004 if (delegate_) {
Mark Pilgrim57499082018-06-12 12:38:304005 delegate_->RequestMediaAccessPermission(this, request, std::move(callback));
[email protected]d19b84b2014-03-14 11:52:374006 } else {
Antonio Gomes0d42960a2019-06-05 12:35:514007 std::move(callback).Run(
4008 blink::MediaStreamDevices(),
4009 blink::mojom::MediaStreamRequestResult::FAILED_DUE_TO_SHUTDOWN,
4010 std::unique_ptr<MediaStreamUI>());
[email protected]d19b84b2014-03-14 11:52:374011 }
[email protected]f13b4202012-06-12 23:53:234012}
4013
Chandan Padhia4b8bcb72017-09-12 16:41:044014bool WebContentsImpl::CheckMediaAccessPermission(
Raymes Khouryad7c24a12018-03-05 23:22:584015 RenderFrameHost* render_frame_host,
Chandan Padhia4b8bcb72017-09-12 16:41:044016 const url::Origin& security_origin,
Antonio Gomesc8b734b2019-06-05 18:22:164017 blink::mojom::MediaStreamType type) {
Alexander Timin5fdeff22020-09-08 09:20:374018 OPTIONAL_TRACE_EVENT2("content",
4019 "WebContentsImpl::CheckMediaAccessPermission",
4020 "render_frame_host", render_frame_host,
4021 "security_origin", security_origin.Serialize());
4022
Antonio Gomesc8b734b2019-06-05 18:22:164023 DCHECK(type == blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE ||
4024 type == blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE);
Chandan Padhia4b8bcb72017-09-12 16:41:044025 return delegate_ && delegate_->CheckMediaAccessPermission(
Raymes Khouryad7c24a12018-03-05 23:22:584026 render_frame_host, security_origin.GetURL(), type);
grunell657d4d82014-09-18 00:09:434027}
4028
Guido Urdaneta73fa6632019-01-14 18:46:264029std::string WebContentsImpl::GetDefaultMediaDeviceID(
Antonio Gomesc8b734b2019-06-05 18:22:164030 blink::mojom::MediaStreamType type) {
Alexander Timin5fdeff22020-09-08 09:20:374031 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::GetDefaultMediaDeviceID",
4032 "type", static_cast<int>(type));
4033
guidou8a440b842017-01-30 13:58:434034 if (!delegate_)
4035 return std::string();
4036 return delegate_->GetDefaultMediaDeviceID(this, type);
4037}
4038
[email protected]cc9200432013-07-23 23:02:404039SessionStorageNamespace* WebContentsImpl::GetSessionStorageNamespace(
4040 SiteInstance* instance) {
4041 return controller_.GetSessionStorageNamespace(instance);
4042}
4043
[email protected]6de7fc482014-06-06 10:46:444044SessionStorageNamespaceMap WebContentsImpl::GetSessionStorageNamespaceMap() {
4045 return controller_.GetSessionStorageNamespaceMap();
4046}
4047
[email protected]9b159a52013-10-03 17:24:554048FrameTree* WebContentsImpl::GetFrameTree() {
4049 return &frame_tree_;
4050}
4051
aelias5252baa2016-04-10 01:18:024052bool WebContentsImpl::IsOverridingUserAgent() {
4053 return GetController().GetVisibleEntry() &&
4054 GetController().GetVisibleEntry()->GetIsOverridingUserAgent();
4055}
4056
avi85ee8362016-10-08 02:09:084057bool WebContentsImpl::IsJavaScriptDialogShowing() const {
4058 return is_showing_javascript_dialog_;
4059}
4060
avic031d392017-03-03 03:09:424061bool WebContentsImpl::ShouldIgnoreUnresponsiveRenderer() {
Dominique Fauteux-Chapleau99244382020-07-08 20:37:004062 if (suppress_unresponsive_renderer_count_ > 0)
4063 return true;
4064
avic031d392017-03-03 03:09:424065 // Ignore unresponsive renderers if the debugger is attached to them since the
4066 // unresponsiveness might be a result of the renderer sitting on a breakpoint.
4067 //
David Bienvenu525f8a02019-02-15 02:02:424068#ifdef OS_WIN
4069 // Check if a windows debugger is attached to the renderer process.
4070 base::ProcessHandle process_handle =
4071 GetMainFrame()->GetProcess()->GetProcess().Handle();
4072 BOOL debugger_present = FALSE;
4073 if (CheckRemoteDebuggerPresent(process_handle, &debugger_present) &&
4074 debugger_present)
4075 return true;
4076#endif // OS_WIN
4077
avic031d392017-03-03 03:09:424078 // TODO(pfeldman): Fix this to only return true if the renderer is *actually*
4079 // sitting on a breakpoint. https://crbug.com/684202
4080 return DevToolsAgentHost::IsDebuggerAttached(this);
4081}
4082
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414083ui::AXMode WebContentsImpl::GetAccessibilityMode() {
[email protected]95640212014-07-26 18:14:304084 return accessibility_mode_;
4085}
4086
Mario Sanchez Prada5d7f1ac2020-07-16 17:18:404087void WebContentsImpl::AXTreeIDForMainFrameHasChanged() {
Alexander Timin5fdeff22020-09-08 09:20:374088 OPTIONAL_TRACE_EVENT0("content",
4089 "WebContentsImpl::AXTreeIDForMainFrameHasChanged");
4090
Mario Sanchez Prada5d7f1ac2020-07-16 17:18:404091 RenderWidgetHostViewBase* rwhv =
4092 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
4093 if (rwhv)
4094 rwhv->SetMainFrameAXTreeID(GetMainFrame()->GetAXTreeID());
4095
Alexander Timin90c20c32020-08-12 15:28:324096 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4097 observer->AXTreeIDForMainFrameHasChanged();
4098 });
Mario Sanchez Prada5d7f1ac2020-07-16 17:18:404099}
4100
Dominic Mazzonia7b0edb22017-08-09 16:32:514101void WebContentsImpl::AccessibilityEventReceived(
Dominic Mazzoniccbaa9b2018-06-06 07:44:234102 const AXEventNotificationDetails& details) {
Alexander Timin5fdeff22020-09-08 09:20:374103 OPTIONAL_TRACE_EVENT0("content",
4104 "WebContentsImpl::AccessibilityEventReceived");
Alexander Timin90c20c32020-08-12 15:28:324105 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4106 observer->AccessibilityEventReceived(details);
4107 });
[email protected]31a71eaf2014-03-13 01:47:364108}
4109
dmazzoni2400c462016-08-23 15:07:134110void WebContentsImpl::AccessibilityLocationChangesReceived(
4111 const std::vector<AXLocationChangeNotificationDetails>& details) {
Alexander Timin5fdeff22020-09-08 09:20:374112 OPTIONAL_TRACE_EVENT0(
4113 "content", "WebContentsImpl::AccessibilityLocationChangesReceived");
Alexander Timin90c20c32020-08-12 15:28:324114 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4115 observer->AccessibilityLocationChangesReceived(details);
4116 });
dmazzoni2400c462016-08-23 15:07:134117}
4118
Alexander Surkov2ab51622020-09-02 12:01:424119std::string WebContentsImpl::DumpAccessibilityTree(
Abigail Kleinabb428332019-09-13 18:26:214120 bool internal,
Alexander Surkov90482882020-10-12 16:30:384121 std::vector<ui::AXPropertyFilter> property_filters) {
Alexander Timin5fdeff22020-09-08 09:20:374122 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DumpAccessibilityTree");
James Wallace-Leeeafc94cb92018-07-23 21:35:094123 auto* ax_mgr = GetOrCreateRootBrowserAccessibilityManager();
4124 DCHECK(ax_mgr);
Lei Zhangc98caa3822019-11-07 19:17:274125 return AccessibilityTreeFormatterBase::DumpAccessibilityTreeFromManager(
Abigail Kleinabb428332019-09-13 18:26:214126 ax_mgr, internal, property_filters);
James Wallace-Leeeafc94cb92018-07-23 21:35:094127}
4128
Abigail Kleinaa898742019-11-01 02:31:254129void WebContentsImpl::RecordAccessibilityEvents(
Abigail Kleinbb8304bd2020-05-18 21:44:184130 bool start_recording,
4131 base::Optional<AccessibilityEventCallback> callback) {
Alexander Timin5fdeff22020-09-08 09:20:374132 OPTIONAL_TRACE_EVENT0("content",
4133 "WebContentsImpl::RecordAccessibilityEvents");
Abigail Kleinbb8304bd2020-05-18 21:44:184134 // Only pass a callback to RecordAccessibilityEvents when starting to record.
4135 DCHECK_EQ(start_recording, callback.has_value());
4136 if (start_recording) {
Abigail Kleinaa898742019-11-01 02:31:254137 SetAccessibilityMode(ui::AXMode::kWebContents);
4138 auto* ax_mgr = GetOrCreateRootBrowserAccessibilityManager();
4139 DCHECK(ax_mgr);
4140 base::ProcessId pid = base::Process::Current().Pid();
Alexander Surkov97e969632020-09-29 02:30:054141 event_recorder_ = content::AccessibilityEventRecorder::Create(ax_mgr, pid);
Abigail Kleinbb8304bd2020-05-18 21:44:184142 event_recorder_->ListenToEvents(*callback);
Abigail Kleinaa898742019-11-01 02:31:254143 } else {
Abigail Kleinbb8304bd2020-05-18 21:44:184144 if (event_recorder_) {
4145 event_recorder_->FlushAsyncEvents();
4146 event_recorder_.reset(nullptr);
4147 }
Abigail Kleinaa898742019-11-01 02:31:254148 }
4149}
4150
Ke He7319dbe2017-11-09 05:54:444151device::mojom::GeolocationContext* WebContentsImpl::GetGeolocationContext() {
Alexander Timin5fdeff22020-09-08 09:20:374152 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GetGeolocationContext");
Ella Ge3e375b702020-06-05 15:57:164153 if (delegate_) {
4154 auto* installed_webapp_context =
4155 delegate_->GetInstalledWebappGeolocationContext();
4156 if (installed_webapp_context)
4157 return installed_webapp_context;
4158 }
4159
Ken Rockotce010f02019-12-12 23:32:324160 if (!geolocation_context_) {
4161 GetDeviceService().BindGeolocationContext(
4162 geolocation_context_.BindNewPipeAndPassReceiver());
4163 }
Conley Owens6894c4f2017-07-10 19:29:134164 return geolocation_context_.get();
blundellc57b93f2014-10-29 13:19:574165}
4166
ke.he98b761e2017-05-09 05:59:174167device::mojom::WakeLockContext* WebContentsImpl::GetWakeLockContext() {
blundelld8cd72b2017-03-28 07:18:384168 if (!wake_lock_context_host_)
Fergal Daly55b6d722020-09-11 07:56:334169 wake_lock_context_host_ = std::make_unique<WakeLockContextHost>(this);
blundelle75a8f92017-03-27 08:11:174170 return wake_lock_context_host_->GetWakeLockContext();
alogvinovf50445a2015-10-30 13:00:124171}
4172
blundellf5316fc2017-05-15 11:49:034173#if defined(OS_ANDROID)
Miyoung Shin59f39ff2019-09-17 07:23:204174void WebContentsImpl::GetNFC(
Reilly Grantafbe2242020-02-20 21:14:554175 RenderFrameHost* render_frame_host,
Miyoung Shin59f39ff2019-09-17 07:23:204176 mojo::PendingReceiver<device::mojom::NFC> receiver) {
Reilly Grantafbe2242020-02-20 21:14:554177 if (!nfc_host_)
4178 nfc_host_ = std::make_unique<NFCHost>(this);
4179 nfc_host_->GetNFC(render_frame_host, std::move(receiver));
blundellf5316fc2017-05-15 11:49:034180}
4181#endif
4182
Evan Stade5e750ad02017-08-07 21:59:274183void WebContentsImpl::SetNotWaitingForResponse() {
Alexander Timin5fdeff22020-09-08 09:20:374184 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetNotWaitingForResponse",
4185 "was_waiting_for_response", waiting_for_response_);
Evan Stade5e750ad02017-08-07 21:59:274186 if (waiting_for_response_ == false)
4187 return;
4188
4189 waiting_for_response_ = false;
Alexander Timin90c20c32020-08-12 15:28:324190 observers_.ForEachObserver(
4191 [&](WebContentsObserver* observer) { observer->DidReceiveResponse(); });
Bruce Dawsone1c5c842020-09-15 02:09:144192
4193 // LoadingStateChanged must be called last in case it triggers deletion of
4194 // |this| due to recursive message pumps.
4195 if (delegate_)
4196 delegate_->LoadingStateChanged(this, is_load_to_different_document_);
Evan Stade5e750ad02017-08-07 21:59:274197}
4198
lfgbb9c28a2016-03-01 03:19:494199void WebContentsImpl::SendScreenRects() {
Alexander Timin5fdeff22020-09-08 09:20:374200 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SendScreenRects");
kenrbc52e1b4e2016-03-20 01:03:374201 for (FrameTreeNode* node : frame_tree_.Nodes()) {
kenrb0e8dc202016-05-30 19:51:404202 if (node->current_frame_host()->is_local_root())
kenrbc52e1b4e2016-03-20 01:03:374203 node->current_frame_host()->GetRenderWidgetHost()->SendScreenRects();
4204 }
[email protected]32deec62013-05-15 23:55:044205}
4206
ekaramadadd882292016-06-08 15:22:564207TextInputManager* WebContentsImpl::GetTextInputManager() {
4208 if (GetOuterWebContents())
4209 return GetOuterWebContents()->GetTextInputManager();
4210
Ehsan Karamadc179dc02018-12-15 03:09:294211 if (!text_input_manager_ && !browser_plugin_guest_) {
Fergal Daly55b6d722020-09-11 07:56:334212 text_input_manager_ = std::make_unique<TextInputManager>(
Darren Shenca53d5f2018-05-15 04:56:014213 GetBrowserContext() &&
Fergal Daly55b6d722020-09-11 07:56:334214 !GetBrowserContext()->IsOffTheRecord() /* should_do_learning */);
Darren Shenca53d5f2018-05-15 04:56:014215 }
ekaramadadd882292016-06-08 15:22:564216
4217 return text_input_manager_.get();
4218}
4219
paulmeyer7f6f1d4f2016-11-15 00:00:274220bool WebContentsImpl::OnUpdateDragCursor() {
Alexander Timin5fdeff22020-09-08 09:20:374221 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnUpdateDragCursor");
Lei Zhang6410ec1a2019-01-31 21:38:584222 return browser_plugin_embedder_ &&
4223 browser_plugin_embedder_->OnUpdateDragCursor();
paulmeyer7f6f1d4f2016-11-15 00:00:274224}
4225
kenrb11f213a2017-03-24 18:12:064226bool WebContentsImpl::IsWidgetForMainFrame(
4227 RenderWidgetHostImpl* render_widget_host) {
4228 return render_widget_host == GetMainFrame()->GetRenderWidgetHost();
4229}
4230
[email protected]95640212014-07-26 18:14:304231BrowserAccessibilityManager*
Alexander Timin5fdeff22020-09-08 09:20:374232WebContentsImpl::GetRootBrowserAccessibilityManager() {
Carlos ILd51e7702020-05-07 18:51:394233 RenderFrameHostImpl* rfh = static_cast<RenderFrameHostImpl*>(GetMainFrame());
creisc014b402015-04-23 16:41:454234 return rfh ? rfh->browser_accessibility_manager() : nullptr;
[email protected]95640212014-07-26 18:14:304235}
4236
4237BrowserAccessibilityManager*
Alexander Timin5fdeff22020-09-08 09:20:374238WebContentsImpl::GetOrCreateRootBrowserAccessibilityManager() {
Carlos ILd51e7702020-05-07 18:51:394239 RenderFrameHostImpl* rfh = static_cast<RenderFrameHostImpl*>(GetMainFrame());
creisc014b402015-04-23 16:41:454240 return rfh ? rfh->GetOrCreateBrowserAccessibilityManager() : nullptr;
[email protected]95640212014-07-26 18:14:304241}
4242
Dave Tapuskab336b922017-07-06 19:24:054243void WebContentsImpl::ExecuteEditCommand(
4244 const std::string& command,
4245 const base::Optional<base::string16>& value) {
Alexander Timin5fdeff22020-09-08 09:20:374246 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ExecuteEditCommand");
Dave Tapuska58a099e2020-06-08 21:48:404247 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514248 if (!input_handler)
Dave Tapuskab336b922017-07-06 19:24:054249 return;
4250
Dave Tapuskae782bea2019-07-09 16:21:514251 input_handler->ExecuteEditCommand(command, value);
Dave Tapuskab336b922017-07-06 19:24:054252}
4253
mohsen7ab1ec16ec2015-07-02 18:26:234254void WebContentsImpl::MoveRangeSelectionExtent(const gfx::Point& extent) {
Alexander Timin5fdeff22020-09-08 09:20:374255 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MoveRangeSelectionExtent");
Dave Tapuska58a099e2020-06-08 21:48:404256 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514257 if (!input_handler)
mohsen7ab1ec16ec2015-07-02 18:26:234258 return;
4259
Dave Tapuskae782bea2019-07-09 16:21:514260 input_handler->MoveRangeSelectionExtent(extent);
mohsen7ab1ec16ec2015-07-02 18:26:234261}
4262
4263void WebContentsImpl::SelectRange(const gfx::Point& base,
4264 const gfx::Point& extent) {
Alexander Timin5fdeff22020-09-08 09:20:374265 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SelectRange");
Dave Tapuska58a099e2020-06-08 21:48:404266 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514267 if (!input_handler)
mohsen7ab1ec16ec2015-07-02 18:26:234268 return;
4269
Dave Tapuskae782bea2019-07-09 16:21:514270 input_handler->SelectRange(base, extent);
mohsen7ab1ec16ec2015-07-02 18:26:234271}
4272
Dave Tapuskab336b922017-07-06 19:24:054273void WebContentsImpl::MoveCaret(const gfx::Point& extent) {
Alexander Timin5fdeff22020-09-08 09:20:374274 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
4275 "WebContentsImpl::MoveCaret");
Dave Tapuska58a099e2020-06-08 21:48:404276 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514277 if (!input_handler)
Dave Tapuskab336b922017-07-06 19:24:054278 return;
4279
Dave Tapuskae782bea2019-07-09 16:21:514280 input_handler->MoveCaret(extent);
Dave Tapuskab336b922017-07-06 19:24:054281}
4282
Shimi Zhang37deeb22017-09-28 00:59:014283void WebContentsImpl::AdjustSelectionByCharacterOffset(
4284 int start_adjust,
4285 int end_adjust,
4286 bool show_selection_menu) {
Alexander Timin5fdeff22020-09-08 09:20:374287 OPTIONAL_TRACE_EVENT0("content",
4288 "WebContentsImpl::AdjustSelectionByCharacterOffset");
Dave Tapuska58a099e2020-06-08 21:48:404289 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514290 if (!input_handler)
aurimasab0319022015-07-10 21:57:384291 return;
4292
Shimi Zhang37deeb22017-09-28 00:59:014293 using blink::mojom::SelectionMenuBehavior;
Dave Tapuskae782bea2019-07-09 16:21:514294 input_handler->AdjustSelectionByCharacterOffset(
Shimi Zhang37deeb22017-09-28 00:59:014295 start_adjust, end_adjust,
4296 show_selection_menu ? SelectionMenuBehavior::kShow
4297 : SelectionMenuBehavior::kHide);
aurimasab0319022015-07-10 21:57:384298}
4299
[email protected]b172aee2012-04-10 17:05:264300void WebContentsImpl::UpdatePreferredSize(const gfx::Size& pref_size) {
Alexander Timin5fdeff22020-09-08 09:20:374301 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::UpdatePreferredSize");
[email protected]222f5822014-02-05 23:40:494302 const gfx::Size old_size = GetPreferredSize();
[email protected]bcd2815602012-01-14 18:17:234303 preferred_size_ = pref_size;
[email protected]222f5822014-02-05 23:40:494304 OnPreferredSizeChanged(old_size);
[email protected]0548c5352011-09-07 00:33:334305}
4306
avic3aa8422015-11-09 20:57:224307void WebContentsImpl::ResizeDueToAutoResize(
4308 RenderWidgetHostImpl* render_widget_host,
Fady Samuel97947112018-05-05 16:24:544309 const gfx::Size& new_size) {
Alexander Timin5fdeff22020-09-08 09:20:374310 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ResizeDueToAutoResize",
4311 "render_widget_host", render_widget_host);
avic3aa8422015-11-09 20:57:224312 if (render_widget_host != GetRenderViewHost()->GetWidget())
4313 return;
4314
[email protected]61e2b3cc2012-03-02 16:13:344315 if (delegate_)
4316 delegate_->ResizeDueToAutoResize(this, new_size);
4317}
4318
[email protected]b172aee2012-04-10 17:05:264319WebContents* WebContentsImpl::OpenURL(const OpenURLParams& params) {
Alexander Timin5fdeff22020-09-08 09:20:374320 TRACE_EVENT1("content", "WebContentsImpl::OpenURL", "url",
4321 base::trace_event::ValueToString(params.url));
Aaron Colwell9dab1652019-12-09 18:29:494322#if DCHECK_IS_ON()
4323 DCHECK(params.Valid());
4324#endif
4325
Bo Liu300c6052018-06-12 04:46:074326 if (!delegate_) {
4327 // Embedder can delay setting a delegate on new WebContents with
4328 // WebContentsDelegate::ShouldResumeRequestsForCreatedWindow. In the mean
4329 // time, navigations, including the initial one, that goes through OpenURL
4330 // should be delayed until embedder is ready to resume loading.
4331 delayed_open_url_params_ = std::make_unique<OpenURLParams>(params);
Nasko Oskov83a8cf92018-10-19 14:58:564332
4333 // If there was a navigation deferred when creating the window through
4334 // CreateNewWindow, drop it in favor of this navigation.
4335 delayed_load_url_params_.reset();
4336
Ivan Kotenkov2c0d2bb32017-11-01 15:41:284337 return nullptr;
Bo Liu300c6052018-06-12 04:46:074338 }
[email protected]00c37fc2011-08-02 00:22:504339
[email protected]e5d549d2011-12-28 01:29:204340 WebContents* new_contents = delegate_->OpenURLFromTab(this, params);
pnoland488944652017-02-22 18:58:544341
4342 RenderFrameHost* source_render_frame_host = RenderFrameHost::FromID(
4343 params.source_render_process_id, params.source_render_frame_id);
4344
4345 if (source_render_frame_host && params.source_site_instance) {
4346 CHECK_EQ(source_render_frame_host->GetSiteInstance(),
4347 params.source_site_instance.get());
4348 }
4349
4350 if (new_contents && source_render_frame_host && new_contents != this) {
Alexander Timin90c20c32020-08-12 15:28:324351 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4352 observer->DidOpenRequestedURL(
Lukasz Anforowicz48c9f872018-08-01 00:58:414353 new_contents, source_render_frame_host, params.url, params.referrer,
4354 params.disposition, params.transition,
4355 params.started_from_context_menu, params.is_renderer_initiated);
Alexander Timin90c20c32020-08-12 15:28:324356 });
pnoland488944652017-02-22 18:58:544357 }
4358
[email protected]e5d549d2011-12-28 01:29:204359 return new_contents;
[email protected]d5f942ba2008-09-26 19:30:344360}
4361
avi2b177592014-12-10 02:08:024362void WebContentsImpl::SetHistoryOffsetAndLength(int history_offset,
4363 int history_length) {
Alexander Timin5fdeff22020-09-08 09:20:374364 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetHistoryOffsetAndLength",
4365 "history_offset", history_offset, "history_length",
4366 history_length);
alexmos136fd6e62016-08-15 20:58:414367 SendPageMessage(new PageMsg_SetHistoryOffsetAndLength(
4368 MSG_ROUTING_NONE, history_offset, history_length));
avi2b177592014-12-10 02:08:024369}
4370
4371void WebContentsImpl::SetHistoryOffsetAndLengthForView(
4372 RenderViewHost* render_view_host,
4373 int history_offset,
4374 int history_length) {
Alexander Timin5fdeff22020-09-08 09:20:374375 OPTIONAL_TRACE_EVENT2(
4376 "content", "WebContentsImpl::SetHistoryOffsetAndLengthForView",
4377 "history_offset", history_offset, "history_length", history_length);
alexmos136fd6e62016-08-15 20:58:414378 render_view_host->Send(new PageMsg_SetHistoryOffsetAndLength(
avi2b177592014-12-10 02:08:024379 render_view_host->GetRoutingID(), history_offset, history_length));
[email protected]796931a92011-08-10 01:32:144380}
4381
arthursonzogni818c2642019-09-27 12:18:104382void WebContentsImpl::ReloadFocusedFrame() {
Alexander Timin5fdeff22020-09-08 09:20:374383 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ReloadFocusedFrame");
[email protected]1f3fc1d2014-04-03 14:50:174384 RenderFrameHost* focused_frame = GetFocusedFrame();
4385 if (!focused_frame)
4386 return;
4387
yilkal921048bd2019-10-09 23:51:044388 focused_frame->Reload();
[email protected]959be4c2014-04-08 15:01:334389}
4390
4391void WebContentsImpl::Undo() {
Alexander Timin5fdeff22020-09-08 09:20:374392 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Undo");
Dave Tapuska58a099e2020-06-08 21:48:404393 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514394 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334395 return;
4396
Dave Tapuskae782bea2019-07-09 16:21:514397 input_handler->Undo();
[email protected]959be4c2014-04-08 15:01:334398 RecordAction(base::UserMetricsAction("Undo"));
4399}
4400
4401void WebContentsImpl::Redo() {
Alexander Timin5fdeff22020-09-08 09:20:374402 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Redo");
Dave Tapuska58a099e2020-06-08 21:48:404403 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514404 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334405 return;
Dave Tapuskae782bea2019-07-09 16:21:514406
4407 input_handler->Redo();
[email protected]959be4c2014-04-08 15:01:334408 RecordAction(base::UserMetricsAction("Redo"));
4409}
4410
4411void WebContentsImpl::Cut() {
Alexander Timin5fdeff22020-09-08 09:20:374412 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Cut");
Dave Tapuska58a099e2020-06-08 21:48:404413 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514414 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334415 return;
4416
Dave Tapuskae782bea2019-07-09 16:21:514417 input_handler->Cut();
[email protected]959be4c2014-04-08 15:01:334418 RecordAction(base::UserMetricsAction("Cut"));
4419}
4420
4421void WebContentsImpl::Copy() {
Alexander Timin5fdeff22020-09-08 09:20:374422 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Copy");
Dave Tapuska58a099e2020-06-08 21:48:404423 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514424 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334425 return;
4426
Dave Tapuskae782bea2019-07-09 16:21:514427 input_handler->Copy();
[email protected]959be4c2014-04-08 15:01:334428 RecordAction(base::UserMetricsAction("Copy"));
4429}
4430
4431void WebContentsImpl::CopyToFindPboard() {
Alexander Timin5fdeff22020-09-08 09:20:374432 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::CopyToFindPboard");
Avi Drissman7c57be72020-07-29 20:09:464433#if defined(OS_MAC)
Dave Tapuska58a099e2020-06-08 21:48:404434 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514435 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334436 return;
4437
4438 // Windows/Linux don't have the concept of a find pasteboard.
Dave Tapuskae782bea2019-07-09 16:21:514439 input_handler->CopyToFindPboard();
[email protected]959be4c2014-04-08 15:01:334440 RecordAction(base::UserMetricsAction("CopyToFindPboard"));
4441#endif
4442}
4443
4444void WebContentsImpl::Paste() {
Alexander Timin5fdeff22020-09-08 09:20:374445 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Paste");
Dave Tapuska58a099e2020-06-08 21:48:404446 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514447 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334448 return;
4449
Dave Tapuskae782bea2019-07-09 16:21:514450 input_handler->Paste();
Alexander Timin90c20c32020-08-12 15:28:324451 observers_.ForEachObserver(
4452 [&](WebContentsObserver* observer) { observer->OnPaste(); });
[email protected]959be4c2014-04-08 15:01:334453 RecordAction(base::UserMetricsAction("Paste"));
4454}
4455
4456void WebContentsImpl::PasteAndMatchStyle() {
Alexander Timin5fdeff22020-09-08 09:20:374457 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::PasteAndMatchStyle");
Dave Tapuska58a099e2020-06-08 21:48:404458 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514459 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334460 return;
4461
Dave Tapuskae782bea2019-07-09 16:21:514462 input_handler->PasteAndMatchStyle();
Alexander Timin90c20c32020-08-12 15:28:324463 observers_.ForEachObserver(
4464 [&](WebContentsObserver* observer) { observer->OnPaste(); });
[email protected]959be4c2014-04-08 15:01:334465 RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
4466}
4467
4468void WebContentsImpl::Delete() {
Alexander Timin5fdeff22020-09-08 09:20:374469 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Delete");
Dave Tapuska58a099e2020-06-08 21:48:404470 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514471 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334472 return;
4473
Dave Tapuskae782bea2019-07-09 16:21:514474 input_handler->Delete();
[email protected]959be4c2014-04-08 15:01:334475 RecordAction(base::UserMetricsAction("DeleteSelection"));
4476}
4477
4478void WebContentsImpl::SelectAll() {
Alexander Timin5fdeff22020-09-08 09:20:374479 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SelectAll");
Dave Tapuska58a099e2020-06-08 21:48:404480 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514481 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334482 return;
4483
Dave Tapuskae782bea2019-07-09 16:21:514484 input_handler->SelectAll();
[email protected]959be4c2014-04-08 15:01:334485 RecordAction(base::UserMetricsAction("SelectAll"));
4486}
4487
yabinh351e7ec2017-03-10 02:43:244488void WebContentsImpl::CollapseSelection() {
Alexander Timin5fdeff22020-09-08 09:20:374489 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::CollapseSelection");
Dave Tapuska58a099e2020-06-08 21:48:404490 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514491 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334492 return;
4493
Dave Tapuskae782bea2019-07-09 16:21:514494 input_handler->CollapseSelection();
[email protected]1f3fc1d2014-04-03 14:50:174495}
4496
4497void WebContentsImpl::Replace(const base::string16& word) {
Alexander Timin5fdeff22020-09-08 09:20:374498 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Replace");
Dave Tapuska58a099e2020-06-08 21:48:404499 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514500 if (!input_handler)
[email protected]1f3fc1d2014-04-03 14:50:174501 return;
4502
Dave Tapuskae782bea2019-07-09 16:21:514503 input_handler->Replace(word);
[email protected]1f3fc1d2014-04-03 14:50:174504}
4505
4506void WebContentsImpl::ReplaceMisspelling(const base::string16& word) {
Alexander Timin5fdeff22020-09-08 09:20:374507 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ReplaceMisspelling");
Dave Tapuska58a099e2020-06-08 21:48:404508 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514509 if (!input_handler)
[email protected]1f3fc1d2014-04-03 14:50:174510 return;
4511
Dave Tapuskae782bea2019-07-09 16:21:514512 input_handler->ReplaceMisspelling(word);
[email protected]959be4c2014-04-08 15:01:334513}
4514
4515void WebContentsImpl::NotifyContextMenuClosed(
4516 const CustomContextMenuContext& context) {
Alexander Timin5fdeff22020-09-08 09:20:374517 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::NotifyContextMenuClosed");
[email protected]959be4c2014-04-08 15:01:334518 RenderFrameHost* focused_frame = GetFocusedFrame();
4519 if (!focused_frame)
4520 return;
4521
4522 focused_frame->Send(new FrameMsg_ContextMenuClosed(
4523 focused_frame->GetRoutingID(), context));
4524}
4525
4526void WebContentsImpl::ExecuteCustomContextMenuCommand(
4527 int action, const CustomContextMenuContext& context) {
Alexander Timin5fdeff22020-09-08 09:20:374528 OPTIONAL_TRACE_EVENT1("content",
4529 "WebContentsImpl::ExecuteCustomContextMenuCommand",
4530 "action", action);
[email protected]959be4c2014-04-08 15:01:334531 RenderFrameHost* focused_frame = GetFocusedFrame();
4532 if (!focused_frame)
4533 return;
4534
4535 focused_frame->Send(new FrameMsg_CustomContextMenuAction(
4536 focused_frame->GetRoutingID(), context, action));
[email protected]4fed3702014-04-01 09:08:004537}
4538
[email protected]fc2b46b2014-05-03 16:33:454539gfx::NativeView WebContentsImpl::GetNativeView() {
4540 return view_->GetNativeView();
4541}
4542
4543gfx::NativeView WebContentsImpl::GetContentNativeView() {
4544 return view_->GetContentNativeView();
4545}
4546
4547gfx::NativeWindow WebContentsImpl::GetTopLevelNativeWindow() {
4548 return view_->GetTopLevelNativeWindow();
4549}
4550
4551gfx::Rect WebContentsImpl::GetViewBounds() {
4552 return view_->GetViewBounds();
4553}
4554
4555gfx::Rect WebContentsImpl::GetContainerBounds() {
Jeremy Roman352239c2020-05-21 16:31:324556 return view_->GetContainerBounds();
[email protected]fc2b46b2014-05-03 16:33:454557}
4558
4559DropData* WebContentsImpl::GetDropData() {
4560 return view_->GetDropData();
4561}
4562
4563void WebContentsImpl::Focus() {
Alexander Timin5fdeff22020-09-08 09:20:374564 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Focus");
miu9e14e492014-10-25 02:39:044565 view_->Focus();
[email protected]fc2b46b2014-05-03 16:33:454566}
4567
4568void WebContentsImpl::SetInitialFocus() {
Alexander Timin5fdeff22020-09-08 09:20:374569 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetInitialFocus");
miu9e14e492014-10-25 02:39:044570 view_->SetInitialFocus();
[email protected]fc2b46b2014-05-03 16:33:454571}
4572
4573void WebContentsImpl::StoreFocus() {
Alexander Timin5fdeff22020-09-08 09:20:374574 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::StoreFocus");
miu9e14e492014-10-25 02:39:044575 view_->StoreFocus();
[email protected]fc2b46b2014-05-03 16:33:454576}
4577
4578void WebContentsImpl::RestoreFocus() {
Alexander Timin5fdeff22020-09-08 09:20:374579 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::RestoreFocus");
miu9e14e492014-10-25 02:39:044580 view_->RestoreFocus();
[email protected]fc2b46b2014-05-03 16:33:454581}
4582
[email protected]b172aee2012-04-10 17:05:264583void WebContentsImpl::FocusThroughTabTraversal(bool reverse) {
Alexander Timin5fdeff22020-09-08 09:20:374584 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::FocusThroughTabTraversal",
4585 "reverse", reverse);
Maxim Podgorodskiya926c4ff2017-11-20 02:06:394586 view_->FocusThroughTabTraversal(reverse);
[email protected]96d185d2009-04-24 03:28:544587}
4588
[email protected]b172aee2012-04-10 17:05:264589bool WebContentsImpl::IsSavable() {
[email protected]a53209b2012-01-20 16:48:164590 // WebKit creates Document object when MIME type is application/xhtml+xml,
4591 // so we also support this MIME type.
Yuzu Saijoc23e9b72020-06-25 07:21:274592 std::string mime_type = GetContentsMimeType();
4593 return mime_type == "text/html" || mime_type == "text/xml" ||
4594 mime_type == "application/xhtml+xml" || mime_type == "text/plain" ||
4595 mime_type == "text/css" ||
4596 blink::IsSupportedJavascriptMimeType(mime_type);
[email protected]a53209b2012-01-20 16:48:164597}
4598
[email protected]b172aee2012-04-10 17:05:264599void WebContentsImpl::OnSavePage() {
Alexander Timin5fdeff22020-09-08 09:20:374600 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnSavePage");
[email protected]c7dd2f62011-07-18 15:57:594601 // If we can not save the page, try to download it.
[email protected]a53209b2012-01-20 16:48:164602 if (!IsSavable()) {
Min Qinda0ed2062018-02-23 22:00:534603 download::RecordSavePackageEvent(
4604 download::SAVE_PACKAGE_DOWNLOAD_ON_NON_HTML);
nasko89ad7742015-03-05 22:14:194605 SaveFrame(GetLastCommittedURL(), Referrer());
[email protected]27678b2a2012-02-04 22:09:144606 return;
[email protected]c7dd2f62011-07-18 15:57:594607 }
4608
4609 Stop();
4610
4611 // Create the save package and possibly prompt the user for the name to save
4612 // the page as. The user prompt is an asynchronous operation that runs on
4613 // another thread.
4614 save_package_ = new SavePackage(this);
4615 save_package_->GetSaveInfo();
4616}
4617
4618// Used in automated testing to bypass prompting the user for file names.
4619// Instead, the names and paths are hard coded rather than running them through
4620// file name sanitation and extension / mime checking.
[email protected]2dec8ec2013-02-07 19:20:344621bool WebContentsImpl::SavePage(const base::FilePath& main_file,
4622 const base::FilePath& dir_path,
[email protected]8ff00d72012-10-23 19:12:214623 SavePageType save_type) {
Alexander Timin5fdeff22020-09-08 09:20:374624 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SavePage", "main_file",
4625 base::trace_event::ValueToString(main_file), "dir_path",
4626 base::trace_event::ValueToString(dir_path));
[email protected]c7dd2f62011-07-18 15:57:594627 // Stop the page from navigating.
4628 Stop();
4629
4630 save_package_ = new SavePackage(this, save_type, main_file, dir_path);
[email protected]8ff00d72012-10-23 19:12:214631 return save_package_->Init(SavePackageDownloadCreatedCallback());
[email protected]c7dd2f62011-07-18 15:57:594632}
4633
Alexander Timin5fdeff22020-09-08 09:20:374634void WebContentsImpl::SaveFrame(const GURL& url, const Referrer& referrer) {
4635 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SaveFrame");
Xing Liu10329bf2018-03-20 19:22:144636 SaveFrameWithHeaders(url, referrer, std::string(), base::string16());
kundaji6c7f9692015-03-09 18:00:374637}
4638
Xing Liu10329bf2018-03-20 19:22:144639void WebContentsImpl::SaveFrameWithHeaders(
4640 const GURL& url,
4641 const Referrer& referrer,
4642 const std::string& headers,
4643 const base::string16& suggested_filename) {
Alexander Timin5fdeff22020-09-08 09:20:374644 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SaveFrameWithHeaders",
4645 "url", base::trace_event::ValueToString(url), "headers",
4646 headers);
Lei Zhang13a42e42019-02-19 23:28:114647 // Check and see if the guest can handle this.
4648 if (delegate_) {
4649 WebContents* guest_web_contents = nullptr;
4650 if (browser_plugin_embedder_) {
4651 BrowserPluginGuest* guest = browser_plugin_embedder_->GetFullPageGuest();
4652 if (guest)
4653 guest_web_contents = guest->GetWebContents();
4654 } else if (browser_plugin_guest_) {
4655 guest_web_contents = this;
4656 }
4657
4658 if (guest_web_contents && delegate_->GuestSaveFrame(guest_web_contents))
4659 return;
4660 }
4661
nasko89ad7742015-03-05 22:14:194662 if (!GetLastCommittedURL().is_valid())
[email protected]3c71576ce2013-07-23 02:00:014663 return;
sammc92af61552014-11-19 23:27:404664 if (delegate_ && delegate_->SaveFrame(url, referrer))
4665 return;
4666
nasko89ad7742015-03-05 22:14:194667 // TODO(nasko): This check for main frame is incorrect and should be fixed
brettw760f7442016-05-23 21:19:224668 // by explicitly passing in which frame this method should target. This would
4669 // indicate whether it's the main frame, and also tell us the frame pointer
4670 // to use for routing.
nasko89ad7742015-03-05 22:14:194671 bool is_main_frame = (url == GetLastCommittedURL());
brettw760f7442016-05-23 21:19:224672 RenderFrameHost* frame_host = GetMainFrame();
[email protected]3c71576ce2013-07-23 02:00:014673
avib7348942015-12-25 20:57:104674 int64_t post_id = -1;
[email protected]3c71576ce2013-07-23 02:00:014675 if (is_main_frame) {
Lucas Furukawa Gadani5553a152019-01-08 18:55:574676 NavigationEntry* entry = controller_.GetLastCommittedEntry();
[email protected]3c71576ce2013-07-23 02:00:014677 if (entry)
4678 post_id = entry->GetPostID();
4679 }
Ramin Halavati24e21012017-07-10 12:56:064680 net::NetworkTrafficAnnotationTag traffic_annotation =
4681 net::DefineNetworkTrafficAnnotation("download_web_contents_frame", R"(
4682 semantics {
4683 sender: "Save Page Action"
4684 description:
4685 "Saves the given frame's URL to the local file system."
4686 trigger:
4687 "The user has triggered a save operation on the frame through a "
4688 "context menu or other mechanism."
4689 data: "None."
4690 destination: WEBSITE
4691 }
4692 policy {
Ramin Halavati3b979782017-07-21 11:40:264693 cookies_allowed: YES
Ramin Halavati24e21012017-07-10 12:56:064694 cookies_store: "user"
4695 setting:
4696 "This feature cannot be disabled by settings, but it's is only "
4697 "triggered by user request."
4698 policy_exception_justification: "Not implemented."
4699 })");
Min Qina904f3302018-02-13 23:33:344700 auto params = std::make_unique<download::DownloadUrlParameters>(
brettw760f7442016-05-23 21:19:224701 url, frame_host->GetProcess()->GetID(),
4702 frame_host->GetRenderViewHost()->GetRoutingID(),
Matt Menke0dcaebc32020-03-06 17:00:104703 frame_host->GetRoutingID(), traffic_annotation);
Min Qina904f3302018-02-13 23:33:344704 params->set_referrer(referrer.url);
4705 params->set_referrer_policy(
4706 Referrer::ReferrerPolicyForUrlRequest(referrer.policy));
[email protected]3c71576ce2013-07-23 02:00:014707 params->set_post_id(post_id);
[email protected]3c71576ce2013-07-23 02:00:014708 if (post_id >= 0)
4709 params->set_method("POST");
4710 params->set_prompt(true);
kundaji6c7f9692015-03-09 18:00:374711
4712 if (headers.empty()) {
4713 params->set_prefer_cache(true);
4714 } else {
Min Qina904f3302018-02-13 23:33:344715 for (download::DownloadUrlParameters::RequestHeadersNameValuePair
4716 key_value : ParseDownloadHeaders(headers)) {
Megan Jablonski2f6a4c52017-07-10 23:01:254717 params->add_request_header(key_value.first, key_value.second);
kundaji6c7f9692015-03-09 18:00:374718 }
4719 }
Xing Liu10329bf2018-03-20 19:22:144720 params->set_suggested_name(suggested_filename);
Min Qin0ca8e1ee2018-01-31 00:49:354721 params->set_download_source(download::DownloadSource::WEB_CONTENTS_API);
thestig859c78892017-05-15 21:17:064722 BrowserContext::GetDownloadManager(GetBrowserContext())
Ramin Halavati03efa732017-06-12 09:28:204723 ->DownloadUrl(std::move(params));
[email protected]3c71576ce2013-07-23 02:00:014724}
4725
[email protected]b172aee2012-04-10 17:05:264726void WebContentsImpl::GenerateMHTML(
dewittj6dc5747a2016-05-17 01:48:474727 const MHTMLGenerationParams& params,
Avi Drissman149b7832018-03-23 14:31:494728 base::OnceCallback<void(int64_t)> callback) {
Alexander Timin5fdeff22020-09-08 09:20:374729 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GenerateMHTML");
Angel Alvarez902496682019-08-27 22:58:424730 base::OnceCallback<void(const MHTMLGenerationResult&)> wrapper_callback =
4731 base::BindOnce(
4732 [](base::OnceCallback<void(int64_t)> size_callback,
4733 const MHTMLGenerationResult& result) {
4734 std::move(size_callback).Run(result.file_size);
4735 },
4736 std::move(callback));
4737 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, params,
4738 std::move(wrapper_callback));
4739}
4740
4741void WebContentsImpl::GenerateMHTMLWithResult(
4742 const MHTMLGenerationParams& params,
4743 MHTMLGenerationResult::GenerateMHTMLCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:374744 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GenerateMHTMLWithResult");
Avi Drissman149b7832018-03-23 14:31:494745 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, params,
4746 std::move(callback));
[email protected]aa4f3972012-03-01 18:12:124747}
4748
Tsuyoshi Horob0d8d902020-03-12 00:09:394749void WebContentsImpl::GenerateWebBundle(
4750 const base::FilePath& file_path,
4751 base::OnceCallback<void(uint64_t /* file_size */,
4752 data_decoder::mojom::WebBundlerError)> callback) {
Alexander Timin5fdeff22020-09-08 09:20:374753 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::GenerateWebBundle",
4754 "file_path",
4755 base::trace_event::ValueToString(file_path));
Tsuyoshi Horob0d8d902020-03-12 00:09:394756 SaveAsWebBundleJob::Start(this, file_path, std::move(callback));
4757}
4758
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414759const std::string& WebContentsImpl::GetContentsMimeType() {
Yuzu Saijoc23e9b72020-06-25 07:21:274760 return GetRenderViewHost()->contents_mime_type();
[email protected]0bfbf882011-12-22 18:19:274761}
4762
Leon Hanc819dc62019-01-28 04:30:194763blink::mojom::RendererPreferences* WebContentsImpl::GetMutableRendererPrefs() {
[email protected]0bfbf882011-12-22 18:19:274764 return &renderer_preferences_;
4765}
4766
[email protected]e35ccd52012-05-23 16:22:474767void WebContentsImpl::Close() {
Alexander Timin5fdeff22020-09-08 09:20:374768 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Close");
[email protected]e35ccd52012-05-23 16:22:474769 Close(GetRenderViewHost());
4770}
4771
Ella Ge80a52dce2017-11-15 18:01:524772void WebContentsImpl::DragSourceEndedAt(float client_x,
4773 float client_y,
4774 float screen_x,
4775 float screen_y,
Gyuyoung Kimbad7da7c7d2020-09-25 16:26:594776 blink::DragOperation operation,
Paul Meyer0c58c3712016-11-17 22:59:514777 RenderWidgetHost* source_rwh) {
Alexander Timin5fdeff22020-09-08 09:20:374778 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
4779 "WebContentsImpl::DragSourceEndedAt");
Lei Zhang6410ec1a2019-01-31 21:38:584780 if (browser_plugin_embedder_) {
W. James MacLean9437b5bf2019-12-06 17:33:444781 browser_plugin_embedder_->DragSourceEndedAt(client_x, client_y, screen_x,
4782 screen_y, operation);
Lei Zhang6410ec1a2019-01-31 21:38:584783 }
Paul Meyer0c58c3712016-11-17 22:59:514784 if (source_rwh) {
Ella Ge80a52dce2017-11-15 18:01:524785 source_rwh->DragSourceEndedAt(gfx::PointF(client_x, client_y),
4786 gfx::PointF(screen_x, screen_y), operation);
Paul Meyer0c58c3712016-11-17 22:59:514787 }
[email protected]cf200a562013-05-03 16:24:294788}
4789
jam73f892642016-09-11 06:04:064790void WebContentsImpl::LoadStateChanged(
Charles Harrison911fa062018-03-06 21:01:464791 const std::string& host,
jam73f892642016-09-11 06:04:064792 const net::LoadStateWithParam& load_state,
4793 uint64_t upload_position,
4794 uint64_t upload_size) {
Alexander Timin5fdeff22020-09-08 09:20:374795 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::LoadStateChanged", "host",
4796 host, "load_state", static_cast<int>(load_state.state));
Charles Harrison911fa062018-03-06 21:01:464797 base::string16 host16 = url_formatter::IDNToUnicode(host);
Elly Fong-Jonescad9c3d12018-01-31 17:26:104798 // Drop no-op updates.
4799 if (load_state_.state == load_state.state &&
4800 load_state_.param == load_state.param &&
4801 upload_position_ == upload_position && upload_size_ == upload_size &&
Charles Harrison911fa062018-03-06 21:01:464802 load_state_host_ == host16) {
Elly Fong-Jonescad9c3d12018-01-31 17:26:104803 return;
4804 }
jam73f892642016-09-11 06:04:064805 load_state_ = load_state;
4806 upload_position_ = upload_position;
4807 upload_size_ = upload_size;
Charles Harrison911fa062018-03-06 21:01:464808 load_state_host_ = host16;
jam73f892642016-09-11 06:04:064809 if (load_state_.state == net::LOAD_STATE_READING_RESPONSE)
4810 SetNotWaitingForResponse();
jam73f892642016-09-11 06:04:064811}
4812
Collin Baker989e0882019-11-01 01:27:174813void WebContentsImpl::SetVisibilityAndNotifyObservers(Visibility visibility) {
Alexander Timin5fdeff22020-09-08 09:20:374814 OPTIONAL_TRACE_EVENT1("content",
4815 "WebContentsImpl::SetVisibilityAndNotifyObservers",
4816 "visibility", static_cast<int>(visibility));
Francois Doraye6161152018-03-27 22:05:374817 const Visibility previous_visibility = visibility_;
4818 visibility_ = visibility;
4819
Francois Dorayfe4a1772018-02-17 04:17:094820 // Notify observers if the visibility changed or if WasShown() is being called
4821 // for the first time.
Francois Dorayfe4a1772018-02-17 04:17:094822 if (visibility != previous_visibility ||
4823 (visibility == Visibility::VISIBLE && !did_first_set_visible_)) {
Alexander Timin90c20c32020-08-12 15:28:324824 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4825 observer->OnVisibilityChanged(visibility);
4826 });
Francois Dorayfe4a1772018-02-17 04:17:094827 }
4828}
4829
Michael Thiessen896405db2017-07-20 17:52:324830void WebContentsImpl::NotifyWebContentsFocused(
4831 RenderWidgetHost* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:374832 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::NotifyWebContentsFocused",
4833 "render_widget_host", render_widget_host);
Alexander Timin90c20c32020-08-12 15:28:324834 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4835 observer->OnWebContentsFocused(render_widget_host);
4836 });
calamity7fe55ce2015-04-10 03:59:374837}
4838
Michael Thiessen896405db2017-07-20 17:52:324839void WebContentsImpl::NotifyWebContentsLostFocus(
4840 RenderWidgetHost* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:374841 OPTIONAL_TRACE_EVENT1("content",
4842 "WebContentsImpl::NotifyWebContentsLostFocus",
4843 "render_widget_host", render_widget_host);
Alexander Timin90c20c32020-08-12 15:28:324844 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4845 observer->OnWebContentsLostFocus(render_widget_host);
4846 });
zijiehe3bee08e22017-05-17 04:14:464847}
4848
Paul Meyer0c58c3712016-11-17 22:59:514849void WebContentsImpl::SystemDragEnded(RenderWidgetHost* source_rwh) {
Alexander Timin5fdeff22020-09-08 09:20:374850 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SystemDragEnded",
4851 "render_widget_host", source_rwh);
Paul Meyer0c58c3712016-11-17 22:59:514852 if (source_rwh)
4853 source_rwh->DragSourceSystemDragEnded();
Lei Zhang6410ec1a2019-01-31 21:38:584854 if (browser_plugin_embedder_)
[email protected]cf200a562013-05-03 16:24:294855 browser_plugin_embedder_->SystemDragEnded();
[email protected]7813bd72011-02-05 02:19:344856}
4857
[email protected]b172aee2012-04-10 17:05:264858void WebContentsImpl::SetClosedByUserGesture(bool value) {
Alexander Timin5fdeff22020-09-08 09:20:374859 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetClosedByUserGesture",
4860 "value", value);
[email protected]0bfbf882011-12-22 18:19:274861 closed_by_user_gesture_ = value;
4862}
4863
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414864bool WebContentsImpl::GetClosedByUserGesture() {
[email protected]0bfbf882011-12-22 18:19:274865 return closed_by_user_gesture_;
4866}
4867
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414868int WebContentsImpl::GetMinimumZoomPercent() {
[email protected]0bfbf882011-12-22 18:19:274869 return minimum_zoom_percent_;
4870}
4871
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414872int WebContentsImpl::GetMaximumZoomPercent() {
[email protected]0bfbf882011-12-22 18:19:274873 return maximum_zoom_percent_;
4874}
4875
Dave Tapuska8f7c3872020-02-07 01:16:384876void WebContentsImpl::SetPageScale(float scale_factor) {
Alexander Timin5fdeff22020-09-08 09:20:374877 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetPageScale",
4878 "scale_factor", scale_factor);
Dave Tapuska8f7c3872020-02-07 01:16:384879 GetMainFrame()->GetAssociatedLocalMainFrame()->SetScaleFactor(scale_factor);
ccameronb7c1d6c2015-03-09 17:08:244880}
4881
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414882gfx::Size WebContentsImpl::GetPreferredSize() {
Francois Doray24fc62c2017-12-11 17:27:334883 return IsBeingCaptured() ? preferred_size_for_capture_ : preferred_size_;
[email protected]bcd2815602012-01-14 18:17:234884}
4885
James Hollyerd5c9de462020-03-10 19:02:454886bool WebContentsImpl::GotResponseToLockMouseRequest(
4887 blink::mojom::PointerLockResult result) {
Alexander Timin5fdeff22020-09-08 09:20:374888 OPTIONAL_TRACE_EVENT0("content",
4889 "WebContentsImpl::GotResponseToLockMouseRequest");
lfgf0cd46e2017-01-04 00:05:234890 if (mouse_lock_widget_) {
4891 if (mouse_lock_widget_->delegate()->GetAsWebContents() != this) {
4892 return mouse_lock_widget_->delegate()
4893 ->GetAsWebContents()
James Hollyerd5c9de462020-03-10 19:02:454894 ->GotResponseToLockMouseRequest(result);
lfgf0cd46e2017-01-04 00:05:234895 }
lfgad8244352016-07-13 16:55:514896
James Hollyerd5c9de462020-03-10 19:02:454897 if (mouse_lock_widget_->GotResponseToLockMouseRequest(result))
lfgf0cd46e2017-01-04 00:05:234898 return true;
4899 }
4900
4901 for (WebContentsImpl* current = this; current;
4902 current = current->GetOuterWebContents()) {
4903 current->mouse_lock_widget_ = nullptr;
4904 }
4905
lfgbee1e0a2016-06-08 21:24:214906 return false;
[email protected]0bfbf882011-12-22 18:19:274907}
4908
James Hollyerd5c9de462020-03-10 19:02:454909void WebContentsImpl::GotLockMousePermissionResponse(bool allowed) {
4910 GotResponseToLockMouseRequest(
4911 allowed ? blink::mojom::PointerLockResult::kSuccess
4912 : blink::mojom::PointerLockResult::kPermissionDenied);
4913}
4914
Dave Tapuskab4998782020-10-08 17:22:474915void WebContentsImpl::DropMouseLockForTesting() {
4916 if (mouse_lock_widget_) {
4917 mouse_lock_widget_->RejectMouseLockOrUnlockIfNecessary(
4918 blink::mojom::PointerLockResult::kUnknownError);
4919 for (WebContentsImpl* current = this; current;
4920 current = current->GetOuterWebContents()) {
4921 current->mouse_lock_widget_ = nullptr;
4922 }
4923 }
4924}
4925
Joe Downing13dd76b2018-04-09 18:32:154926bool WebContentsImpl::GotResponseToKeyboardLockRequest(bool allowed) {
Alexander Timin5fdeff22020-09-08 09:20:374927 OPTIONAL_TRACE_EVENT1("content",
4928 "WebContentsImpl::GotResponseToKeyboardLockRequest",
4929 "allowed", allowed);
4930
Joe Downing13dd76b2018-04-09 18:32:154931 if (!keyboard_lock_widget_)
4932 return false;
4933
4934 if (keyboard_lock_widget_->delegate()->GetAsWebContents() != this) {
4935 NOTREACHED();
4936 return false;
4937 }
4938
4939 // KeyboardLock is only supported when called by the top-level browsing
4940 // context and is not supported in embedded content scenarios.
4941 if (GetOuterWebContents())
4942 return false;
4943
4944 keyboard_lock_widget_->GotResponseToKeyboardLockRequest(allowed);
4945 return true;
4946}
4947
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414948bool WebContentsImpl::HasOpener() {
Ivan Kotenkov2c0d2bb32017-11-01 15:41:284949 return GetOpener() != nullptr;
[email protected]a0358d72012-03-09 14:06:504950}
4951
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414952RenderFrameHostImpl* WebContentsImpl::GetOpener() {
alexmose201c7cd2015-06-10 17:14:214953 FrameTreeNode* opener_ftn = frame_tree_.root()->opener();
lukasza6f8ac622017-06-06 03:10:204954 return opener_ftn ? opener_ftn->current_frame_host() : nullptr;
jochen55ff3502014-12-18 20:52:574955}
4956
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414957bool WebContentsImpl::HasOriginalOpener() {
Ivan Kotenkov2c0d2bb32017-11-01 15:41:284958 return GetOriginalOpener() != nullptr;
jochen6004a362017-02-04 00:11:404959}
4960
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414961RenderFrameHostImpl* WebContentsImpl::GetOriginalOpener() {
jochen6004a362017-02-04 00:11:404962 FrameTreeNode* opener_ftn = frame_tree_.root()->original_opener();
lukasza6f8ac622017-06-06 03:10:204963 return opener_ftn ? opener_ftn->current_frame_host() : nullptr;
jochen6004a362017-02-04 00:11:404964}
4965
[email protected]cb805452013-05-22 15:16:214966void WebContentsImpl::DidChooseColorInColorChooser(SkColor color) {
Alexander Timin5fdeff22020-09-08 09:20:374967 OPTIONAL_TRACE_EVENT1("content",
4968 "WebContentsImpl::DidChooseColorInColorChooser",
4969 "color", color);
Joel Hockey85b379d2017-12-11 10:42:134970 color_chooser_->DidChooseColorInColorChooser(color);
[email protected]da8543762012-03-20 08:52:204971}
4972
[email protected]cb805452013-05-22 15:16:214973void WebContentsImpl::DidEndColorChooser() {
Alexander Timin5fdeff22020-09-08 09:20:374974 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidEndColorChooser");
Joel Hockey85b379d2017-12-11 10:42:134975 color_chooser_.reset();
[email protected]da8543762012-03-20 08:52:204976}
4977
halton.huoca2eabd2015-07-06 08:17:404978int WebContentsImpl::DownloadImage(
4979 const GURL& url,
4980 bool is_favicon,
Fredrik Söderquistb2b39eb92019-11-18 16:16:504981 uint32_t preferred_size,
halton.huoca2eabd2015-07-06 08:17:404982 uint32_t max_bitmap_size,
4983 bool bypass_cache,
Avi Drissmana5a52dd2018-03-27 03:39:024984 WebContents::ImageDownloadCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:374985 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DownloadImage", "url",
4986 base::trace_event::ValueToString(url));
Danyao Wanga78f3dd22020-03-05 05:31:274987 return DownloadImageInFrame(GlobalFrameRoutingId(), url, is_favicon,
4988 preferred_size, max_bitmap_size, bypass_cache,
4989 std::move(callback));
4990}
4991
4992int WebContentsImpl::DownloadImageInFrame(
4993 const GlobalFrameRoutingId& initiator_frame_routing_id,
4994 const GURL& url,
4995 bool is_favicon,
4996 uint32_t preferred_size,
4997 uint32_t max_bitmap_size,
4998 bool bypass_cache,
4999 WebContents::ImageDownloadCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:375000 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DownloadImageInFrame");
amistry9f01b772015-07-29 01:54:555001 DCHECK_CURRENTLY_ON(BrowserThread::UI);
halton.huoca2eabd2015-07-06 08:17:405002 static int next_image_download_id = 0;
Danyao Wanga78f3dd22020-03-05 05:31:275003
5004 RenderFrameHostImpl* initiator_frame =
5005 initiator_frame_routing_id.child_id
5006 ? RenderFrameHostImpl::FromID(initiator_frame_routing_id)
5007 : GetMainFrame();
Julie Jeongeun Kimb1473572019-08-15 05:59:135008 const mojo::Remote<blink::mojom::ImageDownloader>& mojo_image_downloader =
Danyao Wanga78f3dd22020-03-05 05:31:275009 initiator_frame->GetMojoImageDownloader();
amistry9f01b772015-07-29 01:54:555010 const int download_id = ++next_image_download_id;
5011 if (!mojo_image_downloader) {
5012 // If the renderer process is dead (i.e. crash, or memory pressure on
5013 // Android), the downloader service will be invalid. Pre-Mojo, this would
Avi Drissmana5a52dd2018-03-27 03:39:025014 // hang the callback indefinitely since the IPC would be dropped. Now,
amistry9f01b772015-07-29 01:54:555015 // respond with a 400 HTTP error code to indicate that something went wrong.
Gabriel Charettee7cdc5cd2020-05-27 23:35:055016 GetUIThreadTaskRunner({})->PostTask(
5017 FROM_HERE,
tzike2aca992017-09-05 08:50:545018 base::BindOnce(&WebContentsImpl::OnDidDownloadImage,
Avi Drissmana5a52dd2018-03-27 03:39:025019 weak_factory_.GetWeakPtr(), std::move(callback),
5020 download_id, url, 400, std::vector<SkBitmap>(),
5021 std::vector<gfx::Size>()));
amistry9f01b772015-07-29 01:54:555022 return download_id;
5023 }
5024
halton.huoca2eabd2015-07-06 08:17:405025 mojo_image_downloader->DownloadImage(
Fredrik Söderquistb2b39eb92019-11-18 16:16:505026 url, is_favicon, preferred_size, max_bitmap_size, bypass_cache,
tzike2aca992017-09-05 08:50:545027 base::BindOnce(&WebContentsImpl::OnDidDownloadImage,
Avi Drissmana5a52dd2018-03-27 03:39:025028 weak_factory_.GetWeakPtr(), std::move(callback),
5029 download_id, url));
amistry9f01b772015-07-29 01:54:555030 return download_id;
[email protected]795c28972012-12-06 06:13:395031}
5032
[email protected]36ec24f2014-01-09 00:32:085033void WebContentsImpl::Find(int request_id,
5034 const base::string16& search_text,
Rakina Zata Amni3f77dff2018-09-08 16:19:435035 blink::mojom::FindOptionsPtr options) {
Alexander Timin5fdeff22020-09-08 09:20:375036 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Find");
thestig6057a6b22015-11-12 23:01:335037 // Cowardly refuse to search for no text.
5038 if (search_text.empty()) {
5039 NOTREACHED();
5040 return;
5041 }
5042
Rakina Zata Amni3f77dff2018-09-08 16:19:435043 GetOrCreateFindRequestManager()->Find(request_id, search_text,
5044 std::move(options));
[email protected]36ec24f2014-01-09 00:32:085045}
5046
5047void WebContentsImpl::StopFinding(StopFindAction action) {
Alexander Timin5fdeff22020-09-08 09:20:375048 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::StopFinding");
paulmeyerfeafc2d2017-04-25 21:46:405049 if (FindRequestManager* manager = GetFindRequestManager())
5050 manager->StopFinding(action);
[email protected]36ec24f2014-01-09 00:32:085051}
5052
Tommy Steimel18360512017-11-01 00:38:195053bool WebContentsImpl::WasEverAudible() {
5054 return was_ever_audible_;
5055}
5056
Avi Drissmana5a52dd2018-03-27 03:39:025057void WebContentsImpl::GetManifest(GetManifestCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:375058 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GetManifest");
Yuzu Saijofce18322020-05-14 05:02:095059 // TODO(yuzus, 1061899): Move this function to RenderFrameHostImpl.
5060 ManifestManagerHost* manifest_manager_host =
5061 ManifestManagerHost::GetOrCreateForCurrentDocument(GetMainFrame());
5062 manifest_manager_host->GetManifest(std::move(callback));
mlamouriefdca9d2014-09-16 16:55:405063}
5064
bokanece34a82016-01-28 19:49:465065void WebContentsImpl::ExitFullscreen(bool will_cause_resize) {
Alexander Timin5fdeff22020-09-08 09:20:375066 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ExitFullscreen");
mlamouri7a78d6fd2015-01-17 13:23:535067 // Clean up related state and initiate the fullscreen exit.
James Hollyerd5c9de462020-03-10 19:02:455068 GetRenderViewHost()->GetWidget()->RejectMouseLockOrUnlockIfNecessary(
5069 blink::mojom::PointerLockResult::kUserRejected);
bokanece34a82016-01-28 19:49:465070 ExitFullscreenMode(will_cause_resize);
mlamouri7a78d6fd2015-01-17 13:23:535071}
5072
Mike Wassermanb6bc0152020-08-25 22:46:205073base::ScopedClosureRunner WebContentsImpl::ForSecurityDropFullscreen(
5074 int64_t display_id) {
Alexander Timin5fdeff22020-09-08 09:20:375075 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ForSecurityDropFullscreen",
5076 "display_id", display_id);
Avi Drissman33972942020-06-19 14:16:015077 // Kick WebContentses that are "related" to this WebContents out of
5078 // fullscreen. This needs to be done with two passes, because it is simple to
5079 // walk _up_ the chain of openers and outer contents, but it not simple to
5080 // walk _down_ the chain.
5081
5082 // First, determine if any WebContents that is in fullscreen has this
5083 // WebContents as an upstream contents. Drop that WebContents out of
5084 // fullscreen if it does. This is theoretically quadratic-ish (fullscreen
5085 // contentses x each one's opener length) but neither of those is expected to
5086 // ever be a large number.
5087
Mike Wassermanb6bc0152020-08-25 22:46:205088 auto* screen = display::Screen::GetScreen();
5089
Avi Drissman33972942020-06-19 14:16:015090 auto fullscreen_set_copy = *FullscreenContentsSet(GetBrowserContext());
5091 for (auto* fullscreen_contents : fullscreen_set_copy) {
Avi Drissman97aef042020-06-30 21:04:485092 // Checking IsFullscreen() for tabs in the fullscreen set may seem
5093 // redundant, but teeeeechnically fullscreen is run by the delegate, and
5094 // it's possible that the delegate's notion of fullscreen may have changed
5095 // outside of WebContents's notice.
Mike Wassermanb6bc0152020-08-25 22:46:205096 if (fullscreen_contents->IsFullscreen() &&
5097 (display_id == display::kInvalidDisplayId || !screen ||
5098 display_id ==
5099 screen->GetDisplayNearestView(fullscreen_contents->GetNativeView())
5100 .id())) {
Avi Drissman33972942020-06-19 14:16:015101 auto opener_contentses = GetAllOpeningWebContents(fullscreen_contents);
5102 if (opener_contentses.count(this))
5103 fullscreen_contents->ExitFullscreen(true);
5104 }
5105 }
5106
5107 // Second, walk upstream from this WebContents, and drop the fullscreen of
5108 // all WebContentses that are in fullscreen. Block all the WebContentses in
5109 // the chain from entering fullscreen while the returned closure runner is
5110 // alive. It's OK that this set doesn't contain downstream WebContentses, as
5111 // any request to enter fullscreen will have the upstream of the WebContents
5112 // checked. (See CanEnterFullscreenMode().)
Avi Drissmanced52b62019-08-14 21:25:465113
Avi Drissman1a55a9d62020-03-10 18:56:455114 std::vector<base::WeakPtr<WebContentsImpl>> blocked_contentses;
5115
Avi Drissman33972942020-06-19 14:16:015116 for (auto* opener : GetAllOpeningWebContents(this)) {
Avi Drissman1a55a9d62020-03-10 18:56:455117 // Drop fullscreen if the WebContents is in it, and...
Mike Wassermanb6bc0152020-08-25 22:46:205118 if (opener->IsFullscreen() &&
5119 (display_id == display::kInvalidDisplayId || !screen ||
5120 display_id ==
5121 screen->GetDisplayNearestView(opener->GetNativeView()).id()))
Avi Drissman33972942020-06-19 14:16:015122 opener->ExitFullscreen(true);
Avi Drissmanced52b62019-08-14 21:25:465123
Avi Drissman1a55a9d62020-03-10 18:56:455124 // ...block the WebContents from entering fullscreen until further notice.
Avi Drissman33972942020-06-19 14:16:015125 ++opener->fullscreen_blocker_count_;
5126 blocked_contentses.push_back(opener->weak_factory_.GetWeakPtr());
Avi Drissmanced52b62019-08-14 21:25:465127 }
Avi Drissman1a55a9d62020-03-10 18:56:455128
5129 return base::ScopedClosureRunner(base::BindOnce(
5130 [](std::vector<base::WeakPtr<WebContentsImpl>> blocked_contentses) {
5131 for (base::WeakPtr<WebContentsImpl>& web_contents :
5132 blocked_contentses) {
5133 if (web_contents) {
5134 DCHECK_GT(web_contents->fullscreen_blocker_count_, 0);
5135 --web_contents->fullscreen_blocker_count_;
5136 }
5137 }
5138 },
5139 std::move(blocked_contentses)));
Avi Drissmanced52b62019-08-14 21:25:465140}
5141
mariakhomenko44bdc4732015-04-29 01:55:385142void WebContentsImpl::ResumeLoadingCreatedWebContents() {
Alexander Timin5fdeff22020-09-08 09:20:375143 OPTIONAL_TRACE_EVENT0("content",
5144 "WebContentsImpl::ResumeLoadingCreatedWebContents");
Nasko Oskov83a8cf92018-10-19 14:58:565145 if (delayed_load_url_params_.get()) {
5146 DCHECK(!delayed_open_url_params_);
5147 controller_.LoadURLWithParams(*delayed_load_url_params_.get());
5148 delayed_load_url_params_.reset(nullptr);
5149 return;
5150 }
5151
mariakhomenkoa4971c12015-07-21 19:04:375152 if (delayed_open_url_params_.get()) {
5153 OpenURL(*delayed_open_url_params_.get());
5154 delayed_open_url_params_.reset(nullptr);
5155 return;
5156 }
5157
mariakhomenko44bdc4732015-04-29 01:55:385158 // Resume blocked requests for both the RenderViewHost and RenderFrameHost.
5159 // TODO(brettw): It seems bogus to reach into here and initialize the host.
dfalcantarae6b7b46752015-07-10 18:14:165160 if (is_resume_pending_) {
5161 is_resume_pending_ = false;
avi0f1bbc9712015-11-17 02:58:135162 GetRenderViewHost()->GetWidget()->Init();
dfalcantarae6b7b46752015-07-10 18:14:165163 GetMainFrame()->Init();
5164 }
mariakhomenko44bdc4732015-04-29 01:55:385165}
5166
[email protected]b172aee2012-04-10 17:05:265167bool WebContentsImpl::FocusLocationBarByDefault() {
Alexander Timin5fdeff22020-09-08 09:20:375168 OPTIONAL_TRACE_EVENT0("content",
5169 "WebContentsImpl::FocusLocationBarByDefault");
Xiyuan Xia2a66b112018-12-06 15:52:165170 if (should_focus_location_bar_by_default_)
[email protected]0c9406632013-02-08 01:13:335171 return true;
Xiyuan Xia2a66b112018-12-06 15:52:165172
[email protected]0c9406632013-02-08 01:13:335173 return delegate_ && delegate_->ShouldFocusLocationBarByDefault(this);
[email protected]0bfbf882011-12-22 18:19:275174}
5175
clamy0e119882015-07-31 16:12:335176void WebContentsImpl::DidStartNavigation(NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:485177 TRACE_EVENT1("navigation", "WebContentsImpl::DidStartNavigation",
5178 "navigation_handle", navigation_handle);
Alan Cutterab48fc02020-02-24 12:26:425179 if (navigation_handle->IsInMainFrame())
5180 favicon_urls_.clear();
Mounir Lamouri7b4a1f232019-12-23 16:32:105181
Alexander Timin90c20c32020-08-12 15:28:325182 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5183 observer->DidStartNavigation(navigation_handle);
5184 });
Xiyuan Xia2a66b112018-12-06 15:52:165185 if (navigation_handle->IsInMainFrame()) {
5186 // When the browser is started with about:blank as the startup URL, focus
5187 // the location bar (which will also select its contents) so people can
5188 // simply begin typing to navigate elsewhere.
5189 //
5190 // We need to be careful not to trigger this for anything other than the
5191 // startup navigation. In particular, if we allow an attacker to open a
5192 // popup to about:blank, then navigate, focusing the Omnibox will cause the
5193 // end of the new URL to be scrolled into view instead of the start,
5194 // allowing the attacker to spoof other URLs. The conditions checked here
5195 // are all aimed at ensuring no such attacker-controlled navigation can
5196 // trigger this.
5197 should_focus_location_bar_by_default_ =
5198 controller_.IsInitialNavigation() &&
5199 !navigation_handle->IsRendererInitiated() &&
5200 navigation_handle->GetURL() == url::kAboutBlankURL;
5201 }
clamy0e119882015-07-31 16:12:335202}
5203
5204void WebContentsImpl::DidRedirectNavigation(
5205 NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:485206 TRACE_EVENT1("navigation", "WebContentsImpl::DidRedirectNavigation",
5207 "navigation_handle", navigation_handle);
Alexander Timin90c20c32020-08-12 15:28:325208 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5209 observer->DidRedirectNavigation(navigation_handle);
5210 });
jam5f358e52017-02-13 16:37:035211 // Notify accessibility if this is a reload. This has to called on the
5212 // BrowserAccessibilityManager associated with the old RFHI.
5213 if (navigation_handle->GetReloadType() != ReloadType::NONE) {
Mohamed Abdelhalim95794962019-09-20 11:16:495214 NavigationRequest* request = NavigationRequest::From(navigation_handle);
jam5f358e52017-02-13 16:37:035215 BrowserAccessibilityManager* manager =
Mohamed Abdelhalim95794962019-09-20 11:16:495216 request->frame_tree_node()
jam5f358e52017-02-13 16:37:035217 ->current_frame_host()
5218 ->browser_accessibility_manager();
5219 if (manager)
5220 manager->UserIsReloading();
5221 }
clamy0e119882015-07-31 16:12:335222}
5223
clamyefca29e2015-09-17 00:22:115224void WebContentsImpl::ReadyToCommitNavigation(
5225 NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:485226 TRACE_EVENT1("navigation", "WebContentsImpl::ReadyToCommitNavigation",
5227 "navigation_handle", navigation_handle);
Alexander Timin90c20c32020-08-12 15:28:325228 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5229 observer->ReadyToCommitNavigation(navigation_handle);
5230 });
Kenneth Russell954ed9ce2018-04-12 23:07:015231 // If any domains are blocked from accessing 3D APIs because they may
5232 // have caused the GPU to reset recently, unblock them here if the user
5233 // initiated this navigation. This implies that the user was involved in
5234 // the decision to navigate, so there's no concern about
5235 // denial-of-service issues. Want to do this as early as
5236 // possible to avoid race conditions with pages attempting to access
5237 // WebGL early on.
5238 //
5239 // TODO(crbug.com/617904): currently navigations initiated by the browser
5240 // (reload button, reload menu option, pressing return in the Omnibox)
5241 // return false from HasUserGesture(). If or when that is addressed,
5242 // remove the check for IsRendererInitiated() below.
5243 //
5244 // TODO(crbug.com/832180): HasUserGesture comes from the renderer
5245 // process and isn't validated. Until it is, don't trust it.
5246 if (!navigation_handle->IsRendererInitiated()) {
5247 GpuDataManagerImpl::GetInstance()->UnblockDomainFrom3DAPIs(
5248 navigation_handle->GetURL());
5249 }
5250
John Abd-El-Malekfde08e6da2017-12-05 04:06:245251 if (navigation_handle->IsSameDocument())
5252 return;
5253
Livvie Lin139bf442018-08-10 00:18:545254 // SSLInfo is not needed on subframe navigations since the main-frame
5255 // certificate is the only one that can be inspected (using the info
5256 // bubble) without refreshing the page with DevTools open.
Carlos ILaed1e7b2019-03-12 19:27:215257 // We don't call DidStartResourceResponse on net errors, since that results on
5258 // existing cert exceptions being revoked, which leads to weird behavior with
5259 // committed interstitials or while offline. We only need the error check for
5260 // the main frame case because unlike this method, SubresourceResponseStarted
5261 // does not get called on network errors.
5262 if (navigation_handle->IsInMainFrame() &&
5263 navigation_handle->GetNetErrorCode() == net::OK) {
Livvie Lin139bf442018-08-10 00:18:545264 controller_.ssl_manager()->DidStartResourceResponse(
Lukasz Anforowiczd334bba2020-02-10 23:32:555265 navigation_handle->GetURL(),
Camille Lamy62b826012019-02-26 09:15:475266 navigation_handle->GetSSLInfo().has_value()
5267 ? net::IsCertStatusError(
5268 navigation_handle->GetSSLInfo()->cert_status)
5269 : false);
5270 }
John Abd-El-Malekfde08e6da2017-12-05 04:06:245271
Bruce Dawsone1c5c842020-09-15 02:09:145272 // LoadingStateChanged must be called last in case it triggers deletion of
5273 // |this| due to recursive message pumps.
John Abd-El-Malekfde08e6da2017-12-05 04:06:245274 SetNotWaitingForResponse();
clamyefca29e2015-09-17 00:22:115275}
5276
clamy0e119882015-07-31 16:12:335277void WebContentsImpl::DidFinishNavigation(NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:485278 TRACE_EVENT1("navigation", "WebContentsImpl::DidFinishNavigation",
5279 "navigation_handle", navigation_handle);
Steven Holte38041342018-06-22 22:00:575280
Alexander Timin90c20c32020-08-12 15:28:325281 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5282 observer->DidFinishNavigation(navigation_handle);
5283 });
Becca Hughesd11d6502018-07-31 17:01:285284 if (display_cutout_host_impl_)
5285 display_cutout_host_impl_->DidFinishNavigation(navigation_handle);
5286
jam5f358e52017-02-13 16:37:035287 if (navigation_handle->HasCommitted()) {
Ian Prestcdd843d2020-01-28 18:59:585288 // TODO(domfarolino, dmazzoni): Do this using WebContentsObserver. See
5289 // https://crbug.com/981271.
5290 BrowserAccessibilityManager* manager =
5291 static_cast<RenderFrameHostImpl*>(
5292 navigation_handle->GetRenderFrameHost())
5293 ->browser_accessibility_manager();
5294 if (manager) {
5295 if (navigation_handle->IsErrorPage()) {
5296 manager->NavigationFailed();
5297 } else {
5298 manager->NavigationSucceeded();
5299 }
5300 }
5301
Yue Ru Sun979c4b162019-11-06 16:11:045302 if (navigation_handle->IsInMainFrame()) {
5303 last_committed_source_id_including_same_document_ =
Steven Holte38041342018-06-22 22:00:575304 ukm::ConvertToSourceId(navigation_handle->GetNavigationId(),
5305 ukm::SourceIdType::NAVIGATION_ID);
Yue Ru Sun979c4b162019-11-06 16:11:045306
5307 if (!navigation_handle->IsSameDocument()) {
5308 was_ever_audible_ = false;
Yue Ru Sun979c4b162019-11-06 16:11:045309 }
Tommy Steimel18360512017-11-01 00:38:195310 }
Lan Weif81c6e7c2020-02-12 16:46:095311
5312 if (!navigation_handle->IsSameDocument())
5313 last_screen_orientation_change_time_ = base::TimeTicks();
dmazzonibf8cec42015-02-08 08:28:085314 }
Xiyuan Xia2a66b112018-12-06 15:52:165315
5316 // If we didn't end up on about:blank after setting this in DidStartNavigation
5317 // then don't focus the location bar.
5318 if (should_focus_location_bar_by_default_ &&
5319 navigation_handle->GetURL() != url::kAboutBlankURL) {
5320 should_focus_location_bar_by_default_ = false;
5321 }
yilkal796e89e2019-10-02 23:58:285322
yilkal172da772019-11-06 22:49:075323 if (navigation_handle->IsInMainFrame() && first_navigation_completed_)
5324 RecordMaxFrameCountUMA(max_loaded_frame_count_);
yilkal796e89e2019-10-02 23:58:285325
yilkal172da772019-11-06 22:49:075326 // If navigation has successfully finished in the main frame, set
5327 // |first_navigation_completed_| to true so that we will record
5328 // |max_loaded_frame_count_| above when future main frame navigations finish.
5329 if (navigation_handle->IsInMainFrame() && !navigation_handle->IsErrorPage()) {
5330 first_navigation_completed_ = true;
5331
5332 // Navigation has completed in main frame. Reset |max_loaded_frame_count_|.
5333 // |max_loaded_frame_count_| is not necessarily 1 if the navigation was
5334 // served from BackForwardCache.
5335 max_loaded_frame_count_ =
5336 GetMainFrame()->frame_tree_node()->GetFrameTreeSize();
yilkal796e89e2019-10-02 23:58:285337 }
Rakina Zata Amni347b70902020-07-22 10:49:045338
5339 if (web_preferences_) {
5340 // Update the WebPreferences for this WebContents that depends on changes
5341 // that might occur during navigation. This will only update the preferences
5342 // that needs to be updated (and won't cause an update/overwrite preferences
5343 // that needs to stay the same after navigations).
5344 bool value_changed_due_to_override =
5345 GetContentClient()->browser()->OverrideWebPreferencesAfterNavigation(
5346 this, web_preferences_.get());
5347 // We need to update the WebPreferences value on the renderer if the value
5348 // is changed due to the override above, or if the navigation is served from
5349 // the back-forward cache, because the WebPreferences value stored in the
5350 // renderer might be stale (because we don't send WebPreferences updates to
5351 // bfcached renderers).
5352 // TODO(rakina): Maybe handle the back-forward cache case in
5353 // ReadyToCommitNavigation instead?
5354 if (value_changed_due_to_override ||
5355 NavigationRequest::From(navigation_handle)
5356 ->IsServedFromBackForwardCache()) {
5357 SetWebPreferences(*web_preferences_.get());
5358 }
5359 }
[email protected]400992b2012-06-14 00:03:545360}
5361
[email protected]b80624c2014-02-09 02:46:555362void WebContentsImpl::DidFailLoadWithError(
5363 RenderFrameHostImpl* render_frame_host,
[email protected]b80624c2014-02-09 02:46:555364 const GURL& url,
Dave Tapuska924ef3c2020-01-22 18:20:595365 int error_code) {
Alexander Timin5fdeff22020-09-08 09:20:375366 TRACE_EVENT2("content,navigation", "WebContentsImpl::DidFailLoadWithError",
5367 "render_frame_host",
5368 base::trace_event::ToTracedValue(render_frame_host), "url",
5369 base::trace_event::ValueToString(url));
Alexander Timin90c20c32020-08-12 15:28:325370 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5371 observer->DidFailLoad(render_frame_host, url, error_code);
5372 });
[email protected]b80624c2014-02-09 02:46:555373}
5374
[email protected]52913802013-12-10 05:52:185375void WebContentsImpl::NotifyChangedNavigationState(
5376 InvalidateTypes changed_flags) {
5377 NotifyNavigationStateChanged(changed_flags);
5378}
5379
lukasza1d025732016-09-28 21:36:085380bool WebContentsImpl::ShouldTransferNavigation(bool is_main_frame_navigation) {
Alexander Timin5fdeff22020-09-08 09:20:375381 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ShouldTransferNavigation",
5382 "is_main_frame_navigation", is_main_frame_navigation);
creis29460272015-12-16 04:38:225383 if (!delegate_)
5384 return true;
lukasza1d025732016-09-28 21:36:085385 return delegate_->ShouldTransferNavigation(is_main_frame_navigation);
creis29460272015-12-16 04:38:225386}
5387
[email protected]aa62afd2014-04-22 19:22:465388bool WebContentsImpl::ShouldPreserveAbortedURLs() {
Alexander Timin5fdeff22020-09-08 09:20:375389 OPTIONAL_TRACE_EVENT0("content",
5390 "WebContentsImpl::ShouldPreserveAbortedURLs");
[email protected]aa62afd2014-04-22 19:22:465391 if (!delegate_)
5392 return false;
5393 return delegate_->ShouldPreserveAbortedURLs(this);
5394}
5395
[email protected]0d0f4c492014-04-02 06:42:575396void WebContentsImpl::DidNavigateMainFramePreCommit(
[email protected]5cfbddc2014-06-23 23:52:235397 bool navigation_is_within_page) {
Alexander Timin5fdeff22020-09-08 09:20:375398 TRACE_EVENT1("content,navigation",
5399 "WebContentsImpl::DidNavigateMainFramePreCommit",
5400 "navigation_is_within_page", navigation_is_within_page);
[email protected]0d0f4c492014-04-02 06:42:575401 // Ensure fullscreen mode is exited before committing the navigation to a
5402 // different page. The next page will not start out assuming it is in
5403 // fullscreen mode.
[email protected]5cfbddc2014-06-23 23:52:235404 if (navigation_is_within_page) {
[email protected]dfc39cb2014-04-09 22:58:195405 // No page change? Then, the renderer and browser can remain in fullscreen.
[email protected]0d0f4c492014-04-02 06:42:575406 return;
5407 }
Avi Drissman97aef042020-06-30 21:04:485408 if (IsFullscreen())
bokanece34a82016-01-28 19:49:465409 ExitFullscreen(false);
Avi Drissman97aef042020-06-30 21:04:485410 DCHECK(!IsFullscreen());
Joe Downingc1a57efe2018-05-09 18:23:545411
5412 // Clean up keyboard lock state when navigating.
5413 CancelKeyboardLock(keyboard_lock_widget_);
[email protected]0d0f4c492014-04-02 06:42:575414}
5415
[email protected]37567b432014-02-12 01:12:225416void WebContentsImpl::DidNavigateMainFramePostCommit(
sky8b00392d2015-01-10 00:30:285417 RenderFrameHostImpl* render_frame_host,
[email protected]37567b432014-02-12 01:12:225418 const LoadCommittedDetails& details,
5419 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
Alexander Timin5fdeff22020-09-08 09:20:375420 OPTIONAL_TRACE_EVENT1(
5421 "content,navigation", "WebContentsImpl::DidNavigateMainFramePostCommit",
5422 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host));
[email protected]37567b432014-02-12 01:12:225423 if (details.is_navigation_to_different_page()) {
5424 // Clear the status bubble. This is a workaround for a bug where WebKit
5425 // doesn't let us know that the cursor left an element during a
5426 // transition (this is also why the mouse cursor remains as a hand after
5427 // clicking on a link); see bugs 1184641 and 980803. We don't want to
5428 // clear the bubble when a user navigates to a named anchor in the same
5429 // page.
Lukasz Anforowiczfd707142018-02-07 19:46:135430 ClearTargetURL();
lanwei9d343ad22015-02-11 01:46:005431
5432 RenderWidgetHostViewBase* rwhvb =
5433 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
5434 if (rwhvb)
5435 rwhvb->OnDidNavigateMainFrameToNewPage();
[email protected]37567b432014-02-12 01:12:225436 }
5437
[email protected]e85165c642014-06-10 14:34:315438 if (delegate_)
[email protected]37567b432014-02-12 01:12:225439 delegate_->DidNavigateMainFramePostCommit(this);
[email protected]e85165c642014-06-10 14:34:315440 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
Shivani Sharma985474f2019-05-23 21:36:475441
Alan Cutterd73a15d92020-08-21 07:12:455442 // The following events will not fire again if the page is restored from the
5443 // BackForwardCache. So fire them ourselves if needed.
Carlos Caballero91fffb22019-10-29 15:24:305444 if (details.is_navigation_to_different_page() &&
5445 GetRenderViewHost()->did_first_visually_non_empty_paint()) {
Carlos Caballero91fffb22019-10-29 15:24:305446 DidFirstVisuallyNonEmptyPaint(GetRenderViewHost());
5447 }
Alan Cutterd73a15d92020-08-21 07:12:455448 if (GetRenderViewHost()->theme_color() != last_sent_theme_color_)
Carlos Caballero1215f882019-10-29 15:58:435449 OnThemeColorChanged(GetRenderViewHost());
Alan Cutterd73a15d92020-08-21 07:12:455450 if (GetRenderViewHost()->background_color() != last_sent_background_color_)
5451 OnBackgroundColorChanged(GetRenderViewHost());
[email protected]37567b432014-02-12 01:12:225452}
5453
5454void WebContentsImpl::DidNavigateAnyFramePostCommit(
5455 RenderFrameHostImpl* render_frame_host,
5456 const LoadCommittedDetails& details,
5457 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
Alexander Timin5fdeff22020-09-08 09:20:375458 OPTIONAL_TRACE_EVENT1(
5459 "content,navigation", "WebContentsImpl::DidNavigateAnyFramePostCommit",
5460 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host));
[email protected]b4c84012014-04-28 19:51:105461 // Now that something has committed, we don't need to track whether the
5462 // initial page has been accessed.
5463 has_accessed_initial_document_ = false;
5464
[email protected]37567b432014-02-12 01:12:225465 // If we navigate off the page, close all JavaScript dialogs.
eugenebutee08663a2017-04-27 17:43:125466 if (!details.is_same_document)
creis89a0f782015-05-27 16:13:175467 CancelActiveAndPendingDialogs();
[email protected]37567b432014-02-12 01:12:225468
avid53461d2016-02-25 17:15:045469 // If this is a user-initiated navigation, start allowing JavaScript dialogs
5470 // again.
avi5d3b8692016-10-12 22:00:465471 if (params.gesture == NavigationGestureUser && dialog_manager_) {
avi6879fcf2017-01-21 05:27:535472 dialog_manager_->CancelDialogs(this, /*reset_state=*/true);
avi5d3b8692016-10-12 22:00:465473 }
[email protected]37567b432014-02-12 01:12:225474}
5475
[email protected]277857a2014-06-03 10:38:015476bool WebContentsImpl::CanOverscrollContent() const {
Alexander Timin5fdeff22020-09-08 09:20:375477 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::CanOverscrollContent");
[email protected]e85165c642014-06-10 14:34:315478 // Disable overscroll when touch emulation is on. See crbug.com/369938.
[email protected]34ff1cfc2014-08-20 06:16:055479 if (force_disable_overscroll_content_)
[email protected]e85165c642014-06-10 14:34:315480 return false;
5481
[email protected]37567b432014-02-12 01:12:225482 if (delegate_)
5483 return delegate_->CanOverscrollContent();
5484
5485 return false;
5486}
5487
Carlos Caballero1215f882019-10-29 15:58:435488void WebContentsImpl::OnThemeColorChanged(RenderViewHostImpl* source) {
Alexander Timin5fdeff22020-09-08 09:20:375489 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnThemeColorChanged",
5490 "render_view_host", source);
Carlos Caballero1215f882019-10-29 15:58:435491 if (source->did_first_visually_non_empty_paint() &&
5492 last_sent_theme_color_ != source->theme_color()) {
Alexander Timin90c20c32020-08-12 15:28:325493 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5494 observer->DidChangeThemeColor();
5495 });
Matt Jones36fc2882020-08-25 14:25:125496 last_sent_theme_color_ = source->theme_color();
peter90afaba2015-06-01 12:05:295497 }
[email protected]e7104762014-06-20 19:17:255498}
5499
Alan Cutterd73a15d92020-08-21 07:12:455500void WebContentsImpl::OnBackgroundColorChanged(RenderViewHostImpl* source) {
Rune Lillesveend14781f2020-10-06 19:36:115501 if (source->did_first_visually_non_empty_paint()) {
5502 if (last_sent_background_color_ != source->background_color()) {
5503 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5504 observer->OnBackgroundColorChanged();
5505 });
5506 last_sent_background_color_ = source->background_color();
5507 }
5508 return;
5509 }
5510
5511 if (source->background_color().has_value()) {
5512 // <meta name="color-scheme" content="dark"> may pass the dark canvas
5513 // background before the first paint in order to avoid flashing the white
5514 // background in between loading documents. If we perform a navigation
5515 // within the same renderer process, we keep the content background from the
5516 // previous page while rendering is blocked in the new page, but for cross
5517 // process navigations we would paint the default background (typically
5518 // white) while the rendering is blocked.
5519 if (auto* view = GetRenderWidgetHostView()) {
5520 static_cast<RenderWidgetHostViewBase*>(view)->SetContentBackgroundColor(
5521 source->background_color().value());
5522 }
Alan Cutterd73a15d92020-08-21 07:12:455523 }
5524}
5525
Gyuyoung Kim1905f7c2020-05-02 00:00:245526void WebContentsImpl::DidLoadResourceFromMemoryCache(
nicka0ac8382016-12-15 23:59:235527 RenderFrameHostImpl* source,
[email protected]724159a2010-12-30 01:11:185528 const GURL& url,
[email protected]70435962011-08-02 20:13:285529 const std::string& http_method,
[email protected]6d6cfb3a2012-05-23 22:53:185530 const std::string& mime_type,
Kinuko Yasuda433f710a2020-02-14 02:11:585531 network::mojom::RequestDestination request_destination) {
Alexander Timin5fdeff22020-09-08 09:20:375532 OPTIONAL_TRACE_EVENT2(
5533 "content", "WebContentsImpl::DidLoadResourceFromMemoryCache",
5534 "render_frame_host", base::trace_event::ToTracedValue(source), "url",
5535 base::trace_event::ValueToString(url));
Alexander Timin90c20c32020-08-12 15:28:325536 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5537 observer->DidLoadResourceFromMemoryCache(url, mime_type,
5538 request_destination);
5539 });
[email protected]b0f724c2013-09-05 04:21:135540
Steven Bingler674fb0822018-12-12 18:04:525541 if (url.is_valid() && url.SchemeIsHTTPOrHTTPS()) {
nicka0ac8382016-12-15 23:59:235542 StoragePartition* partition = source->GetProcess()->GetStoragePartition();
John Abd-El-Malekf4fe9d82019-07-31 04:05:595543 partition->GetNetworkContext()->NotifyExternalCacheHit(
Matt Menke2a33dee2019-12-02 17:01:545544 url, http_method, source->GetNetworkIsolationKey());
[email protected]8bfc8272013-09-09 20:10:535545 }
[email protected]724159a2010-12-30 01:11:185546}
5547
carloskd9d97942017-02-16 08:58:095548void WebContentsImpl::DidDisplayInsecureContent() {
Alexander Timin5fdeff22020-09-08 09:20:375549 OPTIONAL_TRACE_EVENT0("content",
5550 "WebContentsImpl::DidDisplayInsecureContent");
estarkc2273502016-10-12 22:03:025551 controller_.ssl_manager()->DidDisplayMixedContent();
[email protected]724159a2010-12-30 01:11:185552}
5553
Dave Tapuskaa657d872019-10-21 20:23:215554void WebContentsImpl::DidContainInsecureFormAction() {
Alexander Timin5fdeff22020-09-08 09:20:375555 OPTIONAL_TRACE_EVENT0("content",
5556 "WebContentsImpl::DidContainInsecureFormAction");
elawrenceb2ac2a232017-03-27 21:46:255557 controller_.ssl_manager()->DidContainInsecureFormAction();
5558}
5559
Julie Jeongeun Kim0b103492020-01-29 05:30:515560void WebContentsImpl::DocumentAvailableInMainFrame() {
Alexander Timin5fdeff22020-09-08 09:20:375561 OPTIONAL_TRACE_EVENT0("content",
5562 "WebContentsImpl::DocumentAvailableInMainFrame");
Alexander Timin90c20c32020-08-12 15:28:325563 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5564 observer->DocumentAvailableInMainFrame();
5565 });
Julie Jeongeun Kim0b103492020-01-29 05:30:515566}
5567
nicka0ac8382016-12-15 23:59:235568void WebContentsImpl::OnDidRunInsecureContent(RenderFrameHostImpl* source,
5569 const GURL& security_origin,
estark910b4572015-12-09 20:55:415570 const GURL& target_url) {
Alexander Timin5fdeff22020-09-08 09:20:375571 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnDidRunInsecureContent",
5572 "render_frame_host",
5573 base::trace_event::ToTracedValue(source));
nicka0ac8382016-12-15 23:59:235574 // TODO(nick, estark): Should we call FilterURL using |source|'s process on
5575 // these parameters? |target_url| seems unused, except for a log message. And
5576 // |security_origin| might be replaceable with the origin of the main frame.
carloskd9d97942017-02-16 08:58:095577 DidRunInsecureContent(security_origin, target_url);
5578}
5579
5580void WebContentsImpl::DidRunInsecureContent(const GURL& security_origin,
5581 const GURL& target_url) {
Alexander Timin5fdeff22020-09-08 09:20:375582 OPTIONAL_TRACE_EVENT2(
5583 "content", "WebContentsImpl::DidRunInsecureContent", "security_origin",
5584 base::trace_event::ValueToString(security_origin), "target_url",
5585 base::trace_event::ValueToString(target_url));
[email protected]9450c462013-11-23 01:22:585586 LOG(WARNING) << security_origin << " ran insecure content from "
5587 << target_url.possibly_invalid_spec();
[email protected]e6e30ac2014-01-13 21:24:395588 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
estark910b4572015-12-09 20:55:415589 if (base::EndsWith(security_origin.spec(), kDotGoogleDotCom,
brettwa7ff1b292015-07-16 17:49:295590 base::CompareCase::INSENSITIVE_ASCII))
[email protected]e6e30ac2014-01-13 21:24:395591 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
estarkc2273502016-10-12 22:03:025592 controller_.ssl_manager()->DidRunMixedContent(security_origin);
[email protected]724159a2010-12-30 01:11:185593}
5594
carloskd9d97942017-02-16 08:58:095595void WebContentsImpl::PassiveInsecureContentFound(const GURL& resource_url) {
Alexander Timin5fdeff22020-09-08 09:20:375596 OPTIONAL_TRACE_EVENT1(
5597 "content", "WebContentsImpl::PassiveInsecureContentFound", "resource_url",
5598 base::trace_event::ValueToString(resource_url));
Sergey Kuznetsov3ebc01b2018-02-01 04:57:365599 if (delegate_) {
5600 delegate_->PassiveInsecureContentFound(resource_url);
5601 }
carloskd9d97942017-02-16 08:58:095602}
5603
5604bool WebContentsImpl::ShouldAllowRunningInsecureContent(
carloskd9d97942017-02-16 08:58:095605 bool allowed_per_prefs,
5606 const url::Origin& origin,
5607 const GURL& resource_url) {
Alexander Timin5fdeff22020-09-08 09:20:375608 OPTIONAL_TRACE_EVENT0("content",
5609 "WebContentsImpl::ShouldAllowRunningInsecureContent");
Sergey Kuznetsov3ebc01b2018-02-01 04:57:365610 if (delegate_) {
Carlos IL29294a62020-05-15 00:21:165611 return delegate_->ShouldAllowRunningInsecureContent(this, allowed_per_prefs,
5612 origin, resource_url);
Sergey Kuznetsov3ebc01b2018-02-01 04:57:365613 }
5614
5615 return allowed_per_prefs;
carloskd9d97942017-02-16 08:58:095616}
5617
Lukasz Anforowicze1b954d92017-10-30 21:28:065618void WebContentsImpl::ViewSource(RenderFrameHostImpl* frame) {
Alexander Timin5fdeff22020-09-08 09:20:375619 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ViewSource",
5620 "render_frame_host",
5621 base::trace_event::ToTracedValue(frame));
Lukasz Anforowicze1b954d92017-10-30 21:28:065622 DCHECK_EQ(this, WebContents::FromRenderFrameHost(frame));
5623
5624 // Don't do anything if there is no |delegate_| that could accept and show the
5625 // new WebContents containing the view-source.
5626 if (!delegate_)
5627 return;
5628
5629 // Use the last committed entry, since the pending entry hasn't loaded yet and
5630 // won't be copied into the cloned tab.
5631 NavigationEntryImpl* last_committed_entry =
Fergal Daly09d6c762020-05-29 02:05:185632 GetController().GetLastCommittedEntry();
Lukasz Anforowicze1b954d92017-10-30 21:28:065633 if (!last_committed_entry)
5634 return;
5635
5636 FrameNavigationEntry* frame_entry =
5637 last_committed_entry->GetFrameEntry(frame->frame_tree_node());
5638 if (!frame_entry)
5639 return;
5640
5641 // Any new WebContents opened while this WebContents is in fullscreen can be
5642 // used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:455643 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
5644 // The new view source contents will be independent of this contents, so
5645 // release the fullscreen block.
5646 fullscreen_block.RunAndReset();
Lukasz Anforowicze1b954d92017-10-30 21:28:065647
5648 // We intentionally don't share the SiteInstance with the original frame so
5649 // that view source has a consistent process model and always ends up in a new
5650 // process (https://crbug.com/699493).
5651 scoped_refptr<SiteInstanceImpl> site_instance_for_view_source = nullptr;
Lukasz Anforowicz435bcb582019-07-12 20:50:065652 // Referrer and initiator are not important, because view-source should not
5653 // hit the network, but should be served from the cache instead.
Lukasz Anforowicze1b954d92017-10-30 21:28:065654 Referrer referrer_for_view_source;
Lukasz Anforowicz435bcb582019-07-12 20:50:065655 base::Optional<url::Origin> initiator_for_view_source = base::nullopt;
Lukasz Anforowicze1b954d92017-10-30 21:28:065656 // Do not restore title, derive it from the url.
5657 base::string16 title_for_view_source;
5658 auto navigation_entry = std::make_unique<NavigationEntryImpl>(
5659 site_instance_for_view_source, frame_entry->url(),
Lukasz Anforowicz435bcb582019-07-12 20:50:065660 referrer_for_view_source, initiator_for_view_source,
5661 title_for_view_source, ui::PAGE_TRANSITION_LINK,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:095662 /* is_renderer_initiated = */ false,
5663 /* blob_url_loader_factory = */ nullptr);
Joel Hockey891e88062020-04-30 05:38:445664 const GURL url(content::kViewSourceScheme + std::string(":") +
5665 frame_entry->url().spec());
5666 navigation_entry->SetVirtualURL(url);
Matt Menkea56c5992020-04-10 20:53:565667 navigation_entry->set_isolation_info(
5668 frame->GetIsolationInfoForSubresources());
Yao Xiaof68f57d2019-10-03 04:20:055669
Lukasz Anforowicze1b954d92017-10-30 21:28:065670 // Do not restore scroller position.
5671 // TODO(creis, lukasza, arthursonzogni): Do not reuse the original PageState,
5672 // but start from a new one and only copy the needed data.
Miyoung Shin5d77f72072020-10-09 15:14:205673 const blink::PageState& new_page_state =
Lukasz Anforowicze1b954d92017-10-30 21:28:065674 frame_entry->page_state().RemoveScrollOffset();
5675
5676 scoped_refptr<FrameNavigationEntry> new_frame_entry =
5677 navigation_entry->root_node()->frame_entry;
5678 new_frame_entry->set_method(frame_entry->method());
5679 new_frame_entry->SetPageState(new_page_state);
5680
5681 // Create a new WebContents, which is used to display the source code.
erikchenbee5c9622018-04-27 19:30:255682 std::unique_ptr<WebContents> view_source_contents =
Erik Chenbb8e738e2018-04-28 14:10:435683 Create(CreateParams(GetBrowserContext()));
Lukasz Anforowicze1b954d92017-10-30 21:28:065684
5685 // Restore the previously created NavigationEntry.
5686 std::vector<std::unique_ptr<NavigationEntry>> navigation_entries;
5687 navigation_entries.push_back(std::move(navigation_entry));
5688 view_source_contents->GetController().Restore(0, RestoreType::CURRENT_SESSION,
5689 &navigation_entries);
5690
5691 // Add |view_source_contents| as a new tab.
5692 gfx::Rect initial_rect;
5693 constexpr bool kUserGesture = true;
5694 bool ignored_was_blocked;
Joel Hockey891e88062020-04-30 05:38:445695 delegate_->AddNewContents(this, std::move(view_source_contents), url,
Lukasz Anforowicze1b954d92017-10-30 21:28:065696 WindowOpenDisposition::NEW_FOREGROUND_TAB,
5697 initial_rect, kUserGesture, &ignored_was_blocked);
5698 // Note that the |delegate_| could have deleted |view_source_contents| during
5699 // AddNewContents method call.
5700}
5701
Lukasz Anforowiczd334bba2020-02-10 23:32:555702void WebContentsImpl::SubresourceResponseStarted(const GURL& url,
5703 net::CertStatus cert_status) {
Alexander Timin5fdeff22020-09-08 09:20:375704 OPTIONAL_TRACE_EVENT1("content",
5705 "WebContentsImpl::SubresourceResponseStarted", "url",
5706 base::trace_event::ValueToString(url));
Lukasz Anforowiczd334bba2020-02-10 23:32:555707 controller_.ssl_manager()->DidStartResourceResponse(url, cert_status);
Jay Civellid5904f02018-03-23 19:43:575708 SetNotWaitingForResponse();
5709}
5710
Jay Civelli116683f2018-03-27 19:56:235711void WebContentsImpl::ResourceLoadComplete(
Jay Civelli52a63302018-04-30 22:39:555712 RenderFrameHost* render_frame_host,
Clark DuVall36164bd2018-08-09 22:49:085713 const GlobalRequestID& request_id,
Minggang Wangee5af392020-02-05 02:55:285714 blink::mojom::ResourceLoadInfoPtr resource_load_info) {
Alexander Timin5fdeff22020-09-08 09:20:375715 OPTIONAL_TRACE_EVENT2(
5716 "content", "WebContentsImpl::ResourceLoadComplete", "render_frame_host",
5717 base::trace_event::ToTracedValue(render_frame_host), "request_id",
5718 base::trace_event::TracedValue::Build(
5719 {{"child_id", request_id.child_id},
5720 {"request_id", request_id.request_id}}));
Alexander Timin90c20c32020-08-12 15:28:325721 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5722 observer->ResourceLoadComplete(render_frame_host, request_id,
5723 *resource_load_info);
5724 });
John Abd-El-Malekd4882642017-12-04 21:45:195725}
5726
Gyuyoung Kim1ac4ca782020-09-11 03:32:515727const blink::web_pref::WebPreferences&
5728WebContentsImpl::GetOrCreateWebPreferences() {
Alexander Timin5fdeff22020-09-08 09:20:375729 OPTIONAL_TRACE_EVENT0("content",
5730 "WebContentsImpl::GetOrCreateWebPreferences");
Rakina Zata Amni347b70902020-07-22 10:49:045731 // Compute WebPreferences based on the current state if it's null.
5732 if (!web_preferences_)
Rakina Zata Amni4029b6d2020-07-28 02:36:205733 OnWebPreferencesChanged();
Rakina Zata Amni347b70902020-07-22 10:49:045734 return *web_preferences_.get();
5735}
5736
5737bool WebContentsImpl::IsWebPreferencesSet() const {
5738 return web_preferences_.get();
5739}
5740
Gyuyoung Kim1ac4ca782020-09-11 03:32:515741void WebContentsImpl::SetWebPreferences(
5742 const blink::web_pref::WebPreferences& prefs) {
Alexander Timin5fdeff22020-09-08 09:20:375743 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetWebPreferences");
Gyuyoung Kim1ac4ca782020-09-11 03:32:515744 web_preferences_ = std::make_unique<blink::web_pref::WebPreferences>(prefs);
Rakina Zata Amni347b70902020-07-22 10:49:045745 // Get all the RenderViewHosts (except the ones for currently back-forward
5746 // cached pages), and make them send the current WebPreferences
5747 // to the renderer. WebPreferences updates for back-forward cached pages will
5748 // be sent when we restore those pages from the back-forward cache.
5749 for (auto& rvh : frame_tree_.render_view_hosts()) {
5750 rvh.second->SendWebPreferencesToRenderer();
5751 }
5752}
5753
5754void WebContentsImpl::RecomputeWebPreferencesSlow() {
Alexander Timin5fdeff22020-09-08 09:20:375755 OPTIONAL_TRACE_EVENT0("content",
5756 "WebContentsImpl::RecomputeWebPreferencesSlow");
Rakina Zata Amni4029b6d2020-07-28 02:36:205757 // OnWebPreferencesChanged is a no-op when this is true.
5758 if (updating_web_preferences_)
5759 return;
Rakina Zata Amni347b70902020-07-22 10:49:045760 // Resets |web_preferences_| so that we won't have any cached value for slow
5761 // attributes (which won't get recomputed if we have pre-existing values for
5762 // them).
5763 web_preferences_.reset();
Rakina Zata Amni4029b6d2020-07-28 02:36:205764 OnWebPreferencesChanged();
Rakina Zata Amni347b70902020-07-22 10:49:045765}
5766
Wei Li5bb659742018-02-14 03:07:585767void WebContentsImpl::PrintCrossProcessSubframe(
5768 const gfx::Rect& rect,
5769 int document_cookie,
5770 RenderFrameHost* subframe_host) {
Alexander Timin5fdeff22020-09-08 09:20:375771 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::PrintCrossProcessSubframe",
5772 "subframe",
5773 base::trace_event::ToTracedValue(subframe_host));
Wei Li5c0b4d12018-03-22 15:05:225774 auto* outer_contents = GetOuterWebContents();
5775 if (outer_contents) {
5776 // When an extension or app page is printed, the content should be
5777 // composited with outer content, so the outer contents should handle the
5778 // print request.
5779 outer_contents->PrintCrossProcessSubframe(rect, document_cookie,
5780 subframe_host);
5781 return;
5782 }
5783
Wei Li5bb659742018-02-14 03:07:585784 // If there is no delegate such as in tests or during deletion, do nothing.
5785 if (!delegate_)
5786 return;
5787
5788 delegate_->PrintCrossProcessSubframe(this, rect, document_cookie,
5789 subframe_host);
5790}
5791
ckitagawa8695799b2020-02-05 16:08:495792void WebContentsImpl::CapturePaintPreviewOfCrossProcessSubframe(
5793 const gfx::Rect& rect,
5794 const base::UnguessableToken& guid,
5795 RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:375796 OPTIONAL_TRACE_EVENT1(
5797 "content", "WebContentsImpl::CapturePaintPreviewOfCrossProcessSubframe",
5798 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host));
ckitagawa8695799b2020-02-05 16:08:495799 if (!delegate_)
5800 return;
ckitagawac43ac982020-07-07 17:41:175801 delegate_->CapturePaintPreviewOfSubframe(this, rect, guid, render_frame_host);
ckitagawa8695799b2020-02-05 16:08:495802}
5803
rob.buis300b0872017-03-10 20:43:585804#if defined(OS_ANDROID)
5805base::android::ScopedJavaLocalRef<jobject>
5806WebContentsImpl::GetJavaRenderFrameHostDelegate() {
5807 return GetJavaWebContents();
5808}
5809#endif
5810
Hiroki Nakagawa39d1bbe2020-07-14 16:15:525811void WebContentsImpl::OnDidDisplayContentWithCertificateErrors() {
Alexander Timin5fdeff22020-09-08 09:20:375812 OPTIONAL_TRACE_EVENT0(
5813 "content", "WebContentsImpl::OnDidDisplayContentWithCertificateErrors");
estarkc2273502016-10-12 22:03:025814 controller_.ssl_manager()->DidDisplayContentWithCertErrors();
estark910b4572015-12-09 20:55:415815}
5816
5817void WebContentsImpl::OnDidRunContentWithCertificateErrors(
Zhuoyu Qian4353f7f2018-01-08 05:33:005818 RenderFrameHostImpl* source) {
Alexander Timin5fdeff22020-09-08 09:20:375819 OPTIONAL_TRACE_EVENT1(
5820 "content", "WebContentsImpl::OnDidRunContentWithCertificateErrors",
5821 "render_frame_host", base::trace_event::ToTracedValue(source));
Emily Starkabbdd662020-06-05 02:40:135822 // For RenderFrameHosts that are inactive and going to be discarded, we can
5823 // disregard this message; there's no need to update the UI if the UI will
5824 // never be shown again.
5825 //
5826 // We still process this message for speculative RenderFrameHosts. This can
5827 // happen when a subframe's main resource has a certificate error. The
5828 // currently committed navigation entry will get marked as having run insecure
5829 // content and that will carry over to the navigation entry for the
5830 // speculative RFH when it commits.
5831 if (source->lifecycle_state() !=
5832 RenderFrameHostImpl::LifecycleState::kSpeculative &&
5833 source->IsInactiveAndDisallowReactivation()) {
estarkaeda1422016-05-10 02:31:125834 return;
Emily Starkabbdd662020-06-05 02:40:135835 }
estarkcd2e30c2016-08-12 06:51:155836 controller_.ssl_manager()->DidRunContentWithCertErrors(
Emily Starkabbdd662020-06-05 02:40:135837 source->GetMainFrame()->GetLastCommittedOrigin().GetURL());
estark910b4572015-12-09 20:55:415838}
5839
Kouhei Ueno97e0990d2019-09-25 02:57:275840void WebContentsImpl::DOMContentLoaded(RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:375841 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DOMContentLoaded",
5842 "render_frame_host",
5843 base::trace_event::ToTracedValue(render_frame_host));
Alexander Timin90c20c32020-08-12 15:28:325844 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5845 observer->DOMContentLoaded(render_frame_host);
5846 });
[email protected]724159a2010-12-30 01:11:185847}
5848
Gyuyoung Kim525e0c5d2020-03-09 15:04:195849void WebContentsImpl::OnDidFinishLoad(RenderFrameHost* render_frame_host,
nicka0ac8382016-12-15 23:59:235850 const GURL& url) {
Alexander Timin5fdeff22020-09-08 09:20:375851 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnDidFinishLoad",
5852 "render_frame_host",
5853 base::trace_event::ToTracedValue(render_frame_host),
5854 "url", base::trace_event::ValueToString(url));
[email protected]8b3af1e2014-01-24 13:29:125855 GURL validated_url(url);
Gyuyoung Kim525e0c5d2020-03-09 15:04:195856 render_frame_host->GetProcess()->FilterURL(false, &validated_url);
[email protected]028053d42014-03-05 22:20:375857
Alexander Timin90c20c32020-08-12 15:28:325858 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5859 observer->DidFinishLoad(render_frame_host, validated_url);
5860 });
yilkal172da772019-11-06 22:49:075861 size_t tree_size = frame_tree_.root()->GetFrameTreeSize();
5862 if (max_loaded_frame_count_ < tree_size)
5863 max_loaded_frame_count_ = tree_size;
5864
Gyuyoung Kim525e0c5d2020-03-09 15:04:195865 if (!render_frame_host->GetParent())
yilkal172da772019-11-06 22:49:075866 UMA_HISTOGRAM_COUNTS_1000("Navigation.MainFrame.FrameCount", tree_size);
[email protected]1a55c5be2011-11-29 11:36:315867}
5868
Dave Tapuska549baab2019-03-19 15:52:405869void WebContentsImpl::OnGoToEntryAtOffset(RenderFrameHostImpl* source,
Julie Jeongeun Kim144f8192020-01-18 06:59:035870 int32_t offset,
Dave Tapuska043b94a2019-09-10 14:14:355871 bool has_user_gesture) {
Alexander Timin5fdeff22020-09-08 09:20:375872 OPTIONAL_TRACE_EVENT2(
5873 "content", "WebContentsImpl::OnGoToEntryAtOffset", "render_frame_host",
5874 base::trace_event::ToTracedValue(source), "offset", offset);
Arthur Sonzognia7d715a2018-09-20 16:11:135875 // Non-user initiated navigations coming from the renderer should be ignored
5876 // if there is an ongoing browser-initiated navigation.
5877 // See https://crbug.com/879965.
5878 // TODO(arthursonzogni): See if this should check for ongoing navigations in
5879 // the frame(s) affected by the session history navigation, rather than just
5880 // the main frame.
Kevin McNee96851e12020-07-16 03:43:225881 if (Navigator::ShouldIgnoreIncomingRendererRequest(
5882 frame_tree_.root()->navigation_request(), has_user_gesture))
5883 return;
Arthur Sonzognia7d715a2018-09-20 16:11:135884
nicka0ac8382016-12-15 23:59:235885 // All frames are allowed to navigate the global history.
Dave Tapuska8bfd84c2019-03-26 20:47:165886 if (!delegate_ || delegate_->OnGoToEntryOffset(offset)) {
arthursonzognib93a4472020-04-10 07:38:005887 if (source->IsSandboxed(network::mojom::WebSandboxFlags::kTopNavigation)) {
Dave Tapuska8bfd84c2019-03-26 20:47:165888 // Keep track of whether this is a session history from a sandboxed iframe
5889 // with top level navigation disallowed.
5890 controller_.GoToOffsetInSandboxedFrame(offset,
5891 source->GetFrameTreeNodeId());
5892 } else {
5893 controller_.GoToOffset(offset);
5894 }
5895 }
[email protected]216813952011-05-19 22:21:265896}
5897
Dave Tapuska4c02911b2020-02-14 22:52:075898void WebContentsImpl::OnPageScaleFactorChanged(RenderFrameHostImpl* source,
nicka0ac8382016-12-15 23:59:235899 float page_scale_factor) {
Alexander Timin5fdeff22020-09-08 09:20:375900 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnPageScaleFactorChanged",
5901 "render_frame_host",
5902 base::trace_event::ToTracedValue(source),
5903 "page_scale_factor", page_scale_factor);
mcnee336ea2c2017-05-23 22:50:595904#if !defined(OS_ANDROID)
5905 // While page scale factor is used on mobile, this PageScaleFactorIsOne logic
5906 // is only needed on desktop.
mcnee432e47d2015-11-09 19:37:465907 bool is_one = page_scale_factor == 1.f;
5908 if (is_one != page_scale_factor_is_one_) {
5909 page_scale_factor_is_one_ = is_one;
5910
5911 HostZoomMapImpl* host_zoom_map =
5912 static_cast<HostZoomMapImpl*>(HostZoomMap::GetForWebContents(this));
5913
nicka0ac8382016-12-15 23:59:235914 if (host_zoom_map) {
mcnee432e47d2015-11-09 19:37:465915 host_zoom_map->SetPageScaleFactorIsOneForView(
Dave Tapuska4c02911b2020-02-14 22:52:075916 source->GetProcess()->GetID(),
5917 source->GetRenderViewHost()->GetRoutingID(),
mcnee432e47d2015-11-09 19:37:465918 page_scale_factor_is_one_);
5919 }
5920 }
mcnee336ea2c2017-05-23 22:50:595921#endif // !defined(OS_ANDROID)
mcnee432e47d2015-11-09 19:37:465922
Alexander Timin90c20c32020-08-12 15:28:325923 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5924 observer->OnPageScaleFactorChanged(page_scale_factor);
5925 });
mcnee432e47d2015-11-09 19:37:465926}
5927
W. James MacLean62198672019-06-04 16:46:105928void WebContentsImpl::OnTextAutosizerPageInfoChanged(
Henrique Ferreiroba535472020-04-21 11:38:365929 RenderFrameHostImpl* source,
5930 blink::mojom::TextAutosizerPageInfoPtr page_info) {
Alexander Timin5fdeff22020-09-08 09:20:375931 OPTIONAL_TRACE_EVENT1(
5932 "content", "WebContentsImpl::OnTextAutosizerPageInfoChanged",
5933 "render_frame_host", base::trace_event::ToTracedValue(source));
W. James MacLean62198672019-06-04 16:46:105934 // Keep a copy of |page_info| in case we create a new RenderView before
5935 // the next update.
Henrique Ferreiroba535472020-04-21 11:38:365936 text_autosizer_page_info_.main_frame_width = page_info->main_frame_width;
5937 text_autosizer_page_info_.main_frame_layout_width =
5938 page_info->main_frame_layout_width;
5939 text_autosizer_page_info_.device_scale_adjustment =
5940 page_info->device_scale_adjustment;
Antonio Gomesda7e03d2020-08-05 15:03:085941
5942 auto remote_frames_broadcast_callback = base::BindRepeating(
5943 [](const blink::mojom::TextAutosizerPageInfo& page_info,
5944 RenderFrameProxyHost* proxy_host) {
5945 DCHECK(proxy_host);
5946 proxy_host->GetAssociatedRemoteMainFrame()->UpdateTextAutosizerPageInfo(
5947 page_info.Clone());
5948 },
5949 text_autosizer_page_info_);
5950
5951 frame_tree_.root()->render_manager()->ExecuteRemoteFramesBroadcastMethod(
5952 std::move(remote_frames_broadcast_callback), source->GetSiteInstance());
W. James MacLean62198672019-06-04 16:46:105953}
5954
Kent Tamura8c9e0562018-11-06 07:02:195955void WebContentsImpl::EnumerateDirectory(
5956 RenderFrameHost* render_frame_host,
Kent Tamura3abb32d2020-07-02 00:23:015957 scoped_refptr<FileChooserImpl::FileSelectListenerImpl> listener,
Kent Tamura8c9e0562018-11-06 07:02:195958 const base::FilePath& directory_path) {
Alexander Timin5fdeff22020-09-08 09:20:375959 OPTIONAL_TRACE_EVENT2(
5960 "content", "WebContentsImpl::EnumerateDirectory", "render_frame_host",
5961 base::trace_event::ToTracedValue(render_frame_host), "directory_path",
5962 base::trace_event::ValueToString(directory_path));
Avi Drissman1a55a9d62020-03-10 18:56:455963 // Any explicit focusing of another window while this WebContents is in
5964 // fullscreen can be used to confuse the user, so drop fullscreen.
5965 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
5966 listener->SetFullscreenBlock(std::move(fullscreen_block));
5967
Kent Tamura8c9e0562018-11-06 07:02:195968 if (delegate_)
5969 delegate_->EnumerateDirectory(this, std::move(listener), directory_path);
5970 else
5971 listener->FileSelectionCanceled();
[email protected]3a29a6e2011-08-24 18:26:215972}
5973
Dave Tapuskaf9fc3122019-10-18 19:42:555974void WebContentsImpl::RegisterProtocolHandler(RenderFrameHostImpl* source,
5975 const std::string& protocol,
5976 const GURL& url,
5977 const base::string16& title,
5978 bool user_gesture) {
Alexander Timin5fdeff22020-09-08 09:20:375979 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RegisterProtocolHandler",
5980 "render_frame_host",
5981 base::trace_event::ToTracedValue(source), "protocol",
5982 protocol);
nicka0ac8382016-12-15 23:59:235983 // TODO(nick): Do we need to apply FilterURL to |url|?
[email protected]e5f2de02012-07-20 22:15:435984 if (!delegate_)
5985 return;
5986
Raymes Khoury58373df2019-08-06 06:29:205987 if (!AreValidRegisterProtocolHandlerArguments(
5988 protocol, url, source->GetLastCommittedOrigin())) {
5989 ReceivedBadMessage(source->GetProcess(),
5990 bad_message::REGISTER_PROTOCOL_HANDLER_INVALID_URL);
[email protected]b9535422012-02-09 01:47:595991 return;
Raymes Khoury58373df2019-08-06 06:29:205992 }
[email protected]8f810632013-06-06 22:33:325993
Carlos Caballero8a6c6b72020-07-20 16:56:225994 delegate_->RegisterProtocolHandler(source, protocol, url, user_gesture);
[email protected]7d189022011-08-25 22:54:205995}
5996
Dave Tapuskaf9fc3122019-10-18 19:42:555997void WebContentsImpl::UnregisterProtocolHandler(RenderFrameHostImpl* source,
5998 const std::string& protocol,
5999 const GURL& url,
6000 bool user_gesture) {
Alexander Timin5fdeff22020-09-08 09:20:376001 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::UnregisterProtocolHandler",
6002 "render_frame_host",
6003 base::trace_event::ToTracedValue(source), "protocol",
6004 protocol);
nicka0ac8382016-12-15 23:59:236005 // TODO(nick): Do we need to apply FilterURL to |url|?
[email protected]f5273e52014-07-14 16:30:206006 if (!delegate_)
6007 return;
6008
Raymes Khoury58373df2019-08-06 06:29:206009 if (!AreValidRegisterProtocolHandlerArguments(
6010 protocol, url, source->GetLastCommittedOrigin())) {
6011 ReceivedBadMessage(source->GetProcess(),
6012 bad_message::REGISTER_PROTOCOL_HANDLER_INVALID_URL);
[email protected]f5273e52014-07-14 16:30:206013 return;
Raymes Khoury58373df2019-08-06 06:29:206014 }
[email protected]f5273e52014-07-14 16:30:206015
Carlos Caballero8a6c6b72020-07-20 16:56:226016 delegate_->UnregisterProtocolHandler(source, protocol, url, user_gesture);
[email protected]f5273e52014-07-14 16:30:206017}
6018
Marijn Kruisselbrink7f519672019-02-05 19:12:506019void WebContentsImpl::OnAppCacheAccessed(const GURL& manifest_url,
[email protected]b172aee2012-04-10 17:05:266020 bool blocked_by_policy) {
Alexander Timin5fdeff22020-09-08 09:20:376021 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnAppCacheAccessed");
nicka0ac8382016-12-15 23:59:236022 // TODO(nick): Should we consider |source| here? Should we call FilterURL on
6023 // |manifest_url|?
6024
[email protected]7fc4bbb2011-09-08 21:23:106025 // Notify observers about navigation.
Alexander Timin90c20c32020-08-12 15:28:326026 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6027 observer->AppCacheAccessed(manifest_url, blocked_by_policy);
6028 });
[email protected]7fc4bbb2011-09-08 21:23:106029}
6030
Gyuyoung Kimc5f4ac12020-05-08 10:59:396031void WebContentsImpl::DomOperationResponse(const std::string& json_string) {
Alexander Timin5fdeff22020-09-08 09:20:376032 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DomOperationResponse",
6033 "json_string", json_string);
6034
Gyuyoung Kimc5f4ac12020-05-08 10:59:396035 // TODO(lukasza): The notification below should probably indicate which
6036 // RenderFrameHostImpl the message is coming from. This can enable tests to
6037 // talk to 2 frames at the same time, without being confused which frame a
6038 // given response comes from. See also a corresponding TODO in the
6039 // ExecuteScriptHelper in //content/public/test/browser_test_utils.cc
6040 NotificationService::current()->Notify(
6041 NOTIFICATION_DOM_OPERATION_RESPONSE, Source<WebContents>(this),
6042 Details<const std::string>(&json_string));
6043}
6044
Gyuyoung Kim4c50517842020-06-04 17:50:446045void WebContentsImpl::SavableResourceLinksResponse(
6046 RenderFrameHostImpl* source,
6047 const std::vector<GURL>& resources_list,
6048 blink::mojom::ReferrerPtr referrer,
6049 const std::vector<blink::mojom::SavableSubframePtr>& subframes) {
Alexander Timin5fdeff22020-09-08 09:20:376050 OPTIONAL_TRACE_EVENT1(
6051 "content", "WebContentsImpl::SavableResourceLinksResponse",
6052 "render_frame_host", base::trace_event::ToTracedValue(source));
Gyuyoung Kim4c50517842020-06-04 17:50:446053 save_package_->SavableResourceLinksResponse(source, resources_list,
6054 std::move(referrer), subframes);
6055}
6056
6057void WebContentsImpl::SavableResourceLinksError(RenderFrameHostImpl* source) {
Alexander Timin5fdeff22020-09-08 09:20:376058 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SavableResourceLinksError",
6059 "render_frame_host",
6060 base::trace_event::ToTracedValue(source));
Gyuyoung Kim4c50517842020-06-04 17:50:446061 save_package_->SavableResourceLinksError(source);
6062}
6063
Alexander Timin17edc742020-04-23 18:22:186064void WebContentsImpl::OnServiceWorkerAccessed(
6065 RenderFrameHost* render_frame_host,
6066 const GURL& scope,
6067 AllowServiceWorkerResult allowed) {
Alexander Timin5fdeff22020-09-08 09:20:376068 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnServiceWorkerAccessed",
6069 "render_frame_host",
6070 base::trace_event::ToTracedValue(render_frame_host),
6071 "scope", base::trace_event::ValueToString(scope));
Alexander Timin90c20c32020-08-12 15:28:326072 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6073 observer->OnServiceWorkerAccessed(render_frame_host, scope, allowed);
6074 });
Alexander Timin17edc742020-04-23 18:22:186075}
6076
6077void WebContentsImpl::OnServiceWorkerAccessed(
6078 NavigationHandle* navigation,
6079 const GURL& scope,
6080 AllowServiceWorkerResult allowed) {
Alexander Timin5fdeff22020-09-08 09:20:376081 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnServiceWorkerAccessed",
6082 "navigation_handle", navigation, "scope",
6083 base::trace_event::ValueToString(scope));
Alexander Timin90c20c32020-08-12 15:28:326084 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6085 observer->OnServiceWorkerAccessed(navigation, scope, allowed);
6086 });
Alexander Timin17edc742020-04-23 18:22:186087}
6088
Miyoung Shincb6475a2019-11-09 10:49:456089void WebContentsImpl::OnColorChooserFactoryReceiver(
Julie Jeongeun Kim8e2879e2019-08-06 23:55:206090 mojo::PendingReceiver<blink::mojom::ColorChooserFactory> receiver) {
Alexander Timin5fdeff22020-09-08 09:20:376091 OPTIONAL_TRACE_EVENT0("content",
6092 "WebContentsImpl::OnColorChooserFactoryReceiver");
Julie Jeongeun Kim8e2879e2019-08-06 23:55:206093 color_chooser_factory_receivers_.Add(this, std::move(receiver));
Joel Hockey85b379d2017-12-11 10:42:136094}
6095
6096void WebContentsImpl::OpenColorChooser(
Julie Jeongeun Kim8e2879e2019-08-06 23:55:206097 mojo::PendingReceiver<blink::mojom::ColorChooser> chooser_receiver,
6098 mojo::PendingRemote<blink::mojom::ColorChooserClient> client,
[email protected]8ed16472014-04-11 19:02:486099 SkColor color,
Joel Hockey163835a2017-12-20 11:51:576100 std::vector<blink::mojom::ColorSuggestionPtr> suggestions) {
Alexander Timin5fdeff22020-09-08 09:20:376101 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OpenColorChooser");
Joel Hockey85b379d2017-12-11 10:42:136102 content::ColorChooser* new_color_chooser =
Ivan Kotenkov2c0d2bb32017-11-01 15:41:286103 delegate_ ? delegate_->OpenColorChooser(this, color, suggestions)
6104 : nullptr;
[email protected]820957a2014-01-14 14:56:306105 if (!new_color_chooser)
[email protected]cb805452013-05-22 15:16:216106 return;
[email protected]8ed16472014-04-11 19:02:486107
Joel Hockey85b379d2017-12-11 10:42:136108 color_chooser_.reset();
6109 color_chooser_ = std::make_unique<ColorChooser>(
Julie Jeongeun Kim8e2879e2019-08-06 23:55:206110 new_color_chooser, std::move(chooser_receiver), std::move(client));
[email protected]da8543762012-03-20 08:52:206111}
6112
brettw4b461082016-11-19 18:55:166113#if BUILDFLAG(ENABLE_PLUGINS)
nicka0ac8382016-12-15 23:59:236114void WebContentsImpl::OnPepperInstanceCreated(RenderFrameHostImpl* source,
6115 int32_t pp_instance) {
Alexander Timin5fdeff22020-09-08 09:20:376116 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPepperInstanceCreated",
6117 "render_frame_host",
6118 base::trace_event::ToTracedValue(source));
Alexander Timin90c20c32020-08-12 15:28:326119 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6120 observer->PepperInstanceCreated();
6121 });
nicka0ac8382016-12-15 23:59:236122 pepper_playback_observer_->PepperInstanceCreated(source, pp_instance);
emaxxe70f5e12015-05-29 11:26:006123}
6124
nicka0ac8382016-12-15 23:59:236125void WebContentsImpl::OnPepperInstanceDeleted(RenderFrameHostImpl* source,
6126 int32_t pp_instance) {
Alexander Timin5fdeff22020-09-08 09:20:376127 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPepperInstanceDeleted",
6128 "render_frame_host",
6129 base::trace_event::ToTracedValue(source));
Alexander Timin90c20c32020-08-12 15:28:326130 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6131 observer->PepperInstanceDeleted();
6132 });
nicka0ac8382016-12-15 23:59:236133 pepper_playback_observer_->PepperInstanceDeleted(source, pp_instance);
emaxxe70f5e12015-05-29 11:26:006134}
6135
nicka0ac8382016-12-15 23:59:236136void WebContentsImpl::OnPepperPluginHung(RenderFrameHostImpl* source,
6137 int plugin_child_id,
tommyclie6633ca72014-10-31 00:40:426138 const base::FilePath& path,
6139 bool is_hung) {
Alexander Timin5fdeff22020-09-08 09:20:376140 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPepperPluginHung",
6141 "render_frame_host",
6142 base::trace_event::ToTracedValue(source));
Steven Holte95922222018-09-14 20:06:236143 UMA_HISTOGRAM_COUNTS_1M("Pepper.PluginHung", 1);
tommyclie6633ca72014-10-31 00:40:426144
Alexander Timin90c20c32020-08-12 15:28:326145 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6146 observer->PluginHungStatusChanged(plugin_child_id, path, is_hung);
6147 });
tommyclie6633ca72014-10-31 00:40:426148}
6149
nicka0ac8382016-12-15 23:59:236150void WebContentsImpl::OnPepperStartsPlayback(RenderFrameHostImpl* source,
6151 int32_t pp_instance) {
Alexander Timin5fdeff22020-09-08 09:20:376152 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPepperStartsPlayback",
6153 "render_frame_host",
6154 base::trace_event::ToTracedValue(source));
nicka0ac8382016-12-15 23:59:236155 pepper_playback_observer_->PepperStartsPlayback(source, pp_instance);
zqzhang181047e62016-07-01 13:37:176156}
6157
nicka0ac8382016-12-15 23:59:236158void WebContentsImpl::OnPepperStopsPlayback(RenderFrameHostImpl* source,
6159 int32_t pp_instance) {
Alexander Timin5fdeff22020-09-08 09:20:376160 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPepperStopsPlayback",
6161 "render_frame_host",
6162 base::trace_event::ToTracedValue(source));
nicka0ac8382016-12-15 23:59:236163 pepper_playback_observer_->PepperStopsPlayback(source, pp_instance);
zqzhang181047e62016-07-01 13:37:176164}
6165
nicka0ac8382016-12-15 23:59:236166void WebContentsImpl::OnPluginCrashed(RenderFrameHostImpl* source,
6167 const base::FilePath& plugin_path,
tommyclie6633ca72014-10-31 00:40:426168 base::ProcessId plugin_pid) {
Alexander Timin5fdeff22020-09-08 09:20:376169 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPluginCrashed",
6170 "render_frame_host",
6171 base::trace_event::ToTracedValue(source));
nicka0ac8382016-12-15 23:59:236172 // TODO(nick): Eliminate the |plugin_pid| parameter, which can't be trusted,
Gyuyoung Kim26c7bc92020-04-29 00:53:006173 // and is only used by WebTestControlHost.
Alexander Timin90c20c32020-08-12 15:28:326174 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6175 observer->PluginCrashed(plugin_path, plugin_pid);
6176 });
tommyclie6633ca72014-10-31 00:40:426177}
6178
[email protected]d8415ad92012-08-23 14:40:506179void WebContentsImpl::OnRequestPpapiBrokerPermission(
nicka0ac8382016-12-15 23:59:236180 RenderViewHostImpl* source,
6181 int ppb_broker_route_id,
[email protected]d8415ad92012-08-23 14:40:506182 const GURL& url,
[email protected]2dec8ec2013-02-07 19:20:346183 const base::FilePath& plugin_path) {
Alexander Timin5fdeff22020-09-08 09:20:376184 OPTIONAL_TRACE_EVENT1("content",
6185 "WebContentsImpl::OnRequestPpapiBrokerPermission",
6186 "render_view_host", source);
Avi Drissman0a2a967d2019-04-01 19:33:526187 base::OnceCallback<void(bool)> permission_result_callback = base::BindOnce(
nicka0ac8382016-12-15 23:59:236188 &WebContentsImpl::SendPpapiBrokerPermissionResult, base::Unretained(this),
6189 source->GetProcess()->GetID(), ppb_broker_route_id);
[email protected]8c8fc292012-11-23 18:57:166190 if (!delegate_) {
Tommy Nyquist4b749d02018-03-20 21:46:296191 std::move(permission_result_callback).Run(false);
[email protected]8c8fc292012-11-23 18:57:166192 return;
[email protected]d8415ad92012-08-23 14:40:506193 }
6194
Avi Drissman0a2a967d2019-04-01 19:33:526195 delegate_->RequestPpapiBrokerPermission(
6196 this, url, plugin_path, std::move(permission_result_callback));
[email protected]d8415ad92012-08-23 14:40:506197}
6198
nicka0ac8382016-12-15 23:59:236199void WebContentsImpl::SendPpapiBrokerPermissionResult(int process_id,
6200 int ppb_broker_route_id,
6201 bool result) {
Alexander Timin5fdeff22020-09-08 09:20:376202 OPTIONAL_TRACE_EVENT2(
6203 "content", "WebContentsImpl::SendPpapiBrokerPermissionResult",
6204 "process_id", process_id, "ppb_broker_route_id", ppb_broker_route_id);
nicka0ac8382016-12-15 23:59:236205 RenderProcessHost* rph = RenderProcessHost::FromID(process_id);
6206 if (rph) {
6207 // TODO(nick): Convert this from ViewMsg_ to a Ppapi msg, since it
6208 // is not routed to a RenderView.
6209 rph->Send(
6210 new ViewMsg_PpapiBrokerPermissionResult(ppb_broker_route_id, result));
6211 }
[email protected]d8415ad92012-08-23 14:40:506212}
brettw4b461082016-11-19 18:55:166213#endif // BUILDFLAG(ENABLE_PLUGINS)
[email protected]19be7a62012-10-01 23:03:376214
Miyoung Shin5709ab02020-02-19 06:50:416215void WebContentsImpl::UpdateFaviconURL(
6216 RenderFrameHost* source,
6217 std::vector<blink::mojom::FaviconURLPtr> candidates) {
Alexander Timin5fdeff22020-09-08 09:20:376218 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::UpdateFaviconURL",
6219 "render_frame_host",
6220 base::trace_event::ToTracedValue(source));
lukasza178ff092017-06-07 23:39:506221 // Ignore favicons for non-main frame.
6222 if (source->GetParent()) {
6223 NOTREACHED();
6224 return;
6225 }
6226
pkotwiczf9bc20592015-04-21 18:57:066227 // We get updated favicon URLs after the page stops loading. If a cross-site
6228 // navigation occurs while a page is still loading, the initial page
6229 // may stop loading and send us updated favicon URLs after the navigation
6230 // for the new page has committed.
lukasza178ff092017-06-07 23:39:506231 if (!source->IsCurrent())
pkotwiczf9bc20592015-04-21 18:57:066232 return;
6233
Miyoung Shin5709ab02020-02-19 06:50:416234 favicon_urls_ = std::move(candidates);
Mounir Lamouri7b4a1f232019-12-23 16:32:106235
Alexander Timin90c20c32020-08-12 15:28:326236 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6237 observer->DidUpdateFaviconURL(source, favicon_urls_);
6238 });
[email protected]795c28972012-12-06 06:13:396239}
6240
qinmin72e8bd02016-10-21 19:35:376241void WebContentsImpl::SetIsOverlayContent(bool is_overlay_content) {
Alexander Timin5fdeff22020-09-08 09:20:376242 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetIsOverlayContent",
6243 "is_overlay_content", is_overlay_content);
qinmin72e8bd02016-10-21 19:35:376244 is_overlay_content_ = is_overlay_content;
6245}
6246
Albert J. Wongfb64e142018-10-16 01:10:456247void WebContentsImpl::DidFirstVisuallyNonEmptyPaint(
6248 RenderViewHostImpl* source) {
Alexander Timin5fdeff22020-09-08 09:20:376249 OPTIONAL_TRACE_EVENT1("content",
6250 "WebContentsImpl::DidFirstVisuallyNonEmptyPaint",
6251 "render_view_host", source);
nicka0ac8382016-12-15 23:59:236252 // TODO(nick): When this is ported to FrameHostMsg_, we should only listen if
6253 // |source| is the main frame.
Alexander Timin90c20c32020-08-12 15:28:326254 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6255 observer->DidFirstVisuallyNonEmptyPaint();
6256 });
Carlos Caballero1215f882019-10-29 15:58:436257 if (source->theme_color() != last_sent_theme_color_) {
yusufod41c5f92015-03-06 00:14:286258 // Theme color should have updated by now if there was one.
Alexander Timin90c20c32020-08-12 15:28:326259 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6260 observer->DidChangeThemeColor();
6261 });
Carlos Caballero1215f882019-10-29 15:58:436262 last_sent_theme_color_ = source->theme_color();
yusufod41c5f92015-03-06 00:14:286263 }
Alan Cutterd73a15d92020-08-21 07:12:456264
6265 if (source->background_color() != last_sent_background_color_) {
6266 // Background color should have updated by now if there was one.
6267 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6268 observer->OnBackgroundColorChanged();
6269 });
6270 last_sent_background_color_ = source->background_color();
6271 }
[email protected]9f268072013-11-07 00:02:156272}
[email protected]d9030b82013-07-19 08:26:066273
Kevin McNee068c3eb2020-04-03 18:24:196274bool WebContentsImpl::IsPortal() {
Adithya Srinivasan46b8a792019-02-01 14:47:236275 return portal();
6276}
6277
Kevin McNee94ea52f52020-06-23 17:42:066278WebContentsImpl* WebContentsImpl::GetPortalHostWebContents() {
6279 return portal() ? portal()->GetPortalHostContents() : nullptr;
6280}
6281
[email protected]17e286e2013-03-01 23:29:396282void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
Alexander Timin5fdeff22020-09-08 09:20:376283 OPTIONAL_TRACE_EVENT0("content",
6284 "WebContentsImpl::NotifyBeforeFormRepostWarningShow");
Alexander Timin90c20c32020-08-12 15:28:326285 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6286 observer->BeforeFormRepostWarningShow();
6287 });
[email protected]17e286e2013-03-01 23:29:396288}
6289
[email protected]ec6c05f2013-10-23 18:41:576290void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
Alexander Timin5fdeff22020-09-08 09:20:376291 OPTIONAL_TRACE_EVENT0(
6292 "content", "WebContentsImpl::ActivateAndShowRepostFormWarningDialog");
[email protected]ec6c05f2013-10-23 18:41:576293 Activate();
6294 if (delegate_)
6295 delegate_->ShowRepostFormWarningDialog(this);
6296}
6297
[email protected]b4c84012014-04-28 19:51:106298bool WebContentsImpl::HasAccessedInitialDocument() {
6299 return has_accessed_initial_document_;
6300}
6301
afakhry6f0c1ec22016-07-14 13:55:136302void WebContentsImpl::UpdateTitleForEntry(NavigationEntry* entry,
[email protected]fcf75d42013-12-03 20:11:266303 const base::string16& title) {
Alexander Timin5fdeff22020-09-08 09:20:376304 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::UpdateTitleForEntry",
6305 "title", base::trace_event::ValueToString(title));
[email protected]fcf75d42013-12-03 20:11:266306 base::string16 final_title;
Avi Drissman93002212017-09-27 03:20:526307 base::TrimWhitespace(title, base::TRIM_ALL, &final_title);
[email protected]420ae012009-04-24 05:16:326308
[email protected]987fc3a2011-05-26 14:18:096309 // If a page is created via window.open and never navigated,
6310 // there will be no navigation entry. In this situation,
[email protected]73eb2602012-02-09 19:50:556311 // |page_title_when_no_navigation_entry_| will be used for page title.
[email protected]987fc3a2011-05-26 14:18:096312 if (entry) {
[email protected]36fc0392011-12-25 03:59:516313 if (final_title == entry->GetTitle())
afakhry6f0c1ec22016-07-14 13:55:136314 return; // Nothing changed, don't bother.
[email protected]420ae012009-04-24 05:16:326315
[email protected]36fc0392011-12-25 03:59:516316 entry->SetTitle(final_title);
Avi Drissman93002212017-09-27 03:20:526317
6318 // The title for display may differ from the title just set; grab it.
6319 final_title = entry->GetTitleForDisplay();
[email protected]987fc3a2011-05-26 14:18:096320 } else {
6321 if (page_title_when_no_navigation_entry_ == final_title)
afakhry6f0c1ec22016-07-14 13:55:136322 return; // Nothing changed, don't bother.
[email protected]987fc3a2011-05-26 14:18:096323
6324 page_title_when_no_navigation_entry_ = final_title;
6325 }
[email protected]420ae012009-04-24 05:16:326326
[email protected]420ae012009-04-24 05:16:326327 // Lastly, set the title for the view.
[email protected]790e2fd2011-09-21 20:28:236328 view_->SetPageTitle(final_title);
[email protected]420ae012009-04-24 05:16:326329
Alexander Timin90c20c32020-08-12 15:28:326330 observers_.ForEachObserver(
6331 [&](WebContentsObserver* observer) { observer->TitleWasSet(entry); });
afakhry6f0c1ec22016-07-14 13:55:136332 // Broadcast notifications when the UI should be updated.
6333 if (entry == controller_.GetEntryAtOffset(0))
6334 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE);
[email protected]420ae012009-04-24 05:16:326335}
6336
fdegansa696e5112015-04-17 01:57:596337void WebContentsImpl::SendChangeLoadProgress() {
Alexander Timin5fdeff22020-09-08 09:20:376338 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SendChangeLoadProgress",
6339 "load_progress", frame_tree_.load_progress());
[email protected]960b0372014-05-19 18:01:006340 loading_last_progress_update_ = base::TimeTicks::Now();
Alexander Timin90c20c32020-08-12 15:28:326341 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6342 observer->LoadProgressChanged(frame_tree_.load_progress());
6343 });
[email protected]960b0372014-05-19 18:01:006344}
6345
6346void WebContentsImpl::ResetLoadProgressState() {
Alexander Timin5fdeff22020-09-08 09:20:376347 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ResetLoadProgressState");
fdegans1d16355162015-03-26 11:58:346348 frame_tree_.ResetLoadProgress();
[email protected]960b0372014-05-19 18:01:006349 loading_weak_factory_.InvalidateWeakPtrs();
6350 loading_last_progress_update_ = base::TimeTicks();
6351}
6352
clamy44e84ce2016-02-22 15:38:256353// Notifies the RenderWidgetHost instance about the fact that the page is
6354// loading, or done loading.
6355void WebContentsImpl::LoadingStateChanged(bool to_different_document,
clamy44e84ce2016-02-22 15:38:256356 LoadNotificationDetails* details) {
Nate Chapin22ea6592019-03-05 22:29:026357 if (is_being_destroyed_)
6358 return;
clamy44e84ce2016-02-22 15:38:256359
6360 bool is_loading = IsLoading();
6361
Alexander Timin5fdeff22020-09-08 09:20:376362 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::LoadingStateChanged",
6363 "is_loading", is_loading);
6364
clamy44e84ce2016-02-22 15:38:256365 if (!is_loading) {
6366 load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
6367 base::string16());
6368 load_state_host_.clear();
6369 upload_size_ = 0;
6370 upload_position_ = 0;
6371 }
6372
6373 GetRenderManager()->SetIsLoading(is_loading);
6374
6375 waiting_for_response_ = is_loading;
6376 is_load_to_different_document_ = to_different_document;
6377
6378 if (delegate_)
6379 delegate_->LoadingStateChanged(this, to_different_document);
6380 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD);
6381
6382 std::string url = (details ? details->url.possibly_invalid_spec() : "NULL");
6383 if (is_loading) {
6384 TRACE_EVENT_ASYNC_BEGIN2("browser,navigation", "WebContentsImpl Loading",
6385 this, "URL", url, "Main FrameTreeNode id",
6386 GetFrameTree()->root()->frame_tree_node_id());
Alexander Timin90c20c32020-08-12 15:28:326387 observers_.ForEachObserver(
6388 [&](WebContentsObserver* observer) { observer->DidStartLoading(); });
clamy44e84ce2016-02-22 15:38:256389 } else {
6390 TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
6391 this, "URL", url);
Alexander Timin90c20c32020-08-12 15:28:326392 observers_.ForEachObserver(
6393 [&](WebContentsObserver* observer) { observer->DidStopLoading(); });
clamy44e84ce2016-02-22 15:38:256394 }
6395
6396 // TODO(avi): Remove. http://crbug.com/170921
6397 int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP;
6398 NotificationDetails det = NotificationService::NoDetails();
6399 if (details)
6400 det = Details<LoadNotificationDetails>(details);
6401 NotificationService::current()->Notify(
6402 type, Source<NavigationController>(&controller_), det);
6403}
6404
danakja0bce4c952020-05-12 20:40:286405void WebContentsImpl::NotifyViewSwapped(RenderViewHost* old_view,
6406 RenderViewHost* new_view) {
Alexander Timin5fdeff22020-09-08 09:20:376407 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::NotifyViewSwapped",
6408 "old_view", old_view, "new_view", new_view);
danakja0bce4c952020-05-12 20:40:286409 DCHECK_NE(old_view, new_view);
[email protected]420ae012009-04-24 05:16:326410 // After sending out a swap notification, we need to send a disconnect
6411 // notification so that clients that pick up a pointer to |this| can NULL the
6412 // pointer. See Bug 1230284.
6413 notify_disconnection_ = true;
Alexander Timin90c20c32020-08-12 15:28:326414 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6415 observer->RenderViewHostChanged(old_view, new_view);
6416 });
danakja0bce4c952020-05-12 20:40:286417 view_->RenderViewHostChanged(old_view, new_view);
Jinsuk Kimdc5284c22018-07-11 02:22:066418
Lucas Furukawa Gadanif9ea4fc2018-08-03 23:57:136419 // If this is an inner WebContents that has swapped views, we need to reattach
6420 // it to its outer WebContents.
6421 if (node_.outer_web_contents())
6422 ReattachToOuterWebContentsFrame();
6423
[email protected]7a846df2012-09-20 19:17:396424 // Ensure that the associated embedder gets cleared after a RenderViewHost
6425 // gets swapped, so we don't reuse the same embedder next time a
6426 // RenderViewHost is attached to this WebContents.
6427 RemoveBrowserPluginEmbedder();
[email protected]420ae012009-04-24 05:16:326428}
6429
danakja0bce4c952020-05-12 20:40:286430void WebContentsImpl::NotifyFrameSwapped(RenderFrameHost* old_frame,
6431 RenderFrameHost* new_frame,
Jinsuk Kim895b2c52018-07-03 06:49:166432 bool is_main_frame) {
Alexander Timin5fdeff22020-09-08 09:20:376433 TRACE_EVENT2("content", "WebContentsImpl::NotifyFrameSwapped", "old_frame",
6434 base::trace_event::ToTracedValue(old_frame), "new_frame",
6435 base::trace_event::ToTracedValue(new_frame));
Bo Liu168c8642017-08-28 18:26:026436#if defined(OS_ANDROID)
danakja0bce4c952020-05-12 20:40:286437 // Copy importance from |old_frame| if |new_frame| is a main frame.
6438 if (old_frame && !new_frame->GetParent()) {
6439 RenderWidgetHostImpl* old_widget =
6440 static_cast<RenderFrameHostImpl*>(old_frame)->GetRenderWidgetHost();
6441 RenderWidgetHostImpl* new_widget =
6442 static_cast<RenderFrameHostImpl*>(new_frame)->GetRenderWidgetHost();
6443 new_widget->SetImportance(old_widget->importance());
Bo Liu7c6779e92017-08-16 02:02:286444 }
Bo Liu168c8642017-08-28 18:26:026445#endif
Alexander Timin90c20c32020-08-12 15:28:326446 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6447 observer->RenderFrameHostChanged(old_frame, new_frame);
6448 });
[email protected]02d7b6e2014-06-24 21:01:506449}
6450
[email protected]da7a7182013-09-06 08:11:116451// TODO(avi): Remove this entire function because this notification is already
6452// covered by two observer functions. http://crbug.com/170921
[email protected]b172aee2012-04-10 17:05:266453void WebContentsImpl::NotifyDisconnected() {
Alexander Timin5fdeff22020-09-08 09:20:376454 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::NotifyDisconnected");
[email protected]420ae012009-04-24 05:16:326455 if (!notify_disconnection_)
6456 return;
6457
6458 notify_disconnection_ = false;
[email protected]8ff00d72012-10-23 19:12:216459 NotificationService::current()->Notify(
6460 NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
6461 Source<WebContents>(this),
6462 NotificationService::NoDetails());
[email protected]420ae012009-04-24 05:16:326463}
6464
[email protected]cbb1ef592013-06-05 19:49:466465void WebContentsImpl::NotifyNavigationEntryCommitted(
6466 const LoadCommittedDetails& load_details) {
Alexander Timin5fdeff22020-09-08 09:20:376467 OPTIONAL_TRACE_EVENT0("content",
6468 "WebContentsImpl::NotifyNavigationEntryCommitted");
Alexander Timin90c20c32020-08-12 15:28:326469 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6470 observer->NavigationEntryCommitted(load_details);
6471 });
[email protected]cbb1ef592013-06-05 19:49:466472}
6473
Sam McNally5c087a32017-08-25 01:46:146474void WebContentsImpl::NotifyNavigationEntryChanged(
6475 const EntryChangedDetails& change_details) {
Alexander Timin5fdeff22020-09-08 09:20:376476 OPTIONAL_TRACE_EVENT0("content",
6477 "WebContentsImpl::NotifyNavigationEntryChanged");
Alexander Timin90c20c32020-08-12 15:28:326478 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6479 observer->NavigationEntryChanged(change_details);
6480 });
Sam McNally5c087a32017-08-25 01:46:146481}
6482
6483void WebContentsImpl::NotifyNavigationListPruned(
6484 const PrunedDetails& pruned_details) {
Alexander Timin5fdeff22020-09-08 09:20:376485 OPTIONAL_TRACE_EVENT0("content",
6486 "WebContentsImpl::NotifyNavigationListPruned");
Alexander Timin90c20c32020-08-12 15:28:326487 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6488 observer->NavigationListPruned(pruned_details);
6489 });
Sam McNally5c087a32017-08-25 01:46:146490}
6491
Christian Dullweber1af31e62018-02-22 11:49:486492void WebContentsImpl::NotifyNavigationEntriesDeleted() {
Alexander Timin5fdeff22020-09-08 09:20:376493 OPTIONAL_TRACE_EVENT0("content",
6494 "WebContentsImpl::NotifyNavigationEntriesDeleted");
Alexander Timin90c20c32020-08-12 15:28:326495 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6496 observer->NavigationEntriesDeleted();
6497 });
Christian Dullweber1af31e62018-02-22 11:49:486498}
6499
rockotf62002a2016-09-15 00:08:596500void WebContentsImpl::OnAssociatedInterfaceRequest(
6501 RenderFrameHost* render_frame_host,
6502 const std::string& interface_name,
6503 mojo::ScopedInterfaceEndpointHandle handle) {
Alexander Timin5fdeff22020-09-08 09:20:376504 OPTIONAL_TRACE_EVENT2(
6505 "content", "WebContentsImpl::OnAssociatedInterfaceRequest",
6506 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host),
6507 "interface_name", interface_name);
Julie Jeongeun Kim7d0986172019-12-04 03:17:256508 auto it = receiver_sets_.find(interface_name);
6509 if (it != receiver_sets_.end())
6510 it->second->OnReceiverForFrame(render_frame_host, std::move(handle));
rockotf62002a2016-09-15 00:08:596511}
6512
Ben Goodger9e24929e2017-07-21 03:13:406513void WebContentsImpl::OnInterfaceRequest(
6514 RenderFrameHost* render_frame_host,
6515 const std::string& interface_name,
6516 mojo::ScopedMessagePipeHandle* interface_pipe) {
Alexander Timin5fdeff22020-09-08 09:20:376517 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnInterfaceRequest",
6518 "render_frame_host",
6519 base::trace_event::ToTracedValue(render_frame_host),
6520 "interface_name", interface_name);
Alexander Timin90c20c32020-08-12 15:28:326521 for (auto& observer : observers_.observer_list()) {
Ben Goodger9e24929e2017-07-21 03:13:406522 observer.OnInterfaceRequestFromFrame(render_frame_host, interface_name,
6523 interface_pipe);
6524 if (!interface_pipe->is_valid())
6525 break;
6526 }
6527}
6528
Varun Khaneja5da94302019-06-25 04:48:106529void WebContentsImpl::OnDidBlockNavigation(
6530 const GURL& blocked_url,
6531 const GURL& initiator_url,
Abhijeet Kandalkarde7348e2020-01-13 06:06:546532 blink::mojom::NavigationBlockedReason reason) {
Alexander Timin5fdeff22020-09-08 09:20:376533 OPTIONAL_TRACE_EVENT1(
6534 "content", "WebContentsImpl::OnDidBlockNavigation", "details",
6535 base::trace_event::TracedValue::Build(
6536 {{"blocked_url", base::trace_event::ValueToString(blocked_url)},
6537 {"initiator_url", base::trace_event::ValueToString(initiator_url)},
6538 {"reason", base::trace_event::ValueToString(reason)}}));
Nicolas Dossou-gbetebcab2472017-09-09 12:28:406539 if (delegate_)
Varun Khaneja5da94302019-06-25 04:48:106540 delegate_->OnDidBlockNavigation(this, blocked_url, initiator_url, reason);
Nicolas Dossou-gbetebcab2472017-09-09 12:28:406541}
6542
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416543const GURL& WebContentsImpl::GetMainFrameLastCommittedURL() {
[email protected]c31a84802014-04-03 15:55:496544 return GetLastCommittedURL();
6545}
6546
[email protected]b849847b2013-12-10 21:57:586547void WebContentsImpl::RenderFrameCreated(RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:376548 TRACE_EVENT1("content", "WebContentsImpl::RenderFrameCreated",
6549 "render_frame_host", render_frame_host);
Alexander Timin90c20c32020-08-12 15:28:326550 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6551 observer->RenderFrameCreated(render_frame_host);
6552 });
dmazzonif8a31042016-12-03 00:52:136553 UpdateAccessibilityModeOnFrame(render_frame_host);
clamy91b7abf2016-03-24 15:17:456554
Becca Hughesd11d6502018-07-31 17:01:286555 if (display_cutout_host_impl_)
6556 display_cutout_host_impl_->RenderFrameCreated(render_frame_host);
6557
clamy91b7abf2016-03-24 15:17:456558 if (!render_frame_host->IsRenderFrameLive() || render_frame_host->GetParent())
6559 return;
6560
6561 NavigationEntry* entry = controller_.GetPendingEntry();
6562 if (entry && entry->IsViewSourceMode()) {
6563 // Put the renderer in view source mode.
Dave Tapuska3c05e1c2019-11-27 18:34:186564 static_cast<RenderFrameHostImpl*>(render_frame_host)
6565 ->GetAssociatedLocalFrame()
6566 ->EnableViewSourceMode();
clamy91b7abf2016-03-24 15:17:456567 }
[email protected]b849847b2013-12-10 21:57:586568}
6569
6570void WebContentsImpl::RenderFrameDeleted(RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:376571 TRACE_EVENT1("content", "WebContentsImpl::RenderFrameDeleted",
6572 "render_frame_host",
6573 base::trace_event::ToTracedValue(render_frame_host));
yilkal172da772019-11-06 22:49:076574 if (IsBeingDestroyed() && !render_frame_host->GetParent() &&
6575 first_navigation_completed_ &&
Hajime Hoshibbc509c2020-04-06 08:55:086576 !render_frame_host->IsInBackForwardCache()) {
yilkal796e89e2019-10-02 23:58:286577 // Main frame has been deleted because WebContents is being destroyed.
Rakina Zata Amni74627df2019-10-15 02:03:176578 // Note that we aren't recording this here when the main frame is in the
6579 // back-forward cache because that means we've actually already navigated
6580 // away from it (and we got to this point because the WebContents is
yilkal172da772019-11-06 22:49:076581 // deleted), which means |max_loaded_frame_count_| is already overwritten.
6582 // The |max_loaded_frame_count_| value will instead be recorded from within
6583 // |WebContentsImpl::DidFinishNavigation()|.
6584 RecordMaxFrameCountUMA(max_loaded_frame_count_);
yilkal796e89e2019-10-02 23:58:286585 }
6586
Alexander Timin90c20c32020-08-12 15:28:326587 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6588 observer->RenderFrameDeleted(render_frame_host);
6589 });
zqzhang7b6f4f02016-12-07 22:10:226590#if BUILDFLAG(ENABLE_PLUGINS)
6591 pepper_playback_observer_->RenderFrameDeleted(render_frame_host);
6592#endif
Becca Hughesfd5d8f892018-06-14 18:23:366593
Becca Hughesd11d6502018-07-31 17:01:286594 if (display_cutout_host_impl_)
6595 display_cutout_host_impl_->RenderFrameDeleted(render_frame_host);
6596
Becca Hughesfd5d8f892018-06-14 18:23:366597 // Remove any fullscreen state that the frame has stored.
6598 FullscreenStateChanged(render_frame_host, false /* is_fullscreen */);
[email protected]b849847b2013-12-10 21:57:586599}
6600
[email protected]a09d53ce2014-01-31 00:46:426601void WebContentsImpl::ShowContextMenu(RenderFrameHost* render_frame_host,
6602 const ContextMenuParams& params) {
Alexander Timin5fdeff22020-09-08 09:20:376603 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ShowContextMenu",
6604 "render_frame_host",
6605 base::trace_event::ToTracedValue(render_frame_host));
avie9fd8722017-04-10 16:17:586606 // If a renderer fires off a second command to show a context menu before the
6607 // first context menu is closed, just ignore it. https://crbug.com/707534
ekaramadf6750aa2017-06-06 18:29:426608 if (showing_context_menu_)
avie9fd8722017-04-10 16:17:586609 return;
6610
[email protected]077e704b2014-05-23 19:24:106611 ContextMenuParams context_menu_params(params);
[email protected]a09d53ce2014-01-31 00:46:426612 // Allow WebContentsDelegates to handle the context menu operation first.
Joel Klinghed0ea22ea2019-02-20 22:04:226613 if (delegate_ &&
6614 delegate_->HandleContextMenu(render_frame_host, context_menu_params))
[email protected]a09d53ce2014-01-31 00:46:426615 return;
6616
[email protected]077e704b2014-05-23 19:24:106617 render_view_host_delegate_view_->ShowContextMenu(render_frame_host,
6618 context_menu_params);
[email protected]a09d53ce2014-01-31 00:46:426619}
6620
Avi Drissman4891b852018-09-25 18:12:586621namespace {
6622// Normalizes the line endings: \r\n -> \n, lone \r -> \n.
6623base::string16 NormalizeLineBreaks(const base::string16& source) {
6624 static const base::NoDestructor<base::string16> kReturnNewline(
6625 base::ASCIIToUTF16("\r\n"));
6626 static const base::NoDestructor<base::string16> kReturn(
6627 base::ASCIIToUTF16("\r"));
6628 static const base::NoDestructor<base::string16> kNewline(
6629 base::ASCIIToUTF16("\n"));
6630
6631 std::vector<base::StringPiece16> pieces;
6632
6633 for (const auto& rn_line : base::SplitStringPieceUsingSubstr(
6634 source, *kReturnNewline, base::KEEP_WHITESPACE,
6635 base::SPLIT_WANT_ALL)) {
6636 auto r_lines = base::SplitStringPieceUsingSubstr(
6637 rn_line, *kReturn, base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
6638 std::move(std::begin(r_lines), std::end(r_lines),
6639 std::back_inserter(pieces));
6640 }
6641
6642 return base::JoinString(pieces, *kNewline);
6643}
6644} // namespace
6645
Dave Tapuskacdf545cc2020-01-23 18:38:526646void WebContentsImpl::RunJavaScriptDialog(
6647 RenderFrameHost* render_frame_host,
6648 const base::string16& message,
6649 const base::string16& default_prompt,
6650 JavaScriptDialogType dialog_type,
6651 JavaScriptDialogCallback response_callback) {
Alexander Timin5fdeff22020-09-08 09:20:376652 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RunJavaScriptDialog",
6653 "render_frame_host",
6654 base::trace_event::ToTracedValue(render_frame_host));
Avi Drissman2ccbb402018-03-20 21:11:366655 // Ensure that if showing a dialog is the first thing that a page does, that
6656 // the contents of the previous page aren't shown behind it. This is required
6657 // because showing a dialog freezes the renderer, so no frames will be coming
6658 // from it. https://crbug.com/823353
6659 auto* render_widget_host_impl =
6660 static_cast<RenderFrameHostImpl*>(render_frame_host)
6661 ->GetRenderWidgetHost();
6662 if (render_widget_host_impl)
6663 render_widget_host_impl->ForceFirstFrameAfterNavigationTimeout();
6664
avi0720b02e2017-06-13 03:22:136665 // Running a dialog causes an exit to webpage-initiated fullscreen.
6666 // http://crbug.com/728276
Avi Drissman1a55a9d62020-03-10 18:56:456667 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
avi0720b02e2017-06-13 03:22:136668
Avi Drissman1a55a9d62020-03-10 18:56:456669 auto callback =
6670 base::BindOnce(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
6671 render_frame_host->GetProcess()->GetID(),
6672 render_frame_host->GetRoutingID(),
6673 std::move(response_callback), std::move(fullscreen_block));
Pavel Feldman3c1842b2017-08-02 05:00:166674
Pavel Feldman3c1842b2017-08-02 05:00:166675 std::vector<protocol::PageHandler*> page_handlers =
6676 protocol::PageHandler::EnabledForWebContents(this);
6677
Pavel Feldmanfab3cb62017-10-05 01:02:016678 if (delegate_)
6679 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
6680
Charlie Reis96077362019-07-04 00:34:046681 // While a JS message dialog is showing, defer commits in this WebContents.
6682 javascript_dialog_navigation_deferrer_ =
6683 std::make_unique<JavaScriptDialogNavigationDeferrer>();
6684
Carlos IL07f282f2020-05-15 22:58:296685 // Suppress JavaScript dialogs when requested.
6686 bool should_suppress = delegate_ && delegate_->ShouldSuppressDialogs(this);
Pavel Feldman1c587bc52018-04-04 21:16:056687 bool has_non_devtools_handlers = delegate_ && dialog_manager_;
6688 bool has_handlers = page_handlers.size() || has_non_devtools_handlers;
Pavel Feldmanfab3cb62017-10-05 01:02:016689 bool suppress_this_message = should_suppress || !has_handlers;
6690
6691 if (suppress_this_message) {
Avi Drissmane04d3992017-10-05 15:11:366692 std::move(callback).Run(true, false, base::string16());
Pavel Feldman3c1842b2017-08-02 05:00:166693 return;
6694 }
6695
6696 scoped_refptr<CloseDialogCallbackWrapper> wrapper =
Avi Drissmane04d3992017-10-05 15:11:366697 new CloseDialogCallbackWrapper(std::move(callback));
Pavel Feldman3c1842b2017-08-02 05:00:166698
6699 is_showing_javascript_dialog_ = true;
6700
Avi Drissman4891b852018-09-25 18:12:586701 base::string16 normalized_message = NormalizeLineBreaks(message);
6702
Pavel Feldman3c1842b2017-08-02 05:00:166703 for (auto* handler : page_handlers) {
Avi Drissmane04d3992017-10-05 15:11:366704 handler->DidRunJavaScriptDialog(
Avi Drissman4891b852018-09-25 18:12:586705 render_frame_host->GetLastCommittedURL(), normalized_message,
6706 default_prompt, dialog_type, has_non_devtools_handlers,
Avi Drissmane04d3992017-10-05 15:11:366707 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
Pavel Feldman3c1842b2017-08-02 05:00:166708 }
6709
6710 if (dialog_manager_) {
[email protected]87de04b02014-04-08 22:14:496711 dialog_manager_->RunJavaScriptDialog(
Avi Drissman4891b852018-09-25 18:12:586712 this, render_frame_host, dialog_type, normalized_message,
6713 default_prompt,
Avi Drissmane04d3992017-10-05 15:11:366714 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false),
6715 &suppress_this_message);
[email protected]87de04b02014-04-08 22:14:496716 }
6717
6718 if (suppress_this_message) {
6719 // If we are suppressing messages, just reply as if the user immediately
6720 // pressed "Cancel", passing true to |dialog_was_suppressed|.
Avi Drissmane04d3992017-10-05 15:11:366721 wrapper->Run(true, false, base::string16());
[email protected]87de04b02014-04-08 22:14:496722 }
[email protected]87de04b02014-04-08 22:14:496723}
6724
6725void WebContentsImpl::RunBeforeUnloadConfirm(
[email protected]39f2f9252014-05-03 00:54:016726 RenderFrameHost* render_frame_host,
[email protected]87de04b02014-04-08 22:14:496727 bool is_reload,
Dave Tapuskacdf545cc2020-01-23 18:38:526728 JavaScriptDialogCallback response_callback) {
Alexander Timin5fdeff22020-09-08 09:20:376729 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RunBeforeUnloadConfirm",
6730 "render_frame_host",
6731 base::trace_event::ToTracedValue(render_frame_host),
6732 "is_reload", is_reload);
Avi Drissman2ccbb402018-03-20 21:11:366733 // Ensure that if showing a dialog is the first thing that a page does, that
6734 // the contents of the previous page aren't shown behind it. This is required
6735 // because showing a dialog freezes the renderer, so no frames will be coming
6736 // from it. https://crbug.com/823353
6737 auto* render_widget_host_impl =
6738 static_cast<RenderFrameHostImpl*>(render_frame_host)
6739 ->GetRenderWidgetHost();
6740 if (render_widget_host_impl)
6741 render_widget_host_impl->ForceFirstFrameAfterNavigationTimeout();
6742
avi0720b02e2017-06-13 03:22:136743 // Running a dialog causes an exit to webpage-initiated fullscreen.
6744 // http://crbug.com/728276
Avi Drissman1a55a9d62020-03-10 18:56:456745 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
avi0720b02e2017-06-13 03:22:136746
[email protected]39f2f9252014-05-03 00:54:016747 RenderFrameHostImpl* rfhi =
6748 static_cast<RenderFrameHostImpl*>(render_frame_host);
[email protected]87de04b02014-04-08 22:14:496749 if (delegate_)
6750 delegate_->WillRunBeforeUnloadConfirm();
6751
Avi Drissman1a55a9d62020-03-10 18:56:456752 auto callback =
6753 base::BindOnce(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
6754 render_frame_host->GetProcess()->GetID(),
6755 render_frame_host->GetRoutingID(),
6756 std::move(response_callback), std::move(fullscreen_block));
Pavel Feldman3c1842b2017-08-02 05:00:166757
Pavel Feldman3c1842b2017-08-02 05:00:166758 std::vector<protocol::PageHandler*> page_handlers =
6759 protocol::PageHandler::EnabledForWebContents(this);
6760
Pavel Feldmanfab3cb62017-10-05 01:02:016761 if (delegate_)
6762 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
6763
Charlie Reis96077362019-07-04 00:34:046764 // While a JS beforeunload dialog is showing, defer commits in this
6765 // WebContents.
6766 javascript_dialog_navigation_deferrer_ =
6767 std::make_unique<JavaScriptDialogNavigationDeferrer>();
6768
Sreeja Kamishettyf352e302020-06-10 13:21:246769 bool should_suppress = !rfhi->IsCurrent() ||
Tarun Bansalc209b742019-12-24 06:53:256770 (delegate_ && delegate_->ShouldSuppressDialogs(this));
Pavel Feldman1c587bc52018-04-04 21:16:056771 bool has_non_devtools_handlers = delegate_ && dialog_manager_;
6772 bool has_handlers = page_handlers.size() || has_non_devtools_handlers;
Pavel Feldmanfab3cb62017-10-05 01:02:016773 if (should_suppress || !has_handlers) {
Avi Drissmane04d3992017-10-05 15:11:366774 std::move(callback).Run(false, true, base::string16());
[email protected]87de04b02014-04-08 22:14:496775 return;
6776 }
6777
6778 is_showing_before_unload_dialog_ = true;
Pavel Feldman3c1842b2017-08-02 05:00:166779
6780 scoped_refptr<CloseDialogCallbackWrapper> wrapper =
Avi Drissmane04d3992017-10-05 15:11:366781 new CloseDialogCallbackWrapper(std::move(callback));
Pavel Feldman3c1842b2017-08-02 05:00:166782
6783 GURL frame_url = rfhi->GetLastCommittedURL();
6784 for (auto* handler : page_handlers) {
Avi Drissmane04d3992017-10-05 15:11:366785 handler->DidRunBeforeUnloadConfirm(
Pavel Feldman1c587bc52018-04-04 21:16:056786 frame_url, has_non_devtools_handlers,
Avi Drissmane04d3992017-10-05 15:11:366787 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
Pavel Feldman3c1842b2017-08-02 05:00:166788 }
6789
6790 if (dialog_manager_) {
Avi Drissmane04d3992017-10-05 15:11:366791 dialog_manager_->RunBeforeUnloadDialog(
Avi Drissmanff9ed752017-11-28 21:18:126792 this, render_frame_host, is_reload,
Avi Drissmane04d3992017-10-05 15:11:366793 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
Pavel Feldman3c1842b2017-08-02 05:00:166794 }
[email protected]87de04b02014-04-08 22:14:496795}
6796
Kent Tamurac260c9a2018-09-14 09:10:566797void WebContentsImpl::RunFileChooser(
6798 RenderFrameHost* render_frame_host,
Kent Tamura3abb32d2020-07-02 00:23:016799 scoped_refptr<FileChooserImpl::FileSelectListenerImpl> listener,
Kent Tamurac260c9a2018-09-14 09:10:566800 const blink::mojom::FileChooserParams& params) {
Alexander Timin5fdeff22020-09-08 09:20:376801 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RunFileChooser",
6802 "render_frame_host",
6803 base::trace_event::ToTracedValue(render_frame_host));
Avi Drissman3d41e7712018-08-27 21:18:086804 // Any explicit focusing of another window while this WebContents is in
6805 // fullscreen can be used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:456806 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
6807 listener->SetFullscreenBlock(std::move(fullscreen_block));
Avi Drissman3d41e7712018-08-27 21:18:086808
naskoada75b22016-06-11 16:09:466809 if (delegate_)
Kent Tamura512a27e2018-10-04 00:49:326810 delegate_->RunFileChooser(render_frame_host, std::move(listener), params);
6811 else
6812 listener->FileSelectionCanceled();
naskoada75b22016-06-11 16:09:466813}
6814
[email protected]a86c0e962013-12-17 17:10:396815WebContents* WebContentsImpl::GetAsWebContents() {
6816 return this;
6817}
6818
mcnee336ea2c2017-05-23 22:50:596819#if !defined(OS_ANDROID)
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416820double WebContentsImpl::GetPendingPageZoomLevel() {
wjmaclean64951902016-04-29 20:59:126821 NavigationEntry* pending_entry = GetController().GetPendingEntry();
6822 if (!pending_entry)
6823 return HostZoomMap::GetZoomLevel(this);
6824
6825 GURL url = pending_entry->GetURL();
6826 return HostZoomMap::GetForWebContents(this)->GetZoomLevelForHostAndScheme(
6827 url.scheme(), net::GetHostOrSpecFromURL(url));
6828}
mcnee336ea2c2017-05-23 22:50:596829#endif // !defined(OS_ANDROID)
wjmaclean64951902016-04-29 20:59:126830
qinmin72e8bd02016-10-21 19:35:376831bool WebContentsImpl::HideDownloadUI() const {
6832 return is_overlay_content_;
6833}
6834
mlamouri5cd9ae82017-02-18 11:05:096835bool WebContentsImpl::HasPersistentVideo() const {
6836 return has_persistent_video_;
6837}
6838
Ian Vollick5d5c37f2019-06-19 22:50:576839bool WebContentsImpl::IsSpatialNavigationDisabled() const {
6840 return is_spatial_navigation_disabled_;
6841}
6842
Albert J. Wong65fe64d2019-09-20 02:48:146843RenderFrameHostImpl* WebContentsImpl::GetPendingMainFrame() {
clamy610c63b32017-12-22 15:05:186844 return GetRenderManager()->speculative_frame_host();
Alex Moshchuk27caae82017-09-11 23:11:186845}
6846
mlamourie52c1b542017-02-23 14:57:506847bool WebContentsImpl::HasActiveEffectivelyFullscreenVideo() const {
6848 return media_web_contents_observer_->HasActiveEffectivelyFullscreenVideo();
6849}
6850
François Beaufortad6c5232018-02-26 11:00:446851bool WebContentsImpl::IsPictureInPictureAllowedForFullscreenVideo() const {
6852 return media_web_contents_observer_
6853 ->IsPictureInPictureAllowedForFullscreenVideo();
6854}
6855
ekaramada110f642016-12-21 19:47:286856bool WebContentsImpl::IsFocusedElementEditable() {
6857 RenderFrameHostImpl* frame = GetFocusedFrame();
6858 return frame && frame->has_focused_editable_element();
6859}
6860
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416861bool WebContentsImpl::IsShowingContextMenu() {
ekaramadf6750aa2017-06-06 18:29:426862 return showing_context_menu_;
6863}
6864
6865void WebContentsImpl::SetShowingContextMenu(bool showing) {
Alexander Timin5fdeff22020-09-08 09:20:376866 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetShowingContextMenu",
6867 "showing", showing);
6868
ekaramadf6750aa2017-06-06 18:29:426869 DCHECK_NE(showing_context_menu_, showing);
6870 showing_context_menu_ = showing;
6871
6872 if (auto* view = GetRenderWidgetHostView()) {
6873 // Notify the main frame's RWHV to run the platform-specific code, if any.
6874 static_cast<RenderWidgetHostViewBase*>(view)->SetShowingContextMenu(
6875 showing);
6876 }
6877}
6878
ekaramada110f642016-12-21 19:47:286879void WebContentsImpl::ClearFocusedElement() {
Alexander Timin5fdeff22020-09-08 09:20:376880 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ClearFocusedElement");
ekaramada110f642016-12-21 19:47:286881 if (auto* frame = GetFocusedFrame())
6882 frame->ClearFocusedElement();
6883}
6884
danakj77eb7e82020-01-09 19:38:466885bool WebContentsImpl::IsNeverComposited() {
[email protected]7912e822014-04-16 02:37:036886 if (!delegate_)
6887 return false;
danakj77eb7e82020-01-09 19:38:466888 return delegate_->IsNeverComposited(this);
[email protected]7912e822014-04-16 02:37:036889}
6890
[email protected]5a3bdf52012-05-24 15:12:576891RenderViewHostDelegateView* WebContentsImpl::GetDelegateView() {
6892 return render_view_host_delegate_view_;
[email protected]420ae012009-04-24 05:16:326893}
6894
Peter Marshall2dc74e92020-07-29 20:02:306895blink::mojom::RendererPreferences WebContentsImpl::GetRendererPrefs() const {
[email protected]840b1512009-07-21 16:53:466896 return renderer_preferences_;
[email protected]80d96fa2009-06-10 22:34:516897}
6898
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166899RenderFrameHostImpl* WebContentsImpl::GetOuterWebContentsFrame() {
6900 if (GetOuterDelegateFrameTreeNodeId() ==
6901 FrameTreeNode::kFrameTreeNodeInvalidId) {
6902 return nullptr;
6903 }
6904
6905 FrameTreeNode* outer_node =
6906 FrameTreeNode::GloballyFindByID(GetOuterDelegateFrameTreeNodeId());
6907 // The outer node should be in the outer WebContents.
6908 DCHECK_EQ(outer_node->frame_tree(), GetOuterWebContents()->GetFrameTree());
Alexander Timin381e7e182020-04-28 19:04:036909 return outer_node->parent();
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166910}
6911
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416912WebContentsImpl* WebContentsImpl::GetOuterWebContents() {
Lucas Furukawa Gadani105de1e812018-05-31 19:38:396913 return node_.outer_web_contents();
avallee0206f782016-07-28 18:55:336914}
6915
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166916std::vector<WebContents*> WebContentsImpl::GetInnerWebContents() {
6917 std::vector<WebContents*> all_inner_contents;
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166918 const auto& inner_contents = node_.GetInnerWebContents();
6919 all_inner_contents.insert(all_inner_contents.end(), inner_contents.begin(),
6920 inner_contents.end());
6921 return all_inner_contents;
6922}
6923
Jeremy Roman7e70bf92020-01-07 23:23:586924WebContentsImpl* WebContentsImpl::GetResponsibleWebContents() {
6925 // Iteratively ask delegates which other contents is responsible until a fixed
6926 // point is found.
6927 WebContentsImpl* contents = this;
6928 while (WebContentsDelegate* delegate = contents->GetDelegate()) {
6929 auto* responsible_contents = static_cast<WebContentsImpl*>(
6930 delegate->GetResponsibleWebContents(contents));
6931 if (responsible_contents == contents)
6932 break;
6933 contents = responsible_contents;
6934 }
6935 return contents;
6936}
6937
avallee0206f782016-07-28 18:55:336938WebContentsImpl* WebContentsImpl::GetFocusedWebContents() {
lfg601233692017-03-06 22:45:446939 return GetOutermostWebContents()->node_.focused_web_contents();
avallee0206f782016-07-28 18:55:336940}
6941
Lukasz Anforowicz2cd231bf2020-10-02 19:13:206942void WebContentsImpl::SetFocusToLocationBar() {
6943 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetFocusToLocationBar");
6944 if (delegate_)
6945 delegate_->SetFocusToLocationBar();
6946}
6947
avallee9993fca2016-11-17 06:16:506948bool WebContentsImpl::ContainsOrIsFocusedWebContents() {
6949 for (WebContentsImpl* focused_contents = GetFocusedWebContents();
6950 focused_contents;
6951 focused_contents = focused_contents->GetOuterWebContents()) {
6952 if (focused_contents == this)
6953 return true;
6954 }
6955
6956 return false;
6957}
6958
W. James MacLean9437b5bf2019-12-06 17:33:446959void WebContentsImpl::RemoveBrowserPluginEmbedder() {
Alexander Timin5fdeff22020-09-08 09:20:376960 OPTIONAL_TRACE_EVENT0("content",
6961 "WebContentsImpl::RemoveBrowserPluginEmbedder");
W. James MacLean9437b5bf2019-12-06 17:33:446962 browser_plugin_embedder_.reset();
6963}
6964
avallee0206f782016-07-28 18:55:336965WebContentsImpl* WebContentsImpl::GetOutermostWebContents() {
6966 WebContentsImpl* root = this;
6967 while (root->GetOuterWebContents())
6968 root = root->GetOuterWebContents();
6969 return root;
6970}
6971
avalleed68cdd12017-06-21 22:07:276972void WebContentsImpl::FocusOuterAttachmentFrameChain() {
Alexander Timin5fdeff22020-09-08 09:20:376973 OPTIONAL_TRACE_EVENT0("content",
6974 "WebContentsImpl::FocusOuterAttachmentFrameChain");
avalleed68cdd12017-06-21 22:07:276975 WebContentsImpl* outer_contents = GetOuterWebContents();
6976 if (!outer_contents)
6977 return;
6978
6979 FrameTreeNode* outer_node =
6980 FrameTreeNode::GloballyFindByID(GetOuterDelegateFrameTreeNodeId());
6981 outer_contents->frame_tree_.SetFocusedFrame(outer_node, nullptr);
6982
6983 // For a browser initiated focus change, let embedding renderer know of the
6984 // change. Otherwise, if the currently focused element is just across a
6985 // process boundary in focus order, it will not be possible to move across
6986 // that boundary. This is because the target element will already be focused
6987 // (that renderer was not notified) and drop the event.
6988 if (GetRenderManager()->GetProxyToOuterDelegate())
6989 GetRenderManager()->GetProxyToOuterDelegate()->SetFocusedFrame();
6990
6991 outer_contents->FocusOuterAttachmentFrameChain();
6992}
6993
Sean Toppingbbc4a2bd2019-01-30 02:16:146994void WebContentsImpl::InnerWebContentsCreated(WebContents* inner_web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:376995 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::InnerWebContentsCreated");
Alexander Timin90c20c32020-08-12 15:28:326996 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6997 observer->InnerWebContentsCreated(inner_web_contents);
6998 });
Sean Toppingbbc4a2bd2019-01-30 02:16:146999}
7000
Jeremy Roman03ce13ce2020-05-29 22:16:577001void WebContentsImpl::InnerWebContentsAttached(
7002 WebContents* inner_web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:377003 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::InnerWebContentsDetached");
Jeremy Roman03ce13ce2020-05-29 22:16:577004 if (inner_web_contents->IsCurrentlyAudible())
7005 OnAudioStateChanged();
7006}
7007
7008void WebContentsImpl::InnerWebContentsDetached(
7009 WebContents* inner_web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:377010 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::InnerWebContentsCreated");
Jeremy Roman03ce13ce2020-05-29 22:16:577011 if (!is_being_destroyed_)
7012 OnAudioStateChanged();
7013}
7014
[email protected]b172aee2012-04-10 17:05:267015void WebContentsImpl::RenderViewCreated(RenderViewHost* render_view_host) {
Alexander Timin5fdeff22020-09-08 09:20:377016 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderViewCreated",
7017 "render_view_host", render_view_host);
[email protected]86f98a22013-03-20 14:35:007018 if (delegate_)
[email protected]e85165c642014-06-10 14:34:317019 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
[email protected]a6b73c62013-02-11 23:05:087020
[email protected]8ff00d72012-10-23 19:12:217021 NotificationService::current()->Notify(
7022 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
7023 Source<WebContents>(this),
7024 Details<RenderViewHost>(render_view_host));
[email protected]420ae012009-04-24 05:16:327025
Alexander Timin90c20c32020-08-12 15:28:327026 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7027 observer->RenderViewCreated(render_view_host);
7028 });
Joel Einbinder848001c2017-09-19 21:39:317029 if (delegate_)
7030 RenderFrameDevToolsAgentHost::WebContentsCreated(this);
[email protected]420ae012009-04-24 05:16:327031}
7032
[email protected]b172aee2012-04-10 17:05:267033void WebContentsImpl::RenderViewReady(RenderViewHost* rvh) {
Alexander Timin5fdeff22020-09-08 09:20:377034 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderViewReady",
7035 "render_view_host", rvh);
[email protected]151a63d2011-12-20 22:32:527036 if (rvh != GetRenderViewHost()) {
[email protected]420ae012009-04-24 05:16:327037 // Don't notify the world, since this came from a renderer in the
7038 // background.
7039 return;
7040 }
7041
dmazzoni62111452017-04-28 23:46:557042 RenderWidgetHostViewBase* rwhv =
7043 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
7044 if (rwhv)
7045 rwhv->SetMainFrameAXTreeID(GetMainFrame()->GetAXTreeID());
7046
[email protected]da7a7182013-09-06 08:11:117047 notify_disconnection_ = true;
[email protected]da7a7182013-09-06 08:11:117048
[email protected]be1f56ab2011-12-22 06:55:317049 bool was_crashed = IsCrashed();
[email protected]443b80e2010-12-14 00:42:237050 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING, 0);
[email protected]9d8a4642009-07-29 17:25:307051
7052 // Restore the focus to the tab (otherwise the focus will be on the top
7053 // window).
[email protected]484ae5912010-09-29 19:16:147054 if (was_crashed && !FocusLocationBarByDefault() &&
7055 (!delegate_ || delegate_->ShouldFocusPageAfterCrash())) {
[email protected]f3615f02013-02-26 06:09:067056 view_->Focus();
[email protected]484ae5912010-09-29 19:16:147057 }
[email protected]32ded2212011-11-10 18:51:437058
Alexander Timin90c20c32020-08-12 15:28:327059 observers_.ForEachObserver(
7060 [&](WebContentsObserver* observer) { observer->RenderViewReady(); });
Jinsuk Kim895b2c52018-07-03 06:49:167061 view_->RenderViewReady();
[email protected]420ae012009-04-24 05:16:327062}
7063
[email protected]ec6a7eb2013-04-22 17:34:227064void WebContentsImpl::RenderViewTerminated(RenderViewHost* rvh,
7065 base::TerminationStatus status,
7066 int error_code) {
Alexander Timin5fdeff22020-09-08 09:20:377067 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RenderViewTerminated",
7068 "render_view_host", rvh, "status",
7069 static_cast<int>(status));
[email protected]151a63d2011-12-20 22:32:527070 if (rvh != GetRenderViewHost()) {
[email protected]420ae012009-04-24 05:16:327071 // The pending page's RenderViewHost is gone.
7072 return;
7073 }
[email protected]2fcdcc32014-03-05 02:14:077074 // Ensure fullscreen mode is exited in the |delegate_| since a crashed
7075 // renderer may not have made a clean exit.
Avi Drissman97aef042020-06-30 21:04:487076 if (IsFullscreen())
bokanece34a82016-01-28 19:49:467077 ExitFullscreenMode(false);
[email protected]2fcdcc32014-03-05 02:14:077078
Jennifer Apacibleb4b972a2018-06-07 04:41:027079 // Ensure any video in Picture-in-Picture is exited in the |delegate_| since
7080 // a crashed renderer may not have made a clean exit.
7081 if (HasPictureInPictureVideo())
7082 ExitPictureInPicture();
7083
[email protected]698191dc2014-02-25 01:06:137084 // Cancel any visible dialogs so they are not left dangling over the sad tab.
creis89a0f782015-05-27 16:13:177085 CancelActiveAndPendingDialogs();
[email protected]698191dc2014-02-25 01:06:137086
dalecurtis3d1e1302017-02-20 22:33:257087 audio_stream_monitor_.RenderProcessGone(rvh->GetProcess()->GetID());
7088
[email protected]960b0372014-05-19 18:01:007089 // Reset the loading progress. TODO(avi): What does it mean to have a
7090 // "renderer crash" when there is more than one renderer process serving a
7091 // webpage? Once this function is called at a more granular frame level, we
7092 // probably will need to more granularly reset the state here.
7093 ResetLoadProgressState();
clamy44e84ce2016-02-22 15:38:257094 NotifyDisconnected();
7095 SetIsCrashed(status, error_code);
[email protected]960b0372014-05-19 18:01:007096
Alexander Timin5fdeff22020-09-08 09:20:377097 TRACE_EVENT0("content",
7098 "Dispatching WebContentsObserver::RenderViewTerminated");
Alexander Timin90c20c32020-08-12 15:28:327099 // Some observers might destroy WebContents in RenderViewTerminated.
7100 base::WeakPtr<WebContentsImpl> weak_ptr = weak_factory_.GetWeakPtr();
7101 auto crashed_status = GetCrashedStatus();
7102 for (auto& observer : observers_.observer_list()) {
7103 observer.RenderProcessGone(crashed_status);
7104 if (!weak_ptr)
7105 return;
7106 }
7107
7108 // |this| might have been deleted. Do not add code here.
[email protected]420ae012009-04-24 05:16:327109}
7110
[email protected]b172aee2012-04-10 17:05:267111void WebContentsImpl::RenderViewDeleted(RenderViewHost* rvh) {
Alexander Timin5fdeff22020-09-08 09:20:377112 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderViewDeleted",
7113 "render_view_host", rvh);
Alexander Timin90c20c32020-08-12 15:28:327114 observers_.ForEachObserver(
7115 [&](WebContentsObserver* observer) { observer->RenderViewDeleted(rvh); });
[email protected]2e4633c2009-07-09 16:58:067116}
7117
Lukasz Anforowiczfd707142018-02-07 19:46:137118void WebContentsImpl::ClearTargetURL() {
Alexander Timin5fdeff22020-09-08 09:20:377119 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ClearTargetURL");
Mario Sanchez Pradadffbe66e2020-09-07 12:01:087120 frame_that_set_last_target_url_ = nullptr;
Lukasz Anforowiczfd707142018-02-07 19:46:137121 if (delegate_)
7122 delegate_->UpdateTargetURL(this, GURL());
7123}
7124
[email protected]b172aee2012-04-10 17:05:267125void WebContentsImpl::Close(RenderViewHost* rvh) {
Alexander Timin5fdeff22020-09-08 09:20:377126 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::Close", "render_view_host",
7127 rvh);
Avi Drissman7c57be72020-07-29 20:09:467128#if defined(OS_MAC)
[email protected]07707302009-11-06 00:50:297129 // The UI may be in an event-tracking loop, such as between the
7130 // mouse-down and mouse-up in text selection or a button click.
7131 // Defer the close until after tracking is complete, so that we
7132 // don't free objects out from under the UI.
[email protected]07707302009-11-06 00:50:297133 // TODO(shess): This could get more fine-grained. For instance,
7134 // closing a tab in another window while selecting text in the
7135 // current window's Omnibox should be just fine.
Christopher Cameron9ae31e0d2019-03-01 20:01:197136 if (view_->CloseTabAfterEventTrackingIfNeeded())
[email protected]07707302009-11-06 00:50:297137 return;
[email protected]60780f412013-02-25 16:34:107138#endif
[email protected]07707302009-11-06 00:50:297139
[email protected]420ae012009-04-24 05:16:327140 // Ignore this if it comes from a RenderViewHost that we aren't showing.
[email protected]151a63d2011-12-20 22:32:527141 if (delegate_ && rvh == GetRenderViewHost())
[email protected]6934a702011-12-20 00:04:517142 delegate_->CloseContents(this);
[email protected]420ae012009-04-24 05:16:327143}
7144
Avi Drissman014dec72018-06-07 02:34:017145void WebContentsImpl::RequestSetBounds(const gfx::Rect& new_bounds) {
Alexander Timin5fdeff22020-09-08 09:20:377146 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::RequestSetBounds");
Mike Wassermandabad612020-08-13 04:26:277147 if (!delegate_)
7148 return;
7149
7150 // Members of |new_bounds| may be 0 to indicate uninitialized values for newly
7151 // opened windows, even if the |GetContainerBounds()| inner rect is correct.
7152 // TODO(crbug.com/897300): Plumb values as specified; fallback on outer rect.
7153 auto bounds = new_bounds;
7154 if (bounds.IsEmpty())
7155 bounds.set_size(GetContainerBounds().size());
7156
7157 // Only requests from the main frame, not subframes, should reach this code.
Mike Wassermanb6bc0152020-08-25 22:46:207158 int64_t display_id = AdjustRequestedWindowBounds(&bounds, GetMainFrame());
7159
7160 // Drop fullscreen when placing a WebContents to prohibit deceptive behavior.
7161 // Only drop fullscreen on the specific destination display, which is known.
7162 // This supports sites using cross-screen window placement capabilities to
7163 // retain fullscreen and place a window on another screen.
7164 ForSecurityDropFullscreen(display_id).RunAndReset();
7165
Mike Wassermandabad612020-08-13 04:26:277166 delegate_->SetContentsBounds(this, bounds);
[email protected]420ae012009-04-24 05:16:327167}
7168
fdegansa696e5112015-04-17 01:57:597169void WebContentsImpl::DidStartLoading(FrameTreeNode* frame_tree_node,
[email protected]e3b10d12014-03-28 16:06:097170 bool to_different_document) {
Alexander Timin5fdeff22020-09-08 09:20:377171 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DidStartLoading",
7172 "frame_tree_node", frame_tree_node);
Evan Stadec3b26022017-07-14 19:50:247173 LoadingStateChanged(frame_tree_node->IsMainFrame() && to_different_document,
Carlos IL07f282f2020-05-15 22:58:297174 nullptr);
dmazzonibf8cec42015-02-08 08:28:087175
Xiyuan Xia2a66b112018-12-06 15:52:167176 // Reset the focus state from DidStartNavigation to false if a new load starts
7177 // afterward, in case loading logic triggers a FocusLocationBarByDefault call.
7178 should_focus_location_bar_by_default_ = false;
Ian Prestcdd843d2020-01-28 18:59:587179
7180 // Notify accessibility that the user is navigating away from the
7181 // current document.
7182 // TODO(domfarolino, dmazzoni): Do this using WebContentsObserver. See
7183 // https://crbug.com/981271.
7184 BrowserAccessibilityManager* manager =
7185 frame_tree_node->current_frame_host()->browser_accessibility_manager();
7186 if (manager)
7187 manager->UserIsNavigatingAway();
[email protected]420ae012009-04-24 05:16:327188}
7189
fdegansc73eec22015-03-19 14:47:547190void WebContentsImpl::DidStopLoading() {
Alexander Timin5fdeff22020-09-08 09:20:377191 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidStopLoading");
dcheng59716272016-04-09 05:19:087192 std::unique_ptr<LoadNotificationDetails> details;
[email protected]420ae012009-04-24 05:16:327193
[email protected]9595fd82013-04-19 21:28:497194 // Use the last committed entry rather than the active one, in case a
7195 // pending entry has been created.
7196 NavigationEntry* entry = controller_.GetLastCommittedEntry();
7197
[email protected]420ae012009-04-24 05:16:327198 // An entry may not exist for a stop when loading an initial blank page or
7199 // if an iframe injected by script into a blank page finishes loading.
7200 if (entry) {
Fergal Daly55b6d722020-09-11 07:56:337201 details = std::make_unique<LoadNotificationDetails>(
7202 entry->GetVirtualURL(), &controller_,
7203 controller_.GetCurrentEntryIndex());
[email protected]420ae012009-04-24 05:16:327204 }
7205
Carlos IL07f282f2020-05-15 22:58:297206 LoadingStateChanged(true, details.get());
[email protected]420ae012009-04-24 05:16:327207}
7208
fdegansa696e5112015-04-17 01:57:597209void WebContentsImpl::DidChangeLoadProgress() {
Alexander Timin5fdeff22020-09-08 09:20:377210 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidChangeLoadProgress");
Nate Chapin22ea6592019-03-05 22:29:027211 if (is_being_destroyed_)
7212 return;
fdegansa696e5112015-04-17 01:57:597213 double load_progress = frame_tree_.load_progress();
7214
7215 // The delegate is notified immediately for the first and last updates. Also,
7216 // since the message loop may be pretty busy when a page is loaded, it might
7217 // not execute a posted task in a timely manner so the progress report is sent
7218 // immediately if enough time has passed.
7219 base::TimeDelta min_delay =
7220 base::TimeDelta::FromMilliseconds(kMinimumDelayBetweenLoadingUpdatesMS);
7221 bool delay_elapsed = loading_last_progress_update_.is_null() ||
7222 base::TimeTicks::Now() - loading_last_progress_update_ > min_delay;
7223
7224 if (load_progress == 0.0 || load_progress == 1.0 || delay_elapsed) {
7225 // If there is a pending task to send progress, it is now obsolete.
7226 loading_weak_factory_.InvalidateWeakPtrs();
7227
7228 // Notify the load progress change.
7229 SendChangeLoadProgress();
7230
7231 // Clean-up the states if needed.
7232 if (load_progress == 1.0)
7233 ResetLoadProgressState();
7234 return;
7235 }
7236
7237 if (loading_weak_factory_.HasWeakPtrs())
7238 return;
7239
skyostil95082a62015-06-05 19:53:077240 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
tzike2aca992017-09-05 08:50:547241 FROM_HERE,
7242 base::BindOnce(&WebContentsImpl::SendChangeLoadProgress,
7243 loading_weak_factory_.GetWeakPtr()),
fdegansa696e5112015-04-17 01:57:597244 min_delay);
7245}
7246
avid6d88b912017-01-13 00:16:007247std::vector<std::unique_ptr<NavigationThrottle>>
7248WebContentsImpl::CreateThrottlesForNavigation(
clamycbf524d42016-09-27 12:48:357249 NavigationHandle* navigation_handle) {
Alexander Timin5fdeff22020-09-08 09:20:377250 OPTIONAL_TRACE_EVENT1("content",
7251 "WebContentsImpl::CreateThrottlesForNavigation",
7252 "navigation", navigation_handle);
Charlie Reis96077362019-07-04 00:34:047253 auto throttles = GetContentClient()->browser()->CreateThrottlesForNavigation(
clamycbf524d42016-09-27 12:48:357254 navigation_handle);
Charlie Reis96077362019-07-04 00:34:047255
7256 // This is not a normal place to be adding a throttle. However, in the case
7257 // javascript dialogs, related logic is present in the web_contents/ layer,
7258 // and the purpose of the throttle is to ensure that navigation commits are
7259 // deferred for the entire WebContents. Most throttles are either added by
7260 // the embederrer outside of content/, or are per-frame and added by
7261 // NavigationThrottleRunner.
7262 std::unique_ptr<content::NavigationThrottle> dialog_throttle =
7263 JavaScriptDialogNavigationThrottle::MaybeCreateThrottleFor(
7264 navigation_handle);
7265 if (dialog_throttle)
7266 throttles.push_back(std::move(dialog_throttle));
7267
7268 return throttles;
clamycbf524d42016-09-27 12:48:357269}
7270
clamy1e5574e2016-09-29 16:48:447271std::unique_ptr<NavigationUIData> WebContentsImpl::GetNavigationUIData(
7272 NavigationHandle* navigation_handle) {
Alexander Timin5fdeff22020-09-08 09:20:377273 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GetNavigationUIData");
clamy1e5574e2016-09-29 16:48:447274 return GetContentClient()->browser()->GetNavigationUIData(navigation_handle);
7275}
7276
W. James MacLean1c40862c2020-04-27 21:05:577277void WebContentsImpl::RegisterExistingOriginToPreventOptInIsolation(
W. James MacLeanb70fab82020-05-01 18:51:147278 const url::Origin& origin,
7279 NavigationRequest* navigation_request_to_exclude) {
Alexander Timin5fdeff22020-09-08 09:20:377280 OPTIONAL_TRACE_EVENT2(
7281 "content",
7282 "WebContentsImpl::RegisterExistingOriginToPreventOptInIsolation",
7283 "origin", base::trace_event::ValueToString(origin),
7284 "navigation_request_to_exclude", navigation_request_to_exclude);
W. James MacLean1c40862c2020-04-27 21:05:577285 // Note: This function can be made static if we ever need call it without
7286 // a WebContentsImpl instance, in which case we can use a wrapper to
7287 // implement the override from NavigatorDelegate.
7288 for (WebContentsImpl* web_contents : GetAllWebContents()) {
7289 web_contents->controller_.RegisterExistingOriginToPreventOptInIsolation(
7290 origin);
W. James MacLeanb70fab82020-05-01 18:51:147291 // Walk the frame tree to pick up any frames without FrameNavigationEntries.
7292 // * Some frames won't have FrameNavigationEntries (Issues 524208, 608402).
7293 // * Some pending navigations won't have NavigationEntries.
7294 web_contents->GetFrameTree()->RegisterExistingOriginToPreventOptInIsolation(
7295 origin, navigation_request_to_exclude);
W. James MacLean1c40862c2020-04-27 21:05:577296 }
7297}
7298
pdr15f5b5b2017-06-20 00:58:007299void WebContentsImpl::DidCancelLoading() {
Alexander Timin5fdeff22020-09-08 09:20:377300 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidCancelLoading");
pdr15f5b5b2017-06-20 00:58:007301 controller_.DiscardNonCommittedEntries();
7302
7303 // Update the URL display.
7304 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
7305}
7306
[email protected]59167c22013-06-03 18:07:327307void WebContentsImpl::DidAccessInitialDocument() {
Alexander Timin5fdeff22020-09-08 09:20:377308 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidAccessInitialDocument");
[email protected]b4c84012014-04-28 19:51:107309 has_accessed_initial_document_ = true;
7310
[email protected]d1371bf8e2014-04-19 03:26:247311 // We may have left a failed browser-initiated navigation in the address bar
7312 // to let the user edit it and try again. Clear it now that content might
7313 // show up underneath it.
7314 if (!IsLoading() && controller_.GetPendingEntry())
avi45a72532015-04-07 21:01:457315 controller_.DiscardPendingEntry(false);
[email protected]d1371bf8e2014-04-19 03:26:247316
[email protected]59167c22013-06-03 18:07:327317 // Update the URL display.
thestigc4cac8f2014-09-04 21:17:507318 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
[email protected]59167c22013-06-03 18:07:327319}
7320
alexmosbe2f4c32015-03-10 02:30:237321void WebContentsImpl::DidChangeName(RenderFrameHost* render_frame_host,
7322 const std::string& name) {
Alexander Timin5fdeff22020-09-08 09:20:377323 OPTIONAL_TRACE_EVENT2(
7324 "content", "WebContentsImpl::DidChangeName", "render_frame_host",
7325 base::trace_event::ToTracedValue(render_frame_host), "name", name);
Alexander Timin90c20c32020-08-12 15:28:327326 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7327 observer->FrameNameChanged(render_frame_host, name);
7328 });
alexmosbe2f4c32015-03-10 02:30:237329}
7330
John Delaneyedd8d6c2019-01-25 00:23:577331void WebContentsImpl::DidReceiveFirstUserActivation(
7332 RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:377333 OPTIONAL_TRACE_EVENT1(
7334 "content", "WebContentsImpl::DidReceiveFirstUserActivation",
7335 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host));
Alexander Timin90c20c32020-08-12 15:28:327336 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7337 observer->FrameReceivedFirstUserActivation(render_frame_host);
7338 });
John Delaneyedd8d6c2019-01-25 00:23:577339}
7340
John Delaney0146a742019-01-25 19:25:287341void WebContentsImpl::DidChangeDisplayState(RenderFrameHost* render_frame_host,
7342 bool is_display_none) {
Alexander Timin5fdeff22020-09-08 09:20:377343 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::DidChangeDisplayState",
7344 "render_frame_host",
7345 base::trace_event::ToTracedValue(render_frame_host),
7346 "is_display_none", is_display_none);
Alexander Timin90c20c32020-08-12 15:28:327347 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7348 observer->FrameDisplayStateChanged(render_frame_host, is_display_none);
7349 });
John Delaney0146a742019-01-25 19:25:287350}
7351
7352void WebContentsImpl::FrameSizeChanged(RenderFrameHost* render_frame_host,
7353 const gfx::Size& frame_size) {
Alexander Timin5fdeff22020-09-08 09:20:377354 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::FrameSizeChanged",
7355 "render_frame_host",
7356 base::trace_event::ToTracedValue(render_frame_host));
Alexander Timin90c20c32020-08-12 15:28:327357 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7358 observer->FrameSizeChanged(render_frame_host, frame_size);
7359 });
John Delaney0146a742019-01-25 19:25:287360}
7361
[email protected]39f2f9252014-05-03 00:54:017362void WebContentsImpl::DocumentOnLoadCompleted(
[email protected]50279492014-05-05 23:24:297363 RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:377364 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DocumentOnLoadCompleted",
7365 "render_frame_host",
7366 base::trace_event::ToTracedValue(render_frame_host));
falken52a56e32016-12-08 05:02:407367 ShowInsecureLocalhostWarningIfNeeded();
7368
Alexander Timindd0fa0c52019-11-06 13:03:377369 GetRenderViewHost()->DocumentOnLoadCompletedInMainFrame();
7370
Alexander Timin90c20c32020-08-12 15:28:327371 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7372 observer->DocumentOnLoadCompletedInMainFrame();
7373 });
[email protected]6578fef2013-10-14 02:35:097374
7375 // TODO(avi): Remove. http://crbug.com/170921
[email protected]8ff00d72012-10-23 19:12:217376 NotificationService::current()->Notify(
7377 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
7378 Source<WebContents>(this),
[email protected]50279492014-05-05 23:24:297379 NotificationService::NoDetails());
[email protected]25497492010-09-11 15:15:087380}
7381
creis8eb8ef22015-11-04 22:51:387382void WebContentsImpl::UpdateStateForFrame(RenderFrameHost* render_frame_host,
Miyoung Shin5d77f72072020-10-09 15:14:207383 const blink::PageState& page_state) {
Alexander Timin5fdeff22020-09-08 09:20:377384 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::UpdateStateForFrame",
7385 "render_frame_host",
7386 base::trace_event::ToTracedValue(render_frame_host));
creis8eb8ef22015-11-04 22:51:387387 // The state update affects the last NavigationEntry associated with the given
7388 // |render_frame_host|. This may not be the last committed NavigationEntry (as
7389 // in the case of an UpdateState from a frame being swapped out). We track
7390 // which entry this is in the RenderFrameHost's nav_entry_id.
7391 RenderFrameHostImpl* rfhi =
7392 static_cast<RenderFrameHostImpl*>(render_frame_host);
7393 NavigationEntryImpl* entry =
7394 controller_.GetEntryWithUniqueID(rfhi->nav_entry_id());
7395 if (!entry)
7396 return;
7397
7398 FrameNavigationEntry* frame_entry =
7399 entry->GetFrameEntry(rfhi->frame_tree_node());
7400 if (!frame_entry)
7401 return;
7402
creisd06a9422015-11-11 03:08:457403 // The SiteInstance might not match if we do a cross-process navigation with
7404 // replacement (e.g., auto-subframe), in which case the swap out of the old
7405 // RenderFrameHost runs in the background after the old FrameNavigationEntry
7406 // has already been replaced and destroyed.
7407 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
7408 return;
7409
creis8eb8ef22015-11-04 22:51:387410 if (page_state == frame_entry->page_state())
7411 return; // Nothing to update.
7412
creis0cade2e2017-02-28 06:37:477413 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
nasko34634672016-07-29 18:46:067414
7415 // The document_sequence_number and item_sequence_number recorded in the
7416 // FrameNavigationEntry should not differ from the one coming with the update,
7417 // since it must come from the same document. Do not update it if a difference
7418 // is detected, as this indicates that |frame_entry| is not the correct one.
Miyoung Shin5d77f72072020-10-09 15:14:207419 blink::ExplodedPageState exploded_state;
7420 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
nasko34634672016-07-29 18:46:067421 return;
7422
7423 if (exploded_state.top.document_sequence_number !=
7424 frame_entry->document_sequence_number() ||
7425 exploded_state.top.item_sequence_number !=
7426 frame_entry->item_sequence_number()) {
7427 return;
7428 }
7429
nasko04a322f25a2016-09-01 00:00:347430 frame_entry->SetPageState(page_state);
creis8eb8ef22015-11-04 22:51:387431 controller_.NotifyEntryChanged(entry);
7432}
7433
[email protected]ef3adfc2014-05-11 00:04:547434void WebContentsImpl::UpdateTitle(RenderFrameHost* render_frame_host,
[email protected]ef3adfc2014-05-11 00:04:547435 const base::string16& title,
7436 base::i18n::TextDirection title_direction) {
Alexander Timin5fdeff22020-09-08 09:20:377437 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::UpdateTitle",
7438 "render_frame_host",
7439 base::trace_event::ToTracedValue(render_frame_host),
7440 "title", base::trace_event::ValueToString(title));
[email protected]ef3adfc2014-05-11 00:04:547441 // Try to find the navigation entry, which might not be the current one.
avi286019ce2015-07-29 01:26:587442 // For example, it might be from a recently swapped out RFH.
avi1edc8552016-10-13 21:37:167443 NavigationEntryImpl* entry = controller_.GetEntryWithUniqueID(
creisad8c31a2016-05-24 17:07:047444 static_cast<RenderFrameHostImpl*>(render_frame_host)->nav_entry_id());
[email protected]ef3adfc2014-05-11 00:04:547445
7446 // We can handle title updates when we don't have an entry in
7447 // UpdateTitleForEntry, but only if the update is from the current RVH.
7448 // TODO(avi): Change to make decisions based on the RenderFrameHost.
avi286019ce2015-07-29 01:26:587449 if (!entry && render_frame_host != GetMainFrame())
[email protected]ef3adfc2014-05-11 00:04:547450 return;
7451
7452 // TODO(evan): make use of title_direction.
7453 // http://code.google.com/p/chromium/issues/detail?id=27094
afakhry6f0c1ec22016-07-14 13:55:137454 UpdateTitleForEntry(entry, title);
[email protected]ef3adfc2014-05-11 00:04:547455}
7456
Mario Sanchez Pradadffbe66e2020-09-07 12:01:087457void WebContentsImpl::UpdateTargetURL(RenderFrameHost* render_frame_host,
7458 const GURL& url) {
Alexander Timin5fdeff22020-09-08 09:20:377459 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::UpdateTargetURL",
7460 "render_frame_host",
7461 base::trace_event::ToTracedValue(render_frame_host),
7462 "url", base::trace_event::ValueToString(url));
Mario Sanchez Pradadffbe66e2020-09-07 12:01:087463 if (fullscreen_widget_routing_id_ != MSG_ROUTING_NONE) {
7464 // If we're in flash fullscreen (i.e. Pepper plugin fullscreen) only update
7465 // the url if it's from the fullscreen renderer.
7466 RenderWidgetHostView* fs = GetFullscreenRenderWidgetHostView();
7467 RenderViewHost* render_view_host = render_frame_host->GetRenderViewHost();
7468 if (fs && fs->GetRenderWidgetHost() != render_view_host->GetWidget())
7469 return;
7470 }
7471
7472 // In case of racey updates from multiple RenderViewHosts, the last URL should
7473 // be shown - see also some discussion in https://crbug.com/807776.
7474 if (!url.is_valid() && render_frame_host != frame_that_set_last_target_url_)
7475 return;
7476 frame_that_set_last_target_url_ =
7477 url.is_valid() ? render_frame_host : nullptr;
7478
7479 if (delegate_)
7480 delegate_->UpdateTargetURL(this, url);
7481}
7482
alexmose7da5a12015-04-09 02:22:167483bool WebContentsImpl::ShouldRouteMessageEvent(
7484 RenderFrameHost* target_rfh,
7485 SiteInstance* source_site_instance) const {
Alexander Timin5fdeff22020-09-08 09:20:377486 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::ShouldRouteMessageEvent",
7487 "render_frame_host",
7488 base::trace_event::ToTracedValue(target_rfh),
7489 "source_site_instance", source_site_instance);
alexmose7da5a12015-04-09 02:22:167490 // Allow the message if this WebContents is dedicated to a browser plugin
7491 // guest.
[email protected]0eba810b2012-10-18 03:19:367492 // Note: This check means that an embedder could theoretically receive a
7493 // postMessage from anyone (not just its own guests). However, this is
7494 // probably not a risk for apps since other pages won't have references
7495 // to App windows.
alexmose7da5a12015-04-09 02:22:167496 return GetBrowserPluginGuest() || GetBrowserPluginEmbedder();
7497}
[email protected]f546640b2012-05-15 00:03:497498
alexmos58729042015-06-18 23:20:007499void WebContentsImpl::EnsureOpenerProxiesExist(RenderFrameHost* source_rfh) {
Alexander Timin5fdeff22020-09-08 09:20:377500 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::EnsureOpenerProxiesExist",
7501 "render_frame_host",
7502 base::trace_event::ToTracedValue(source_rfh));
alexmose7da5a12015-04-09 02:22:167503 WebContentsImpl* source_web_contents = static_cast<WebContentsImpl*>(
7504 WebContents::FromRenderFrameHost(source_rfh));
[email protected]f546640b2012-05-15 00:03:497505
alexmose7da5a12015-04-09 02:22:167506 if (source_web_contents) {
lazyboy6ec48b2a2015-06-29 15:18:147507 // If this message is going to outer WebContents from inner WebContents,
7508 // then we should not create a RenderView. AttachToOuterWebContentsFrame()
7509 // already created a RenderFrameProxyHost for that purpose.
7510 if (GetBrowserPluginEmbedder() &&
W. James MacLean2539adb32019-12-13 00:40:447511 source_web_contents->browser_plugin_guest_) {
lazyboy6ec48b2a2015-06-29 15:18:147512 return;
W. James MacLean2539adb32019-12-13 00:40:447513 }
lazyboy6ec48b2a2015-06-29 15:18:147514
lfg812874d2016-02-09 22:26:137515 if (this != source_web_contents && GetBrowserPluginGuest()) {
naskob3041b98a42016-03-12 04:43:067516 // We create a RenderFrameProxyHost for the embedder in the guest's render
7517 // process but we intentionally do not expose the embedder's opener chain
7518 // to it.
7519 source_web_contents->GetRenderManager()->CreateRenderFrameProxy(
7520 GetSiteInstance());
[email protected]f546640b2012-05-15 00:03:497521 } else {
alexmos58729042015-06-18 23:20:007522 RenderFrameHostImpl* source_rfhi =
7523 static_cast<RenderFrameHostImpl*>(source_rfh);
7524 source_rfhi->frame_tree_node()->render_manager()->CreateOpenerProxies(
alexmos90325cf2015-09-02 17:18:397525 GetSiteInstance(), nullptr);
[email protected]f546640b2012-05-15 00:03:497526 }
7527 }
[email protected]f546640b2012-05-15 00:03:497528}
7529
avallee9993fca2016-11-17 06:16:507530void WebContentsImpl::SetAsFocusedWebContentsIfNecessary() {
Alexander Timin5fdeff22020-09-08 09:20:377531 OPTIONAL_TRACE_EVENT0("content",
7532 "WebContentsImpl::SetAsFocusedWebContentsIfNecessary");
Adithya Srinivasan11af2c52019-12-16 22:52:557533 DCHECK(!portal());
avallee9993fca2016-11-17 06:16:507534 // Only change focus if we are not currently focused.
7535 WebContentsImpl* old_contents = GetFocusedWebContents();
7536 if (old_contents == this)
7537 return;
7538
paulmeyerfeafc2d2017-04-25 21:46:407539 GetOutermostWebContents()->node_.SetFocusedWebContents(this);
7540
avallee9993fca2016-11-17 06:16:507541 // Send a page level blur to the old contents so that it displays inactive UI
7542 // and focus this contents to activate it.
7543 if (old_contents)
7544 old_contents->GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(false);
avalleec2ff1ef2017-01-21 00:12:307545
7546 // Make sure the outer web contents knows our frame is focused. Otherwise, the
7547 // outer renderer could have the element before or after the frame element
7548 // focused which would return early without actually advancing focus.
avalleed68cdd12017-06-21 22:07:277549 FocusOuterAttachmentFrameChain();
avalleec2ff1ef2017-01-21 00:12:307550
Carlos ILd51e7702020-05-07 18:51:397551 GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(true);
avallee9993fca2016-11-17 06:16:507552}
7553
avallee0206f782016-07-28 18:55:337554void WebContentsImpl::SetFocusedFrame(FrameTreeNode* node,
7555 SiteInstance* source) {
Alexander Timin5fdeff22020-09-08 09:20:377556 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetFocusedFrame",
7557 "frame_tree_node", node, "source_site_instance",
7558 source);
Adithya Srinivasan11af2c52019-12-16 22:52:557559 DCHECK(!portal());
avallee0206f782016-07-28 18:55:337560 frame_tree_.SetFocusedFrame(node, source);
avalleed68cdd12017-06-21 22:07:277561
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:577562 if (auto* inner_contents = node_.GetInnerWebContentsInFrame(node)) {
7563 // |this| is an outer WebContents and |node| represents an inner
7564 // WebContents. Transfer the focus to the inner contents if |this| is
7565 // focused.
7566 if (GetFocusedWebContents() == this)
7567 inner_contents->SetAsFocusedWebContentsIfNecessary();
7568 } else if (node_.OuterContentsFrameTreeNode() &&
7569 node_.OuterContentsFrameTreeNode()
7570 ->current_frame_host()
7571 ->GetSiteInstance() == source) {
7572 // |this| is an inner WebContents, |node| is its main FrameTreeNode and
7573 // the outer WebContents FrameTreeNode is at |source|'s SiteInstance.
7574 // Transfer the focus to the inner WebContents if the outer WebContents is
7575 // focused. This branch is used when an inner WebContents is focused through
Lowell Mannersa9530382019-08-01 09:46:577576 // its RenderFrameProxyHost (via FrameFocused mojo call, used to
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:577577 // implement the window.focus() API).
7578 if (GetFocusedWebContents() == GetOuterWebContents())
7579 SetAsFocusedWebContentsIfNecessary();
7580 } else if (!GetOuterWebContents()) {
7581 // This is an outermost WebContents.
7582 SetAsFocusedWebContentsIfNecessary();
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:577583 }
avalleed68cdd12017-06-21 22:07:277584}
7585
Avi Drissman36f801f2018-02-01 20:06:047586void WebContentsImpl::DidCallFocus() {
Alexander Timin5fdeff22020-09-08 09:20:377587 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidCallFocus");
Avi Drissman36f801f2018-02-01 20:06:047588 // Any explicit focusing of another window while this WebContents is in
7589 // fullscreen can be used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:457590 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
7591 // The other contents is independent of this contents, so release the
7592 // fullscreen block.
7593 fullscreen_block.RunAndReset();
Avi Drissman36f801f2018-02-01 20:06:047594}
7595
avalleed68cdd12017-06-21 22:07:277596RenderFrameHost* WebContentsImpl::GetFocusedFrameIncludingInnerWebContents() {
Alexander Timin5fdeff22020-09-08 09:20:377597 OPTIONAL_TRACE_EVENT0(
7598 "content", "WebContentsImpl::GetFocusedFrameIncludingInnerWebContents");
avalleed68cdd12017-06-21 22:07:277599 WebContentsImpl* contents = this;
7600 FrameTreeNode* focused_node = contents->frame_tree_.GetFocusedFrame();
7601
7602 // If there is no focused frame in the outer WebContents, we need to return
7603 // null.
7604 if (!focused_node)
7605 return nullptr;
7606
7607 // If the focused frame is embedding an inner WebContents, we must descend
7608 // into that contents. If the current WebContents does not have a focused
7609 // frame, return the main frame of this contents instead of the focused empty
7610 // frame embedding this contents.
7611 while (true) {
7612 contents = contents->node_.GetInnerWebContentsInFrame(focused_node);
7613 if (!contents)
7614 return focused_node->current_frame_host();
7615
7616 focused_node = contents->frame_tree_.GetFocusedFrame();
7617 if (!focused_node)
7618 return contents->GetMainFrame();
7619 }
avallee0206f782016-07-28 18:55:337620}
7621
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:577622void WebContentsImpl::OnAdvanceFocus(RenderFrameHostImpl* source_rfh) {
Alexander Timin5fdeff22020-09-08 09:20:377623 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnAdvanceFocus",
7624 "render_frame_host",
7625 base::trace_event::ToTracedValue(source_rfh));
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:577626 // When a RenderFrame needs to advance focus to a RenderFrameProxy (by hitting
7627 // TAB), the RenderFrameProxy sends an IPC to RenderFrameProxyHost. When this
7628 // RenderFrameProxyHost represents an inner WebContents, the outer WebContents
7629 // needs to focus the inner WebContents.
7630 if (GetOuterWebContents() &&
7631 GetOuterWebContents() == source_rfh->delegate()->GetAsWebContents() &&
7632 GetFocusedWebContents() == GetOuterWebContents()) {
7633 SetAsFocusedWebContentsIfNecessary();
7634 }
7635}
7636
ekaramada110f642016-12-21 19:47:287637void WebContentsImpl::OnFocusedElementChangedInFrame(
7638 RenderFrameHostImpl* frame,
Emily Stark023dbacc2020-08-27 22:31:407639 const gfx::Rect& bounds_in_root_view,
7640 blink::mojom::FocusType focus_type) {
Alexander Timin5fdeff22020-09-08 09:20:377641 OPTIONAL_TRACE_EVENT1(
7642 "content", "WebContentsImpl::OnFocusedElementChangedInFrame",
7643 "render_frame_host", base::trace_event::ToTracedValue(frame));
ekaramada110f642016-12-21 19:47:287644 RenderWidgetHostViewBase* root_view =
7645 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
7646 if (!root_view || !frame->GetView())
7647 return;
Katie De0131372020-07-09 23:03:107648 // Convert to screen coordinates from window coordinates by adding the
7649 // window's origin.
ekaramada110f642016-12-21 19:47:287650 gfx::Point origin = bounds_in_root_view.origin();
7651 origin += root_view->GetViewBounds().OffsetFromOrigin();
7652 gfx::Rect bounds_in_screen(origin, bounds_in_root_view.size());
7653
7654 root_view->FocusedNodeChanged(frame->has_focused_editable_element(),
7655 bounds_in_screen);
7656
7657 FocusedNodeDetails details = {frame->has_focused_editable_element(),
Emily Stark023dbacc2020-08-27 22:31:407658 bounds_in_screen, focus_type};
ekaramada110f642016-12-21 19:47:287659
7660 // TODO(ekaramad): We should replace this with an observer notification
7661 // (https://crbug.com/675975).
7662 NotificationService::current()->Notify(
7663 NOTIFICATION_FOCUS_CHANGED_IN_PAGE,
7664 Source<RenderViewHost>(GetRenderViewHost()),
7665 Details<FocusedNodeDetails>(&details));
Jeff Fisher709b4c52019-07-29 20:07:347666
Alexander Timin90c20c32020-08-12 15:28:327667 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7668 observer->OnFocusChangedInPage(&details);
7669 });
ekaramada110f642016-12-21 19:47:287670}
7671
Lowell Manners1de5242e2019-04-25 10:18:467672bool WebContentsImpl::DidAddMessageToConsole(
7673 blink::mojom::ConsoleMessageLevel log_level,
7674 const base::string16& message,
7675 int32_t line_no,
7676 const base::string16& source_id) {
Alexander Timin5fdeff22020-09-08 09:20:377677 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DidAddMessageToConsole",
7678 "message", base::trace_event::ValueToString(message));
7679
Alexander Timin90c20c32020-08-12 15:28:327680 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7681 observer->OnDidAddMessageToConsole(log_level, message, line_no, source_id);
7682 });
Alexander Timin5fdeff22020-09-08 09:20:377683
[email protected]a796f202012-05-30 14:14:257684 if (!delegate_)
7685 return false;
Lowell Manners1de5242e2019-04-25 10:18:467686 return delegate_->DidAddMessageToConsole(this, log_level, message, line_no,
avia90ae4e2016-11-11 20:49:337687 source_id);
[email protected]a796f202012-05-30 14:14:257688}
7689
Daniel Cheng90196c82018-04-25 21:49:147690void WebContentsImpl::DidReceiveInputEvent(
dominickn9c7ceaa32016-02-27 01:52:537691 RenderWidgetHostImpl* render_widget_host,
Emily Starkc7bd40c42020-07-21 19:12:557692 const blink::WebInputEvent& event) {
Alexander Timin5fdeff22020-09-08 09:20:377693 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DidReceiveInputEvent",
7694 "render_widget_host", render_widget_host);
7695
Emily Starkc7bd40c42020-07-21 19:12:557696 if (!IsUserInteractionInputType(event.GetType()))
Daniel Cheng90196c82018-04-25 21:49:147697 return;
7698
kenrb19221852016-04-29 17:21:407699 // Ignore unless the widget is currently in the frame tree.
7700 if (!HasMatchingWidgetHost(&frame_tree_, render_widget_host))
avic3aa8422015-11-09 20:57:227701 return;
7702
Emily Starkc7bd40c42020-07-21 19:12:557703 if (event.GetType() != blink::WebInputEvent::Type::kGestureScrollBegin)
Daniel Cheng90196c82018-04-25 21:49:147704 last_interactive_input_event_time_ = ui::EventTimeForNow();
dominickn9c7ceaa32016-02-27 01:52:537705
Alexander Timin90c20c32020-08-12 15:28:327706 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7707 observer->DidGetUserInteraction(event);
7708 });
dominickn2dd142dd2015-10-29 05:30:507709}
7710
Avi Drissman738ea192018-08-29 20:24:167711bool WebContentsImpl::ShouldIgnoreInputEvents() {
7712 WebContentsImpl* web_contents = this;
7713 while (web_contents) {
7714 if (web_contents->ignore_input_events_)
7715 return true;
7716 web_contents = web_contents->GetOuterWebContents();
7717 }
7718
7719 return false;
7720}
7721
avallee9993fca2016-11-17 06:16:507722void WebContentsImpl::FocusOwningWebContents(
7723 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:377724 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::FocusOwningWebContents",
7725 "render_widget_host", render_widget_host);
Alex Moshchukc4f0a722019-11-19 22:41:287726 RenderWidgetHostImpl* main_frame_widget_host =
7727 GetMainFrame()->GetRenderWidgetHost();
avallee9993fca2016-11-17 06:16:507728 RenderWidgetHostImpl* focused_widget =
Alex Moshchukc4f0a722019-11-19 22:41:287729 GetFocusedRenderWidgetHost(main_frame_widget_host);
avallee9993fca2016-11-17 06:16:507730
7731 if (focused_widget != render_widget_host &&
avallee8e881592016-11-19 00:39:307732 (!focused_widget ||
7733 focused_widget->delegate() != render_widget_host->delegate())) {
avallee9993fca2016-11-17 06:16:507734 SetAsFocusedWebContentsIfNecessary();
7735 }
7736}
7737
[email protected]b172aee2012-04-10 17:05:267738void WebContentsImpl::OnIgnoredUIEvent() {
Alexander Timin5fdeff22020-09-08 09:20:377739 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnIgnoredUIEvent");
[email protected]31145092011-09-30 01:49:447740 // Notify observers.
Alexander Timin90c20c32020-08-12 15:28:327741 observers_.ForEachObserver(
7742 [&](WebContentsObserver* observer) { observer->DidGetIgnoredUIEvent(); });
[email protected]fa1cf0b82010-01-15 21:49:447743}
7744
avic3aa8422015-11-09 20:57:227745void WebContentsImpl::RendererUnresponsive(
Lukasz Anforowicz52b93722018-06-20 16:11:397746 RenderWidgetHostImpl* render_widget_host,
7747 base::RepeatingClosure hang_monitor_restarter) {
Alexander Timin5fdeff22020-09-08 09:20:377748 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RendererUnresponsive",
7749 "render_widget_host", render_widget_host);
avic031d392017-03-03 03:09:427750 if (ShouldIgnoreUnresponsiveRenderer())
[email protected]e5fc1632011-08-08 07:51:537751 return;
7752
Lukasz Anforowicz4f0593d2018-09-21 18:33:547753 // Do not report hangs (to task manager, to hang renderer dialog, etc.) for
7754 // invisible tabs (like extension background page, background tabs). See
7755 // https://crbug.com/881812 for rationale and for choosing the visibility
7756 // (rather than process priority) as the signal here.
7757 if (GetVisibility() != Visibility::VISIBLE)
7758 return;
7759
Avi Drissman8920def2018-01-31 19:53:367760 if (!render_widget_host->renderer_initialized())
[email protected]55452902011-06-01 21:57:477761 return;
7762
Alexander Timin90c20c32020-08-12 15:28:327763 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7764 observer->OnRendererUnresponsive(render_widget_host->GetProcess());
7765 });
Dave Tapuskac6146c52017-12-20 22:48:157766 if (delegate_)
Lukasz Anforowicz52b93722018-06-20 16:11:397767 delegate_->RendererUnresponsive(this, render_widget_host,
7768 std::move(hang_monitor_restarter));
[email protected]420ae012009-04-24 05:16:327769}
7770
avic3aa8422015-11-09 20:57:227771void WebContentsImpl::RendererResponsive(
7772 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:377773 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderResponsive",
7774 "render_widget_host", render_widget_host);
Alexander Timin90c20c32020-08-12 15:28:327775 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7776 observer->OnRendererResponsive(render_widget_host->GetProcess());
7777 });
Alexander Timin5fdeff22020-09-08 09:20:377778
[email protected]6934a702011-12-20 00:04:517779 if (delegate_)
Avi Drissman1572e8c3c2018-02-02 19:06:367780 delegate_->RendererResponsive(this, render_widget_host);
[email protected]420ae012009-04-24 05:16:327781}
7782
Alex Moshchuk7b4f0652019-05-30 18:54:417783void WebContentsImpl::SubframeCrashed(
7784 blink::mojom::FrameVisibility visibility) {
Alexander Timin5fdeff22020-09-08 09:20:377785 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SubframeCrashed",
7786 "visibility",
7787 base::trace_event::ValueToString(visibility));
Alex Moshchuk7b4f0652019-05-30 18:54:417788 // If a subframe crashed on a hidden tab, mark the tab for reload to avoid
7789 // showing a sad frame to the user if they ever switch back to that tab. Do
7790 // this for subframes that are either visible in viewport or visible but
7791 // scrolled out of view, but skip subframes that are not rendered (e.g., via
7792 // "display:none"), since in that case the user wouldn't see a sad frame
7793 // anyway.
7794 bool did_mark_for_reload = false;
7795 if (IsHidden() && visibility != blink::mojom::FrameVisibility::kNotRendered &&
7796 base::FeatureList::IsEnabled(
7797 features::kReloadHiddenTabsWithCrashedSubframes)) {
7798 controller_.SetNeedsReload(
7799 NavigationControllerImpl::NeedsReloadType::kCrashedSubframe);
7800 did_mark_for_reload = true;
7801 UMA_HISTOGRAM_ENUMERATION(
7802 "Stability.ChildFrameCrash.TabMarkedForReload.Visibility", visibility);
7803 }
7804
7805 UMA_HISTOGRAM_BOOLEAN("Stability.ChildFrameCrash.TabMarkedForReload",
7806 did_mark_for_reload);
7807}
7808
[email protected]b172aee2012-04-10 17:05:267809void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
[email protected]feaded02012-09-25 19:12:557810 bool proceed, const base::TimeTicks& proceed_time,
[email protected]420ae012009-04-24 05:16:327811 bool* proceed_to_fire_unload) {
Alexander Timin5fdeff22020-09-08 09:20:377812 OPTIONAL_TRACE_EVENT0("content",
7813 "WebContentsImpl::BeforeUnloadFiredFromRenderManager");
Alexander Timin90c20c32020-08-12 15:28:327814 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7815 observer->BeforeUnloadFired(proceed, proceed_time);
7816 });
[email protected]6934a702011-12-20 00:04:517817 if (delegate_)
7818 delegate_->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
[email protected]e80af492013-06-24 21:52:097819 // Note: |this| might be deleted at this point.
[email protected]420ae012009-04-24 05:16:327820}
7821
[email protected]58d5cfe2013-07-10 02:40:527822void WebContentsImpl::RenderProcessGoneFromRenderManager(
[email protected]3a3d47472010-07-15 21:03:547823 RenderViewHost* render_view_host) {
[email protected]443b80e2010-12-14 00:42:237824 DCHECK(crashed_status_ != base::TERMINATION_STATUS_STILL_RUNNING);
[email protected]ec6a7eb2013-04-22 17:34:227825 RenderViewTerminated(render_view_host, crashed_status_, crashed_error_code_);
[email protected]3a3d47472010-07-15 21:03:547826}
7827
[email protected]af905902013-10-01 21:38:517828void WebContentsImpl::CancelModalDialogsForRenderManager() {
Alexander Timin5fdeff22020-09-08 09:20:377829 OPTIONAL_TRACE_EVENT0("content",
7830 "WebContentsImpl::CancelModalDialogsForRenderManager");
[email protected]af905902013-10-01 21:38:517831 // We need to cancel modal dialogs when doing a process swap, since the load
avi2460c762015-04-17 15:21:547832 // deferrer would prevent us from swapping out. We also clear the state
7833 // because this is a cross-process navigation, which means that it's a new
7834 // site that should not have to pay for the sins of its predecessor.
creis89a0f782015-05-27 16:13:177835 //
Lei Zhang6410ec1a2019-01-31 21:38:587836 // Note that we don't bother telling |browser_plugin_embedder_| because the
creis89a0f782015-05-27 16:13:177837 // cross-process navigation will either destroy the browser plugins or not
7838 // require their dialogs to close.
avi5d3b8692016-10-12 22:00:467839 if (dialog_manager_) {
avi6879fcf2017-01-21 05:27:537840 dialog_manager_->CancelDialogs(this, /*reset_state=*/true);
avi5d3b8692016-10-12 22:00:467841 }
[email protected]af905902013-10-01 21:38:517842}
7843
danakja0bce4c952020-05-12 20:40:287844void WebContentsImpl::NotifySwappedFromRenderManager(RenderFrameHost* old_frame,
7845 RenderFrameHost* new_frame,
[email protected]02d7b6e2014-06-24 21:01:507846 bool is_main_frame) {
Alexander Timin5fdeff22020-09-08 09:20:377847 TRACE_EVENT2(
7848 "content", "WebContentsImpl::NotifySwappedFromRenderManager",
7849 "old_render_frame_host", base::trace_event::ToTracedValue(old_frame),
7850 "new_render_frame_host", base::trace_event::ToTracedValue(new_frame));
[email protected]02d7b6e2014-06-24 21:01:507851 if (is_main_frame) {
danakja0bce4c952020-05-12 20:40:287852 // The |new_frame| and its various compadres are already swapped into place
7853 // for the WebContentsImpl when this method is called.
7854 DCHECK(GetMainFrame() == new_frame);
7855 DCHECK(GetRenderViewHost() == new_frame->GetRenderViewHost());
7856 DCHECK(GetRenderWidgetHostView() == new_frame->GetView());
7857
Fergal Daly6767b2e2020-02-04 03:15:167858 RenderViewHost* old_rvh =
danakja0bce4c952020-05-12 20:40:287859 old_frame ? old_frame->GetRenderViewHost() : nullptr;
7860 RenderViewHost* new_rvh = new_frame->GetRenderViewHost();
Fergal Daly6767b2e2020-02-04 03:15:167861 // |old_rvh| and |new_rvh| might be equal when navigating from a crashed
7862 // RenderFrameHost to a new same-site one. With RenderDocument, this will
7863 // happen for every same-site navigation.
7864 if (old_rvh != new_rvh)
7865 NotifyViewSwapped(old_rvh, new_rvh);
[email protected]a6b73c62013-02-11 23:05:087866
[email protected]02d7b6e2014-06-24 21:01:507867 // Make sure the visible RVH reflects the new delegate's preferences.
7868 if (delegate_)
7869 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
[email protected]d56a49e2013-02-23 00:47:397870
danakja0bce4c952020-05-12 20:40:287871 auto* rwhv = static_cast<RenderWidgetHostViewBase*>(new_frame->GetView());
7872 if (rwhv) {
7873 rwhv->SetMainFrameAXTreeID(new_frame->GetAXTreeID());
7874
7875 // The RenderWidgetHostView for the speculative RenderFrameHost is not
7876 // resized with the current RenderFrameHost while a navigation is
7877 // pending. So when we swap in the main frame, we need to update the
7878 // RenderWidgetHostView's size.
7879 //
7880 // Historically, this was done to fix b/1079768 for interstitials.
7881 rwhv->SetSize(GetSizeForMainFrame());
7882 }
[email protected]02d7b6e2014-06-24 21:01:507883 }
7884
danakja0bce4c952020-05-12 20:40:287885 NotifyFrameSwapped(old_frame, new_frame, is_main_frame);
[email protected]3a3d47472010-07-15 21:03:547886}
7887
naskof5940b9f2015-03-02 23:04:057888void WebContentsImpl::NotifyMainFrameSwappedFromRenderManager(
danakja0bce4c952020-05-12 20:40:287889 RenderFrameHost* old_frame,
7890 RenderFrameHost* new_frame) {
7891 NotifyViewSwapped(old_frame ? old_frame->GetRenderViewHost() : nullptr,
7892 new_frame->GetRenderViewHost());
naskof5940b9f2015-03-02 23:04:057893}
7894
[email protected]b172aee2012-04-10 17:05:267895NavigationControllerImpl& WebContentsImpl::GetControllerForRenderManager() {
[email protected]d1198fd2012-08-13 22:50:197896 return GetController();
[email protected]3a3d47472010-07-15 21:03:547897}
7898
dcheng59716272016-04-09 05:19:087899std::unique_ptr<WebUIImpl> WebContentsImpl::CreateWebUIForRenderFrameHost(
Miyoung Shin072d4052020-07-13 07:52:447900 RenderFrameHost* frame_host,
Denis Kuznetsov [CET]2c6f0159f2020-05-18 14:18:167901 const GURL& url) {
Miyoung Shin072d4052020-07-13 07:52:447902 return CreateWebUI(frame_host, url);
[email protected]420ae012009-04-24 05:16:327903}
7904
lfgbede6392015-09-11 21:54:067905void WebContentsImpl::CreateRenderWidgetHostViewForRenderManager(
7906 RenderViewHost* render_view_host) {
Alexander Timin5fdeff22020-09-08 09:20:377907 OPTIONAL_TRACE_EVENT1(
7908 "content", "WebContentsImpl::CreateRenderWidgetHostViewForRenderManager",
7909 "render_view_host", render_view_host);
lfgc740d4b22016-04-15 16:45:337910 RenderWidgetHostViewBase* rwh_view =
W. James MacLean13d834d2019-12-04 16:06:457911 view_->CreateViewForWidget(render_view_host->GetWidget());
danakja0bce4c952020-05-12 20:40:287912 rwh_view->SetSize(GetSizeForMainFrame());
lfgbede6392015-09-11 21:54:067913}
7914
Fergal Daly6de62f52020-10-14 01:56:447915void WebContentsImpl::ReattachOuterDelegateIfNeeded() {
7916 if (node_.outer_web_contents())
7917 ReattachToOuterWebContentsFrame();
7918}
7919
lfgbede6392015-09-11 21:54:067920bool WebContentsImpl::CreateRenderViewForRenderManager(
7921 RenderViewHost* render_view_host,
Antonio Gomesb3dd5fc2020-05-25 22:53:277922 const base::Optional<base::UnguessableToken>& opener_frame_token,
Daniel Chengabfdb002020-06-04 06:02:307923 int proxy_routing_id) {
Alexander Timin5fdeff22020-09-08 09:20:377924 TRACE_EVENT1("browser,navigation",
7925 "WebContentsImpl::CreateRenderViewForRenderManager",
7926 "render_view_host", render_view_host);
lfgbede6392015-09-11 21:54:067927
piman00cf9402017-04-03 17:09:207928 if (proxy_routing_id == MSG_ROUTING_NONE)
lfg9431efd2016-12-14 14:45:267929 CreateRenderWidgetHostViewForRenderManager(render_view_host);
lfg9431efd2016-12-14 14:45:267930
piman00cf9402017-04-03 17:09:207931 if (!static_cast<RenderViewHostImpl*>(render_view_host)
Daniel Chengabfdb002020-06-04 06:02:307932 ->CreateRenderView(opener_frame_token, proxy_routing_id,
Antonio Gomesb3dd5fc2020-05-25 22:53:277933 created_with_opener_)) {
[email protected]a4127722011-04-27 23:13:527934 return false;
[email protected]14392a52012-05-02 20:28:447935 }
W. James MacLean62198672019-06-04 16:46:107936 // Set the TextAutosizer state from the main frame's renderer on the new view,
7937 // but only if it's not for the main frame. Main frame renderers should create
7938 // this state themselves from up-to-date values, so we shouldn't override it
7939 // with the cached values.
7940 if (!render_view_host->GetMainFrame()) {
Antonio Gomesda7e03d2020-08-05 15:03:087941 auto* proxy_host = GetRenderManager()->GetRenderFrameProxyHost(
7942 render_view_host->GetSiteInstance());
7943 proxy_host->GetAssociatedRemoteMainFrame()->UpdateTextAutosizerPageInfo(
7944 text_autosizer_page_info_.Clone());
W. James MacLean62198672019-06-04 16:46:107945 }
[email protected]a4127722011-04-27 23:13:527946
Fergal Daly6de62f52020-10-14 01:56:447947 if (proxy_routing_id == MSG_ROUTING_NONE)
7948 ReattachOuterDelegateIfNeeded();
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:147949
avi2b177592014-12-10 02:08:027950 SetHistoryOffsetAndLengthForView(render_view_host,
7951 controller_.GetLastCommittedEntryIndex(),
7952 controller_.GetEntryCount());
7953
Avi Drissman7c57be72020-07-29 20:09:467954#if defined(OS_POSIX) && !defined(OS_MAC) && !defined(OS_ANDROID)
[email protected]f8233cc2011-05-31 20:24:507955 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
7956 // linux. See crbug.com/83941.
avif9ab5d942015-10-15 14:05:447957 RenderWidgetHostView* rwh_view = render_view_host->GetWidget()->GetView();
[email protected]245f7d52011-11-28 15:36:447958 if (rwh_view) {
7959 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
Fady Samuel0b911822018-04-25 13:22:167960 render_widget_host->SynchronizeVisualProperties();
[email protected]245f7d52011-11-28 15:36:447961 }
[email protected]f8233cc2011-05-31 20:24:507962#endif
7963
[email protected]420ae012009-04-24 05:16:327964 return true;
7965}
7966
mfomitchev2b8b066a2016-01-28 19:23:157967#if defined(OS_ANDROID)
[email protected]fc2b46b2014-05-03 16:33:457968
[email protected]155c7f22013-12-09 17:07:187969base::android::ScopedJavaLocalRef<jobject>
7970WebContentsImpl::GetJavaWebContents() {
mostynb042582e2015-03-16 22:13:407971 DCHECK_CURRENTLY_ON(BrowserThread::UI);
[email protected]0e813a52014-08-13 10:34:567972 return GetWebContentsAndroid()->GetJavaObject();
7973}
[email protected]155c7f22013-12-09 17:07:187974
[email protected]0e813a52014-08-13 10:34:567975WebContentsAndroid* WebContentsImpl::GetWebContentsAndroid() {
Kevin McNee576bb5d82019-05-29 16:47:517976 if (!web_contents_android_) {
7977 web_contents_android_ = std::make_unique<WebContentsAndroid>(this);
[email protected]155c7f22013-12-09 17:07:187978 }
Kevin McNee576bb5d82019-05-29 16:47:517979 return web_contents_android_.get();
7980}
7981
7982void WebContentsImpl::ClearWebContentsAndroid() {
7983 DCHECK_CURRENTLY_ON(BrowserThread::UI);
7984 web_contents_android_.reset();
[email protected]155c7f22013-12-09 17:07:187985}
7986
paulmeyerc0b762b2016-04-13 11:55:177987void WebContentsImpl::ActivateNearestFindResult(float x,
7988 float y) {
Alexander Timin5fdeff22020-09-08 09:20:377989 OPTIONAL_TRACE_EVENT0("content",
7990 "WebContentsImpl::ActivateNearestFindResult");
paulmeyerc0b762b2016-04-13 11:55:177991 GetOrCreateFindRequestManager()->ActivateNearestFindResult(x, y);
7992}
7993
7994void WebContentsImpl::RequestFindMatchRects(int current_version) {
Alexander Timin5fdeff22020-09-08 09:20:377995 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::RequestFindMatchRects");
paulmeyerc0b762b2016-04-13 11:55:177996 GetOrCreateFindRequestManager()->RequestFindMatchRects(current_version);
7997}
7998
rockot400ea35b2016-10-15 19:15:327999service_manager::InterfaceProvider* WebContentsImpl::GetJavaInterfaces() {
sammcf5f1b0f2016-09-20 23:05:118000 if (!java_interfaces_) {
Gyuyoung Kim6c9ce9022019-11-26 05:40:088001 mojo::PendingRemote<service_manager::mojom::InterfaceProvider> provider;
8002 BindInterfaceRegistryForWebContents(
8003 provider.InitWithNewPipeAndPassReceiver(), this);
rockot400ea35b2016-10-15 19:15:328004 java_interfaces_.reset(new service_manager::InterfaceProvider);
sammcf5f1b0f2016-09-20 23:05:118005 java_interfaces_->Bind(std::move(provider));
8006 }
8007 return java_interfaces_.get();
8008}
8009
Francois Doray6c26f3342018-08-24 17:17:228010#endif
8011
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:418012bool WebContentsImpl::CompletedFirstVisuallyNonEmptyPaint() {
Carlos Caballero91fffb22019-10-29 15:24:308013 return GetRenderViewHost()->did_first_visually_non_empty_paint();
spqchane72c3cb2017-06-30 23:02:108014}
8015
pkotwicz75ca8ffd2016-02-16 23:10:198016void WebContentsImpl::OnDidDownloadImage(
Avi Drissmana5a52dd2018-03-27 03:39:028017 ImageDownloadCallback callback,
pkotwicz75ca8ffd2016-02-16 23:10:198018 int id,
8019 const GURL& image_url,
leon.hancbc4bc3c2016-02-26 07:08:528020 int32_t http_status_code,
leon.hanc2228532016-08-16 05:59:188021 const std::vector<SkBitmap>& images,
8022 const std::vector<gfx::Size>& original_image_sizes) {
Alexander Timin5fdeff22020-09-08 09:20:378023 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnDidDownloadImage",
8024 "image_url",
8025 base::trace_event::ValueToString(image_url));
Avi Drissmana5a52dd2018-03-27 03:39:028026 std::move(callback).Run(id, http_status_code, image_url, images,
8027 original_image_sizes);
pkotwicz75ca8ffd2016-02-16 23:10:198028}
8029
[email protected]6fba26d2014-04-29 09:38:288030void WebContentsImpl::OnDialogClosed(int render_process_id,
8031 int render_frame_id,
Dave Tapuskacdf545cc2020-01-23 18:38:528032 JavaScriptDialogCallback response_callback,
Avi Drissman1a55a9d62020-03-10 18:56:458033 base::ScopedClosureRunner fullscreen_block,
[email protected]87de04b02014-04-08 22:14:498034 bool dialog_was_suppressed,
[email protected]b172aee2012-04-10 17:05:268035 bool success,
[email protected]fcf75d42013-12-03 20:11:268036 const base::string16& user_input) {
[email protected]6fba26d2014-04-29 09:38:288037 RenderFrameHostImpl* rfh = RenderFrameHostImpl::FromID(render_process_id,
8038 render_frame_id);
Alexander Timin5fdeff22020-09-08 09:20:378039 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnDialogClosed",
8040 "render_frame_host",
8041 base::trace_event::ToTracedValue(rfh));
[email protected]87de04b02014-04-08 22:14:498042 last_dialog_suppressed_ = dialog_was_suppressed;
Avi Drissman1a55a9d62020-03-10 18:56:458043 fullscreen_block.RunAndReset();
[email protected]87de04b02014-04-08 22:14:498044
Charlie Reis96077362019-07-04 00:34:048045 javascript_dialog_navigation_deferrer_.reset();
8046
[email protected]beb440c2009-11-06 04:08:548047 if (is_showing_before_unload_dialog_ && !success) {
clamybc6f4152016-04-01 20:14:238048 // It is possible for the current RenderFrameHost to have changed in the
8049 // meantime. Do not reset the navigation state in that case.
8050 if (rfh && rfh == rfh->frame_tree_node()->current_frame_host()) {
clamy44e84ce2016-02-22 15:38:258051 rfh->frame_tree_node()->BeforeUnloadCanceled();
clamybc6f4152016-04-01 20:14:238052 controller_.DiscardNonCommittedEntries();
8053 }
[email protected]ec8e8b02013-06-19 04:57:108054
Charles Reis15d60b132017-11-03 17:43:478055 // Update the URL display either way, to avoid showing a stale URL.
8056 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
8057
Alexander Timin90c20c32020-08-12 15:28:328058 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8059 observer->BeforeUnloadDialogCancelled();
8060 });
[email protected]beb440c2009-11-06 04:08:548061 }
[email protected]87de04b02014-04-08 22:14:498062
Dave Tapuskacdf545cc2020-01-23 18:38:528063 std::move(response_callback).Run(success, user_input);
Pavel Feldman3c1842b2017-08-02 05:00:168064
Dave Tapuskacdf545cc2020-01-23 18:38:528065 std::vector<protocol::PageHandler*> page_handlers =
8066 protocol::PageHandler::EnabledForWebContents(this);
8067 for (auto* handler : page_handlers)
8068 handler->DidCloseJavaScriptDialog(success, user_input);
avi1c51fb62017-02-27 20:43:038069
8070 is_showing_javascript_dialog_ = false;
8071 is_showing_before_unload_dialog_ = false;
[email protected]beb440c2009-11-06 04:08:548072}
8073
[email protected]1ac10dca2013-08-20 20:47:048074bool WebContentsImpl::IsHidden() {
Francois Doraye6161152018-03-27 22:05:378075 return !IsBeingCaptured() && visibility_ != Visibility::VISIBLE;
[email protected]1ac10dca2013-08-20 20:47:048076}
8077
rob97250742015-12-10 17:45:158078int WebContentsImpl::GetOuterDelegateFrameTreeNodeId() {
lfg601233692017-03-06 22:45:448079 return node_.outer_contents_frame_tree_node_id();
lazyboy6ec48b2a2015-06-29 15:18:148080}
8081
ekaramadaeb3c5c2016-11-09 03:22:358082RenderWidgetHostImpl* WebContentsImpl::GetFullscreenRenderWidgetHost() const {
8083 return RenderWidgetHostImpl::FromID(fullscreen_widget_process_id_,
8084 fullscreen_widget_routing_id_);
8085}
8086
[email protected]b0936d22013-11-28 06:47:368087RenderFrameHostManager* WebContentsImpl::GetRenderManager() const {
[email protected]fa944cb82013-11-15 17:51:218088 return frame_tree_.root()->render_manager();
8089}
8090
[email protected]f8497342013-02-05 22:15:028091BrowserPluginGuest* WebContentsImpl::GetBrowserPluginGuest() const {
[email protected]7a846df2012-09-20 19:17:398092 return browser_plugin_guest_.get();
8093}
8094
Albert J. Wongc55cc64d2018-10-12 02:50:048095void WebContentsImpl::SetBrowserPluginGuest(
8096 std::unique_ptr<BrowserPluginGuest> guest) {
Alexander Timin5fdeff22020-09-08 09:20:378097 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetBrowserPluginGuest");
Albert J. Wongc55cc64d2018-10-12 02:50:048098 DCHECK(!browser_plugin_guest_);
8099 DCHECK(guest);
8100 browser_plugin_guest_ = std::move(guest);
[email protected]738f57a2013-06-29 21:06:548101}
8102
Aidan Wolter52bcc12a2018-11-14 03:27:298103base::UnguessableToken WebContentsImpl::GetAudioGroupId() {
Aidan Wolter52bcc12a2018-11-14 03:27:298104 return GetAudioStreamFactory()->group_id();
8105}
8106
Miyoung Shin5709ab02020-02-19 06:50:418107const std::vector<blink::mojom::FaviconURLPtr>&
8108WebContentsImpl::GetFaviconURLs() {
Mounir Lamouri7b4a1f232019-12-23 16:32:108109 return favicon_urls_;
8110}
8111
Mugdha Lakhani0a0d7862020-07-29 09:58:458112// The Mac implementation of the next two methods is in
8113// web_contents_impl_mac.mm
Avi Drissmand4d79f72020-07-30 18:35:188114#if !defined(OS_MAC)
Mugdha Lakhani0a0d7862020-07-29 09:58:458115
8116void WebContentsImpl::Resize(const gfx::Rect& new_bounds) {
Alexander Timin5fdeff22020-09-08 09:20:378117 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Resize");
Mugdha Lakhani0a0d7862020-07-29 09:58:458118#if defined(USE_AURA)
8119 aura::Window* window = GetNativeView();
8120 window->SetBounds(gfx::Rect(window->bounds().origin(), new_bounds.size()));
8121#elif defined(OS_ANDROID)
8122 content::RenderWidgetHostView* view = GetRenderWidgetHostView();
8123 if (view)
8124 view->SetBounds(new_bounds);
8125#endif
8126}
8127
8128gfx::Size WebContentsImpl::GetSize() {
8129#if defined(USE_AURA)
8130 aura::Window* window = GetNativeView();
8131 return window->bounds().size();
8132#elif defined(OS_ANDROID)
8133 ui::ViewAndroid* view_android = GetNativeView();
8134 return view_android->bounds().size();
8135#endif
8136}
8137
Avi Drissmand4d79f72020-07-30 18:35:188138#endif // !defined(OS_MAC)
Mugdha Lakhani0a0d7862020-07-29 09:58:458139
[email protected]f8497342013-02-05 22:15:028140BrowserPluginEmbedder* WebContentsImpl::GetBrowserPluginEmbedder() const {
[email protected]7a846df2012-09-20 19:17:398141 return browser_plugin_embedder_.get();
8142}
[email protected]8ff00d72012-10-23 19:12:218143
fsamuel60b42282015-03-10 03:29:148144void WebContentsImpl::CreateBrowserPluginEmbedderIfNecessary() {
Alexander Timin5fdeff22020-09-08 09:20:378145 OPTIONAL_TRACE_EVENT0(
8146 "content", "WebContentsImpl::CreateBrowserPluginEmbedderIfNecessary");
fsamuel60b42282015-03-10 03:29:148147 if (browser_plugin_embedder_)
8148 return;
8149 browser_plugin_embedder_.reset(BrowserPluginEmbedder::Create(this));
8150}
8151
danakja0bce4c952020-05-12 20:40:288152gfx::Size WebContentsImpl::GetSizeForMainFrame() {
8153 if (delegate_) {
8154 // The delegate has a chance to specify a size independent of the UI.
8155 gfx::Size delegate_size = delegate_->GetSizeForNewRenderView(this);
8156 if (!delegate_size.IsEmpty())
8157 return delegate_size;
8158 }
8159
8160 // Device emulation, when enabled, can specify a size independent of the UI.
8161 if (!device_emulation_size_.IsEmpty())
8162 return device_emulation_size_;
8163
8164 return GetContainerBounds().size();
[email protected]dc0fd432013-08-27 15:29:218165}
8166
[email protected]ae7eeda2014-07-04 01:53:268167void WebContentsImpl::OnFrameRemoved(RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:378168 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnFrameRemoved",
8169 "render_frame_host",
8170 base::trace_event::ToTracedValue(render_frame_host));
Alexander Timin90c20c32020-08-12 15:28:328171 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8172 observer->FrameDeleted(render_frame_host);
8173 });
[email protected]9b159a52013-10-03 17:24:558174}
8175
[email protected]222f5822014-02-05 23:40:498176void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size& old_size) {
Alexander Timin5fdeff22020-09-08 09:20:378177 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnPreferredSizeChanged");
[email protected]222f5822014-02-05 23:40:498178 if (!delegate_)
8179 return;
8180 const gfx::Size new_size = GetPreferredSize();
8181 if (new_size != old_size)
8182 delegate_->UpdatePreferredSize(this, new_size);
8183}
8184
Miyoung Shin072d4052020-07-13 07:52:448185std::unique_ptr<WebUIImpl> WebContentsImpl::CreateWebUI(
8186 RenderFrameHost* frame_host,
8187 const GURL& url) {
Alexander Timin5fdeff22020-09-08 09:20:378188 TRACE_EVENT2("content", "WebContentsImpl::CreateWebUI", "frame_host",
8189 base::trace_event::ToTracedValue(frame_host), "url",
8190 base::trace_event::ValueToString(url));
Miyoung Shin072d4052020-07-13 07:52:448191 std::unique_ptr<WebUIImpl> web_ui =
8192 std::make_unique<WebUIImpl>(this, frame_host);
Lei Zhangee3b63ad2018-06-06 23:25:318193 std::unique_ptr<WebUIController> controller(
avie865b1d2016-10-24 19:42:598194 WebUIControllerFactoryRegistry::GetInstance()
Lei Zhangee3b63ad2018-06-06 23:25:318195 ->CreateWebUIControllerForURL(web_ui.get(), url));
dbeama1b926a2015-08-31 23:17:518196 if (controller) {
Lei Zhangee3b63ad2018-06-06 23:25:318197 web_ui->SetController(std::move(controller));
dbeama1b926a2015-08-31 23:17:518198 return web_ui;
8199 }
8200
avie865b1d2016-10-24 19:42:598201 return nullptr;
dbeama1b926a2015-08-31 23:17:518202}
8203
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:418204FindRequestManager* WebContentsImpl::GetFindRequestManager() {
8205 for (auto* contents = this; contents;
paulmeyerfeafc2d2017-04-25 21:46:408206 contents = contents->GetOuterWebContents()) {
8207 if (contents->find_request_manager_)
8208 return contents->find_request_manager_.get();
8209 }
8210
8211 return nullptr;
8212}
8213
paulmeyerc0b762b2016-04-13 11:55:178214FindRequestManager* WebContentsImpl::GetOrCreateFindRequestManager() {
paulmeyerfeafc2d2017-04-25 21:46:408215 if (FindRequestManager* manager = GetFindRequestManager())
8216 return manager;
8217
Ehsan Karamad6beb2ea2018-11-25 18:15:138218 DCHECK(!browser_plugin_guest_ || GetOuterWebContents());
8219
paulmeyerfeafc2d2017-04-25 21:46:408220 // No existing FindRequestManager found, so one must be created.
Fergal Daly55b6d722020-09-11 07:56:338221 find_request_manager_ = std::make_unique<FindRequestManager>(this);
paulmeyerfeafc2d2017-04-25 21:46:408222
8223 // Concurrent find sessions must not overlap, so destroy any existing
8224 // FindRequestManagers in any inner WebContentses.
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:168225 for (WebContents* contents : GetWebContentsAndAllInner()) {
8226 auto* web_contents_impl = static_cast<WebContentsImpl*>(contents);
8227 if (web_contents_impl == this)
paulmeyerfeafc2d2017-04-25 21:46:408228 continue;
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:168229 if (web_contents_impl->find_request_manager_) {
8230 web_contents_impl->find_request_manager_->StopFinding(
8231 STOP_FIND_ACTION_CLEAR_SELECTION);
8232 web_contents_impl->find_request_manager_.release();
paulmeyerfeafc2d2017-04-25 21:46:408233 }
8234 }
paulmeyerc0b762b2016-04-13 11:55:178235
8236 return find_request_manager_.get();
8237}
8238
8239void WebContentsImpl::NotifyFindReply(int request_id,
8240 int number_of_matches,
8241 const gfx::Rect& selection_rect,
8242 int active_match_ordinal,
8243 bool final_update) {
Alexander Timin5fdeff22020-09-08 09:20:378244 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::NotifyFindReply");
Sebastien Marchandcf97ed52017-07-24 23:50:348245 if (delegate_ && !is_being_destroyed_ &&
Lukasz Anforowicze9ae3722017-09-29 17:37:388246 !GetMainFrame()->GetProcess()->FastShutdownStarted()) {
paulmeyerc0b762b2016-04-13 11:55:178247 delegate_->FindReply(this, request_id, number_of_matches, selection_rect,
8248 active_match_ordinal, final_update);
8249 }
8250}
8251
ortuno467e5792016-06-10 04:32:398252void WebContentsImpl::IncrementBluetoothConnectedDeviceCount() {
Alexander Timin5fdeff22020-09-08 09:20:378253 OPTIONAL_TRACE_EVENT0(
8254 "content", "WebContentsImpl::IncrementBluetoothConnectedDeviceCount");
ortuno467e5792016-06-10 04:32:398255 // Trying to invalidate the tab state while being destroyed could result in a
8256 // use after free.
8257 if (IsBeingDestroyed()) {
8258 return;
8259 }
8260 // Notify for UI updates if the state changes.
8261 bluetooth_connected_device_count_++;
8262 if (bluetooth_connected_device_count_ == 1) {
Francois Doray66766a572019-12-17 20:56:498263 OnIsConnectedToBluetoothDeviceChanged(true);
ortuno467e5792016-06-10 04:32:398264 }
8265}
8266
8267void WebContentsImpl::DecrementBluetoothConnectedDeviceCount() {
Alexander Timin5fdeff22020-09-08 09:20:378268 OPTIONAL_TRACE_EVENT0(
8269 "content", "WebContentsImpl::DecrementBluetoothConnectedDeviceCount");
ortuno467e5792016-06-10 04:32:398270 // Trying to invalidate the tab state while being destroyed could result in a
8271 // use after free.
8272 if (IsBeingDestroyed()) {
8273 return;
8274 }
8275 // Notify for UI updates if the state changes.
Lukasz Anforowicze9ae3722017-09-29 17:37:388276 DCHECK_NE(bluetooth_connected_device_count_, 0u);
ortuno467e5792016-06-10 04:32:398277 bluetooth_connected_device_count_--;
8278 if (bluetooth_connected_device_count_ == 0) {
Francois Doray66766a572019-12-17 20:56:498279 OnIsConnectedToBluetoothDeviceChanged(false);
8280 }
8281}
8282
8283void WebContentsImpl::OnIsConnectedToBluetoothDeviceChanged(
8284 bool is_connected_to_bluetooth_device) {
Alexander Timin5fdeff22020-09-08 09:20:378285 OPTIONAL_TRACE_EVENT0(
8286 "content", "WebContentsImpl::OnIsConnectedToBluetoothDeviceChanged");
Francois Doray66766a572019-12-17 20:56:498287 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
Alexander Timin90c20c32020-08-12 15:28:328288 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8289 observer->OnIsConnectedToBluetoothDeviceChanged(
Francois Doray66766a572019-12-17 20:56:498290 is_connected_to_bluetooth_device);
Alexander Timin90c20c32020-08-12 15:28:328291 });
ortuno467e5792016-06-10 04:32:398292}
8293
Ovidio Henriquez76696f62020-07-08 03:06:598294void WebContentsImpl::IncrementBluetoothScanningSessionsCount() {
Alexander Timin5fdeff22020-09-08 09:20:378295 OPTIONAL_TRACE_EVENT0(
8296 "content", "WebContentsImpl::IncrementBluetoothScanningSessionsCount");
Ovidio Henriquez76696f62020-07-08 03:06:598297 // Trying to invalidate the tab state while being destroyed could result in a
8298 // use after free.
8299 if (IsBeingDestroyed())
8300 return;
8301
8302 // Notify for UI updates if the state changes.
8303 bluetooth_scanning_sessions_count_++;
8304 if (bluetooth_scanning_sessions_count_ == 1)
8305 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8306}
8307
8308void WebContentsImpl::DecrementBluetoothScanningSessionsCount() {
Alexander Timin5fdeff22020-09-08 09:20:378309 OPTIONAL_TRACE_EVENT0(
8310 "content", "WebContentsImpl::DecrementBluetoothScanningSessionsCount");
Ovidio Henriquez76696f62020-07-08 03:06:598311 // Trying to invalidate the tab state while being destroyed could result in a
8312 // use after free.
8313 if (IsBeingDestroyed())
8314 return;
8315
8316 DCHECK_NE(0u, bluetooth_scanning_sessions_count_);
8317 bluetooth_scanning_sessions_count_--;
8318 if (bluetooth_scanning_sessions_count_ == 0)
8319 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8320}
8321
Reilly Grant5e7c79b22019-04-09 17:26:208322void WebContentsImpl::IncrementSerialActiveFrameCount() {
Alexander Timin5fdeff22020-09-08 09:20:378323 OPTIONAL_TRACE_EVENT0("content",
8324 "WebContentsImpl::IncrementSerialActiveFrameCount");
Reilly Grant5e7c79b22019-04-09 17:26:208325 // Trying to invalidate the tab state while being destroyed could result in a
8326 // use after free.
8327 if (IsBeingDestroyed())
8328 return;
8329
8330 // Notify for UI updates if the state changes.
8331 serial_active_frame_count_++;
8332 if (serial_active_frame_count_ == 1)
8333 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8334}
8335
8336void WebContentsImpl::DecrementSerialActiveFrameCount() {
Alexander Timin5fdeff22020-09-08 09:20:378337 OPTIONAL_TRACE_EVENT0("content",
8338 "WebContentsImpl::DecrementSerialActiveFrameCount");
Reilly Grant5e7c79b22019-04-09 17:26:208339 // Trying to invalidate the tab state while being destroyed could result in a
8340 // use after free.
8341 if (IsBeingDestroyed())
8342 return;
8343
8344 // Notify for UI updates if the state changes.
8345 DCHECK_NE(0u, serial_active_frame_count_);
8346 serial_active_frame_count_--;
8347 if (serial_active_frame_count_ == 0)
8348 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8349}
8350
Matt Reynoldse8c6c1f2019-11-02 09:53:538351void WebContentsImpl::IncrementHidActiveFrameCount() {
Alexander Timin5fdeff22020-09-08 09:20:378352 OPTIONAL_TRACE_EVENT0("content",
8353 "WebContentsImpl::IncrementHidActiveFrameCount");
Matt Reynoldse8c6c1f2019-11-02 09:53:538354 // Trying to invalidate the tab state while being destroyed could result in a
8355 // use after free.
8356 if (IsBeingDestroyed())
8357 return;
8358
8359 // Notify for UI updates if the active frame count transitions from zero to
8360 // non-zero.
8361 hid_active_frame_count_++;
8362 if (hid_active_frame_count_ == 1)
8363 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8364}
8365
8366void WebContentsImpl::DecrementHidActiveFrameCount() {
Alexander Timin5fdeff22020-09-08 09:20:378367 OPTIONAL_TRACE_EVENT0("content",
8368 "WebContentsImpl::DecrementHidActiveFrameCount");
Matt Reynoldse8c6c1f2019-11-02 09:53:538369 // Trying to invalidate the tab state while being destroyed could result in a
8370 // use after free.
8371 if (IsBeingDestroyed())
8372 return;
8373
8374 // Notify for UI updates if the active frame count transitions from non-zero
8375 // to zero.
8376 DCHECK_NE(0u, hid_active_frame_count_);
8377 hid_active_frame_count_--;
8378 if (hid_active_frame_count_ == 0)
8379 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8380}
8381
Marijn Kruisselbrink29051042019-08-06 22:56:558382void WebContentsImpl::IncrementNativeFileSystemHandleCount() {
Alexander Timin5fdeff22020-09-08 09:20:378383 OPTIONAL_TRACE_EVENT0(
8384 "content", "WebContentsImpl::IncrementNativeFileSystemHandleCount");
Marijn Kruisselbrink29051042019-08-06 22:56:558385 // Trying to invalidate the tab state while being destroyed could result in a
8386 // use after free.
8387 if (IsBeingDestroyed())
8388 return;
8389
8390 // Notify for UI updates if the state changes. Need both TYPE_TAB and TYPE_URL
8391 // to update both the tab-level usage indicator and the usage indicator in the
8392 // omnibox.
8393 native_file_system_handle_count_++;
8394 if (native_file_system_handle_count_ == 1) {
8395 NotifyNavigationStateChanged(static_cast<content::InvalidateTypes>(
8396 INVALIDATE_TYPE_TAB | INVALIDATE_TYPE_URL));
8397 }
8398}
8399
8400void WebContentsImpl::DecrementNativeFileSystemHandleCount() {
Alexander Timin5fdeff22020-09-08 09:20:378401 OPTIONAL_TRACE_EVENT0(
8402 "content", "WebContentsImpl::DecrementNativeFileSystemHandleCount");
Marijn Kruisselbrink29051042019-08-06 22:56:558403 // Trying to invalidate the tab state while being destroyed could result in a
8404 // use after free.
8405 if (IsBeingDestroyed())
8406 return;
8407
8408 // Notify for UI updates if the state changes. Need both TYPE_TAB and TYPE_URL
8409 // to update both the tab-level usage indicator and the usage indicator in the
8410 // omnibox.
8411 DCHECK_NE(0u, native_file_system_handle_count_);
8412 native_file_system_handle_count_--;
8413 if (native_file_system_handle_count_ == 0) {
8414 NotifyNavigationStateChanged(static_cast<content::InvalidateTypes>(
8415 INVALIDATE_TYPE_TAB | INVALIDATE_TYPE_URL));
8416 }
8417}
8418
zqzhang8ac49002017-03-16 21:51:358419void WebContentsImpl::SetHasPersistentVideo(bool has_persistent_video) {
Alexander Timin5fdeff22020-09-08 09:20:378420 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetHasPersistentVideo",
8421 "has_persistent_video", has_persistent_video,
8422 "had_persistent_value", has_persistent_video_);
zqzhang8ac49002017-03-16 21:51:358423 if (has_persistent_video_ == has_persistent_video)
mlamouri5cd9ae82017-02-18 11:05:098424 return;
8425
zqzhang8ac49002017-03-16 21:51:358426 has_persistent_video_ = has_persistent_video;
mlamouri5cd9ae82017-02-18 11:05:098427 NotifyPreferencesChanged();
zqzhang8ac49002017-03-16 21:51:358428 media_web_contents_observer()->RequestPersistentVideo(has_persistent_video);
mlamouri5cd9ae82017-02-18 11:05:098429}
8430
Ian Vollick5d5c37f2019-06-19 22:50:578431void WebContentsImpl::SetSpatialNavigationDisabled(bool disabled) {
Alexander Timin5fdeff22020-09-08 09:20:378432 OPTIONAL_TRACE_EVENT2(
8433 "content", "WebContentsImpl::SetSpatialNavigationDisabled", "disabled",
8434 disabled, "was_disabled", is_spatial_navigation_disabled_);
Ian Vollick5d5c37f2019-06-19 22:50:578435 if (is_spatial_navigation_disabled_ == disabled)
8436 return;
8437
8438 is_spatial_navigation_disabled_ = disabled;
8439 NotifyPreferencesChanged();
8440}
8441
paulmeyerfeafc2d2017-04-25 21:46:408442void WebContentsImpl::BrowserPluginGuestWillDetach() {
Alexander Timin5fdeff22020-09-08 09:20:378443 OPTIONAL_TRACE_EVENT0("content",
8444 "WebContentsImpl::BrowserPluginGuestWillDetach");
paulmeyerfeafc2d2017-04-25 21:46:408445 WebContentsImpl* outermost = GetOutermostWebContents();
8446 if (this != outermost && ContainsOrIsFocusedWebContents())
8447 outermost->SetAsFocusedWebContentsIfNecessary();
8448}
8449
Becca Hughes112832e2019-06-11 17:19:028450PictureInPictureResult WebContentsImpl::EnterPictureInPicture(
Mounir Lamouri11e9ef42018-05-22 03:10:168451 const viz::SurfaceId& surface_id,
8452 const gfx::Size& natural_size) {
Alexander Timin5fdeff22020-09-08 09:20:378453 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::EnterPictureInPicture");
François Beaufortf09e4462019-01-18 14:34:518454 return delegate_
8455 ? delegate_->EnterPictureInPicture(this, surface_id, natural_size)
Becca Hughes112832e2019-06-11 17:19:028456 : PictureInPictureResult::kNotSupported;
Mounir Lamouri11e9ef42018-05-22 03:10:168457}
8458
Mounir Lamouri6d759e12018-05-16 20:01:308459void WebContentsImpl::ExitPictureInPicture() {
Alexander Timin5fdeff22020-09-08 09:20:378460 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ExitPictureInPicture");
Mounir Lamouri6d759e12018-05-16 20:01:308461 if (delegate_)
8462 delegate_->ExitPictureInPicture();
8463}
8464
paulmeyerc0b762b2016-04-13 11:55:178465#if defined(OS_ANDROID)
8466void WebContentsImpl::NotifyFindMatchRectsReply(
8467 int version,
8468 const std::vector<gfx::RectF>& rects,
8469 const gfx::RectF& active_rect) {
Alexander Timin5fdeff22020-09-08 09:20:378470 OPTIONAL_TRACE_EVENT0("content",
8471 "WebContentsImpl::NotifyFindMatchRectsReply");
paulmeyerc0b762b2016-04-13 11:55:178472 if (delegate_)
8473 delegate_->FindMatchRectsReply(this, version, rects, active_rect);
8474}
8475#endif
8476
[email protected]34ff1cfc2014-08-20 06:16:058477void WebContentsImpl::SetForceDisableOverscrollContent(bool force_disable) {
Alexander Timin5fdeff22020-09-08 09:20:378478 OPTIONAL_TRACE_EVENT1("content",
8479 "WebContentsImpl::SetForceDisableOverscrollContent",
8480 "force_disable", force_disable);
[email protected]34ff1cfc2014-08-20 06:16:058481 force_disable_overscroll_content_ = force_disable;
8482 if (view_)
8483 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
8484}
8485
Jianzhou Fengd8720c72018-01-18 03:06:308486bool WebContentsImpl::SetDeviceEmulationSize(const gfx::Size& new_size) {
Alexander Timin5fdeff22020-09-08 09:20:378487 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetDeviceEmulationSize");
Jianzhou Fengd8720c72018-01-18 03:06:308488 device_emulation_size_ = new_size;
8489 RenderWidgetHostView* rwhv = GetMainFrame()->GetView();
8490
8491 const gfx::Size current_size = rwhv->GetViewBounds().size();
8492 if (view_size_before_emulation_.IsEmpty())
8493 view_size_before_emulation_ = current_size;
8494
8495 if (current_size != new_size)
8496 rwhv->SetSize(new_size);
8497
8498 return current_size != new_size;
8499}
8500
8501void WebContentsImpl::ClearDeviceEmulationSize() {
Alexander Timin5fdeff22020-09-08 09:20:378502 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ClearDeviceEmulationSize");
Jianzhou Fengd8720c72018-01-18 03:06:308503 RenderWidgetHostView* rwhv = GetMainFrame()->GetView();
8504 // WebContentsView could get resized during emulation, which also resizes
8505 // RWHV. If it happens, assume user would like to keep using the size after
8506 // emulation.
8507 // TODO(jzfeng): Prohibit resizing RWHV through any other means (at least when
8508 // WebContentsView size changes).
Dmitry Gozmanc63707182018-03-06 00:09:398509 if (!view_size_before_emulation_.IsEmpty() && rwhv &&
8510 rwhv->GetViewBounds().size() == device_emulation_size_) {
Jianzhou Fengd8720c72018-01-18 03:06:308511 rwhv->SetSize(view_size_before_emulation_);
Dmitry Gozmanc63707182018-03-06 00:09:398512 }
Jianzhou Fengd8720c72018-01-18 03:06:308513 device_emulation_size_ = gfx::Size();
8514 view_size_before_emulation_ = gfx::Size();
8515}
8516
Max Morin5bc74f52018-05-09 07:00:218517ForwardingAudioStreamFactory* WebContentsImpl::GetAudioStreamFactory() {
8518 if (!audio_stream_factory_) {
8519 audio_stream_factory_.emplace(
8520 this,
Max Morinddebb972018-09-20 10:04:148521 // BrowserMainLoop::GetInstance() may be null in unit tests.
8522 BrowserMainLoop::GetInstance()
8523 ? static_cast<media::UserInputMonitorBase*>(
8524 BrowserMainLoop::GetInstance()->user_input_monitor())
8525 : nullptr,
Ken Rockot72964402019-12-06 10:40:518526 AudioStreamBrokerFactory::CreateImpl());
Max Morin5bc74f52018-05-09 07:00:218527 }
8528
8529 return &*audio_stream_factory_;
8530}
8531
dalecurtis88c240072015-12-09 02:11:188532void WebContentsImpl::MediaStartedPlaying(
billorr21c005d2016-11-17 03:57:048533 const WebContentsObserver::MediaPlayerInfo& media_info,
Mounir Lamouri0f5bdf52019-04-04 16:32:358534 const MediaPlayerId& id) {
Alexander Timin5fdeff22020-09-08 09:20:378535 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MediaStartedPlaying");
billorr21c005d2016-11-17 03:57:048536 if (media_info.has_video)
8537 currently_playing_video_count_++;
8538
Alexander Timin90c20c32020-08-12 15:28:328539 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8540 observer->MediaStartedPlaying(media_info, id);
8541 });
dalecurtis88c240072015-12-09 02:11:188542}
8543
8544void WebContentsImpl::MediaStoppedPlaying(
billorr21c005d2016-11-17 03:57:048545 const WebContentsObserver::MediaPlayerInfo& media_info,
Mounir Lamouri0f5bdf52019-04-04 16:32:358546 const MediaPlayerId& id,
Becca Hughes220bfc102017-11-14 18:24:078547 WebContentsObserver::MediaStoppedReason reason) {
Alexander Timin5fdeff22020-09-08 09:20:378548 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MediaStoppedPlaying");
billorr21c005d2016-11-17 03:57:048549 if (media_info.has_video)
8550 currently_playing_video_count_--;
8551
Alexander Timin90c20c32020-08-12 15:28:328552 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8553 observer->MediaStoppedPlaying(media_info, id, reason);
8554 });
billorr21c005d2016-11-17 03:57:048555}
8556
Mounir Lamouri0f5bdf52019-04-04 16:32:358557void WebContentsImpl::MediaResized(const gfx::Size& size,
8558 const MediaPlayerId& id) {
Alexander Timin5fdeff22020-09-08 09:20:378559 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MediaResized");
peconn257951522017-06-09 18:24:598560 cached_video_sizes_[id] = size;
8561
Alexander Timin90c20c32020-08-12 15:28:328562 observers_.ForEachObserver(
8563 [&](WebContentsObserver* observer) { observer->MediaResized(size, id); });
peconn257951522017-06-09 18:24:598564}
8565
Michael Crousee75c7a42020-07-31 21:11:558566void WebContentsImpl::MediaBufferUnderflow(const MediaPlayerId& id) {
Alexander Timin5fdeff22020-09-08 09:20:378567 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MediaBufferUnderflow");
Alexander Timin90c20c32020-08-12 15:28:328568 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8569 observer->MediaBufferUnderflow(id);
8570 });
Michael Crousee75c7a42020-07-31 21:11:558571}
8572
rajendrant4c288462020-10-13 07:35:358573void WebContentsImpl::MediaPlayerSeek(const MediaPlayerId& id) {
8574 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MediaPlayerSeek");
8575 observers_.ForEachObserver(
8576 [&](WebContentsObserver* observer) { observer->MediaPlayerSeek(id); });
8577}
8578
Peter E Conneccb34c22017-09-08 09:37:588579void WebContentsImpl::MediaEffectivelyFullscreenChanged(bool is_fullscreen) {
Alexander Timin5fdeff22020-09-08 09:20:378580 OPTIONAL_TRACE_EVENT1("content",
8581 "WebContentsImpl::MediaEffectivelyFullscreenChanged",
8582 "is_fullscreen", is_fullscreen);
Alexander Timin90c20c32020-08-12 15:28:328583 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8584 observer->MediaEffectivelyFullscreenChanged(is_fullscreen);
8585 });
Peter E Conneccb34c22017-09-08 09:37:588586}
8587
Peter Conn31c726a2017-08-17 11:07:348588base::Optional<gfx::Size> WebContentsImpl::GetFullscreenVideoSize() {
Mounir Lamouri0f5bdf52019-04-04 16:32:358589 base::Optional<MediaPlayerId> id =
Peter Conn31c726a2017-08-17 11:07:348590 media_web_contents_observer_->GetFullscreenVideoMediaPlayerId();
Jan Wilken Dörrie531be7ca2019-06-07 10:05:578591 if (id && base::Contains(cached_video_sizes_, id.value()))
Peter Conn31c726a2017-08-17 11:07:348592 return base::Optional<gfx::Size>(cached_video_sizes_[id.value()]);
Lei Zhang6410ec1a2019-01-31 21:38:588593 return base::nullopt;
peconn257951522017-06-09 18:24:598594}
8595
billorr21c005d2016-11-17 03:57:048596int WebContentsImpl::GetCurrentlyPlayingVideoCount() {
8597 return currently_playing_video_count_;
dalecurtis88c240072015-12-09 02:11:188598}
8599
Raymond Toye413650c2018-08-31 00:12:478600void WebContentsImpl::AudioContextPlaybackStarted(RenderFrameHost* host,
8601 int context_id) {
Alexander Timin5fdeff22020-09-08 09:20:378602 OPTIONAL_TRACE_EVENT1(
8603 "content", "WebContentsImpl::AudioContextPlaybackStarted",
8604 "render_frame_host", base::trace_event::ToTracedValue(host));
Raymond Toye413650c2018-08-31 00:12:478605 WebContentsObserver::AudioContextId audio_context_id(host, context_id);
Alexander Timin90c20c32020-08-12 15:28:328606 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8607 observer->AudioContextPlaybackStarted(audio_context_id);
8608 });
Raymond Toye413650c2018-08-31 00:12:478609}
8610
8611void WebContentsImpl::AudioContextPlaybackStopped(RenderFrameHost* host,
8612 int context_id) {
Alexander Timin5fdeff22020-09-08 09:20:378613 OPTIONAL_TRACE_EVENT1(
8614 "content", "WebContentsImpl::AudioContextPlaybackStopped",
8615 "render_frame_host", base::trace_event::ToTracedValue(host));
Raymond Toye413650c2018-08-31 00:12:478616 WebContentsObserver::AudioContextId audio_context_id(host, context_id);
Alexander Timin90c20c32020-08-12 15:28:328617 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8618 observer->AudioContextPlaybackStopped(audio_context_id);
8619 });
Raymond Toye413650c2018-08-31 00:12:478620}
8621
Chris Hamilton16ca64a2020-05-14 23:13:178622void WebContentsImpl::OnFrameAudioStateChanged(RenderFrameHost* host,
8623 bool is_audible) {
Alexander Timin5fdeff22020-09-08 09:20:378624 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnFrameAudioStateChanged",
8625 "render_frame_host",
8626 base::trace_event::ToTracedValue(host), "is_audible",
8627 is_audible);
Alexander Timin90c20c32020-08-12 15:28:328628 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8629 observer->OnFrameAudioStateChanged(host, is_audible);
8630 });
Chris Hamilton16ca64a2020-05-14 23:13:178631}
8632
evliu7f736f02019-11-07 17:43:508633media::MediaMetricsProvider::RecordAggregateWatchTimeCallback
8634WebContentsImpl::GetRecordAggregateWatchTimeCallback() {
Alexander Timin5fdeff22020-09-08 09:20:378635 OPTIONAL_TRACE_EVENT0("content",
8636 "WebContentsImpl::RecordAggregateWatchTimeCallback");
Becca Hughes53652442020-03-17 15:35:428637 if (!delegate_ || !delegate_->GetDelegateWeakPtr())
8638 return base::DoNothing();
8639
evliu7f736f02019-11-07 17:43:508640 return base::BindRepeating(
Becca Hughes53652442020-03-17 15:35:428641 [](base::WeakPtr<WebContentsDelegate> delegate, GURL last_committed_url,
8642 base::TimeDelta total_watch_time, base::TimeDelta time_stamp,
8643 bool has_video, bool has_audio) {
evliua283c9e2019-11-08 22:57:228644 content::MediaPlayerWatchTime watch_time(
8645 last_committed_url, last_committed_url.GetOrigin(),
8646 total_watch_time, time_stamp, has_video, has_audio);
evliu7f736f02019-11-07 17:43:508647
8648 // Save the watch time if the delegate is still alive.
8649 if (delegate)
8650 delegate->MediaWatchTimeChanged(watch_time);
8651 },
Becca Hughes53652442020-03-17 15:35:428652 delegate_->GetDelegateWeakPtr(), GetMainFrameLastCommittedURL());
evliu7f736f02019-11-07 17:43:508653}
8654
Ehsan Karamad1c631762019-05-13 23:04:018655RenderFrameHostImpl* WebContentsImpl::GetMainFrameForInnerDelegate(
8656 FrameTreeNode* frame_tree_node) {
8657 if (auto* web_contents = node_.GetInnerWebContentsInFrame(frame_tree_node))
8658 return web_contents->GetMainFrame();
8659 return nullptr;
8660}
8661
John Budorickee1c9512019-10-17 15:32:198662bool WebContentsImpl::IsFrameLowPriority(
8663 const RenderFrameHost* render_frame_host) {
8664 if (!delegate_)
8665 return false;
8666 return delegate_->IsFrameLowPriority(this, render_frame_host);
8667}
8668
Roger Tawa03ffdbd2020-01-16 18:12:548669void WebContentsImpl::IsClipboardPasteAllowed(
8670 const GURL& url,
8671 const ui::ClipboardFormatType& data_type,
8672 const std::string& data,
8673 IsClipboardPasteAllowedCallback callback) {
Dominique Fauteux-Chapleau99244382020-07-08 20:37:008674 ++suppress_unresponsive_renderer_count_;
Roger Tawa03ffdbd2020-01-16 18:12:548675 GetContentClient()->browser()->IsClipboardPasteAllowed(
Dominique Fauteux-Chapleau99244382020-07-08 20:37:008676 this, url, data_type, data,
8677 base::BindOnce(&WebContentsImpl::IsClipboardPasteAllowedWrapperCallback,
8678 weak_factory_.GetWeakPtr(), std::move(callback)));
8679}
8680
8681void WebContentsImpl::IsClipboardPasteAllowedWrapperCallback(
8682 IsClipboardPasteAllowedCallback callback,
8683 ClipboardPasteAllowed allowed) {
8684 std::move(callback).Run(allowed);
8685 --suppress_unresponsive_renderer_count_;
Roger Tawa03ffdbd2020-01-16 18:12:548686}
8687
Lan Weif81c6e7c2020-02-12 16:46:098688bool WebContentsImpl::HasSeenRecentScreenOrientationChange() {
8689 static constexpr base::TimeDelta kMaxInterval =
8690 base::TimeDelta::FromSeconds(1);
8691 base::TimeDelta delta =
8692 ui::EventTimeForNow() - last_screen_orientation_change_time_;
Mike Wassermandb8f4f02020-10-06 01:18:378693 // Return whether a screen orientation change happened in the last 1 second.
Lan Weif81c6e7c2020-02-12 16:46:098694 return delta <= kMaxInterval;
8695}
8696
Mike Wassermandb8f4f02020-10-06 01:18:378697bool WebContentsImpl::IsTransientAllowFullscreenActive() const {
8698 return transient_allow_fullscreen_.IsActive();
8699}
8700
Lan Weif81c6e7c2020-02-12 16:46:098701void WebContentsImpl::DidChangeScreenOrientation() {
8702 last_screen_orientation_change_time_ = ui::EventTimeForNow();
8703}
8704
Miyoung Shin8f2e1832020-04-27 09:00:028705bool WebContentsImpl::ShowPopupMenu(
Miyoung Shin4d947d22020-04-24 04:48:338706 RenderFrameHostImpl* render_frame_host,
Miyoung Shin8f2e1832020-04-27 09:00:028707 mojo::PendingRemote<blink::mojom::PopupMenuClient>* popup_client,
Miyoung Shin4d947d22020-04-24 04:48:338708 const gfx::Rect& bounds,
8709 int32_t item_height,
8710 double font_size,
8711 int32_t selected_item,
8712 std::vector<blink::mojom::MenuItemPtr>* menu_items,
8713 bool right_aligned,
8714 bool allow_multiple_selection) {
Alexander Timin5fdeff22020-09-08 09:20:378715 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ShowPopupMenu",
8716 "render_frame_host",
8717 base::trace_event::ToTracedValue(render_frame_host));
Alexander Timin90c20c32020-08-12 15:28:328718 for (auto& observer : observers_.observer_list()) {
Miyoung Shin8f2e1832020-04-27 09:00:028719 if (observer.ShowPopupMenu(render_frame_host, popup_client, bounds,
8720 item_height, font_size, selected_item,
8721 menu_items, right_aligned,
8722 allow_multiple_selection)) {
Miyoung Shin4d947d22020-04-24 04:48:338723 return true;
8724 }
8725 }
8726 return false;
8727}
8728
Francois Doraye6161152018-03-27 22:05:378729void WebContentsImpl::UpdateWebContentsVisibility(Visibility visibility) {
Alexander Timin5fdeff22020-09-08 09:20:378730 OPTIONAL_TRACE_EVENT1("content",
8731 "WebContentsImpl::UpdateWebContentsVisibility",
8732 "visibility", visibility);
Francois Doray3f2afbd2018-04-06 19:18:188733 // Occlusion is disabled when |features::kWebContentsOcclusion| is disabled
8734 // (for power and speed impact assessment) or when
8735 // |switches::kDisableBackgroundingOccludedWindowsForTesting| is specified on
8736 // the command line (to avoid flakiness in browser tests).
8737 const bool occlusion_is_disabled =
8738 !base::FeatureList::IsEnabled(features::kWebContentsOcclusion) ||
Francois Doraye6161152018-03-27 22:05:378739 base::CommandLine::ForCurrentProcess()->HasSwitch(
8740 switches::kDisableBackgroundingOccludedWindowsForTesting);
8741 if (occlusion_is_disabled && visibility == Visibility::OCCLUDED)
8742 visibility = Visibility::VISIBLE;
8743
tapted65ff2ea72016-03-01 23:39:008744 if (!did_first_set_visible_) {
Francois Doraye6161152018-03-27 22:05:378745 if (visibility == Visibility::VISIBLE) {
8746 // A WebContents created with CreateParams::initially_hidden = false
8747 // starts with GetVisibility() == Visibility::VISIBLE even though it is
8748 // not really visible. Call WasShown() when it becomes visible for real as
8749 // the page load mechanism and some WebContentsObserver rely on that.
tapted65ff2ea72016-03-01 23:39:008750 WasShown();
Francois Dorayfe4a1772018-02-17 04:17:098751 did_first_set_visible_ = true;
tapted65ff2ea72016-03-01 23:39:008752 }
Francois Doraye6161152018-03-27 22:05:378753
8754 // Trust the initial visibility of the WebContents and do not switch it to
8755 // HIDDEN or OCCLUDED before it becomes VISIBLE for real. Doing so would
8756 // result in destroying resources that would immediately be recreated (e.g.
8757 // UpdateWebContents(HIDDEN) can be called when a WebContents is added to a
8758 // hidden window that is about to be shown).
8759
tapted65ff2ea72016-03-01 23:39:008760 return;
8761 }
Francois Doraye6161152018-03-27 22:05:378762
8763 if (visibility == visibility_)
tapted65ff2ea72016-03-01 23:39:008764 return;
8765
Collin Baker989e0882019-11-01 01:27:178766 UpdateVisibilityAndNotifyPageAndView(visibility);
tapted65ff2ea72016-03-01 23:39:008767}
8768
aelias5252baa2016-04-10 01:18:028769void WebContentsImpl::UpdateOverridingUserAgent() {
Alexander Timin5fdeff22020-09-08 09:20:378770 OPTIONAL_TRACE_EVENT0("content",
8771 "WebContentsImpl::UpdateOverridingUserAgent");
mlamouri5cd9ae82017-02-18 11:05:098772 NotifyPreferencesChanged();
aelias5252baa2016-04-10 01:18:028773}
8774
avid53461d2016-02-25 17:15:048775void WebContentsImpl::SetJavaScriptDialogManagerForTesting(
8776 JavaScriptDialogManager* dialog_manager) {
Alexander Timin5fdeff22020-09-08 09:20:378777 OPTIONAL_TRACE_EVENT0(
8778 "content", "WebContentsImpl::SetJavaScriptDialogManagerForTesting");
avid53461d2016-02-25 17:15:048779 dialog_manager_ = dialog_manager;
8780}
8781
Julie Jeongeun Kim7d0986172019-12-04 03:17:258782void WebContentsImpl::RemoveReceiverSet(const std::string& interface_name) {
Alexander Timin5fdeff22020-09-08 09:20:378783 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RemoveReceiverSet",
8784 "interface_name", interface_name);
Julie Jeongeun Kim7d0986172019-12-04 03:17:258785 auto it = receiver_sets_.find(interface_name);
8786 if (it != receiver_sets_.end())
8787 receiver_sets_.erase(it);
rockotf62002a2016-09-15 00:08:598788}
8789
nzolghadrd87a308d2016-12-07 15:45:568790bool WebContentsImpl::AddDomainInfoToRapporSample(rappor::Sample* sample) {
Alexander Timin5fdeff22020-09-08 09:20:378791 OPTIONAL_TRACE_EVENT0("content",
8792 "WebContentsImpl::AddDomainInfoToRapporSample");
nzolghadrbbffc6c2017-05-25 17:56:398793 // Here we associate this metric to the main frame URL regardless of what
8794 // caused it.
nzolghadrd87a308d2016-12-07 15:45:568795 sample->SetStringField("Domain", ::rappor::GetDomainAndRegistrySampleFromGURL(
8796 GetLastCommittedURL()));
nzolghadrd87a308d2016-12-07 15:45:568797 return true;
8798}
8799
falken52a56e32016-12-08 05:02:408800void WebContentsImpl::ShowInsecureLocalhostWarningIfNeeded() {
Alexander Timin5fdeff22020-09-08 09:20:378801 OPTIONAL_TRACE_EVENT0(
8802 "content", "WebContentsImpl::ShowInsecureLocalhostWarningIfNeeded");
falken52a56e32016-12-08 05:02:408803 bool allow_localhost = base::CommandLine::ForCurrentProcess()->HasSwitch(
8804 switches::kAllowInsecureLocalhost);
8805 if (!allow_localhost)
8806 return;
8807
8808 content::NavigationEntry* entry = GetController().GetLastCommittedEntry();
Rob Wuf79b3ba2018-01-14 01:54:318809 if (!entry || !net::IsLocalhost(entry->GetURL()))
falken52a56e32016-12-08 05:02:408810 return;
8811
8812 content::SSLStatus ssl_status = entry->GetSSL();
Matt Mueller936511442019-09-03 18:15:128813 if (!net::IsCertStatusError(ssl_status.cert_status))
falken52a56e32016-12-08 05:02:408814 return;
8815
8816 GetMainFrame()->AddMessageToConsole(
Abhijeet Kandalkara5928a0a2019-03-13 05:04:428817 blink::mojom::ConsoleMessageLevel::kWarning,
falken52a56e32016-12-08 05:02:408818 base::StringPrintf("This site does not have a valid SSL "
8819 "certificate! Without SSL, your site's and "
8820 "visitors' data is vulnerable to theft and "
8821 "tampering. Get a valid SSL certificate before"
8822 " releasing your website to the public."));
8823}
8824
ekaramadf6750aa2017-06-06 18:29:428825bool WebContentsImpl::IsShowingContextMenuOnPage() const {
8826 return showing_context_menu_;
8827}
8828
Min Qina904f3302018-02-13 23:33:348829download::DownloadUrlParameters::RequestHeadersType
8830WebContentsImpl::ParseDownloadHeaders(const std::string& headers) {
Alexander Timin5fdeff22020-09-08 09:20:378831 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ParseDownloadHeaders",
8832 "headers", headers);
Min Qina904f3302018-02-13 23:33:348833 download::DownloadUrlParameters::RequestHeadersType request_headers;
Megan Jablonski2f6a4c52017-07-10 23:01:258834 for (const base::StringPiece& key_value : base::SplitStringPiece(
8835 headers, "\r\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) {
8836 std::vector<std::string> pair = base::SplitString(
8837 key_value, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
8838 if (2ul == pair.size())
8839 request_headers.push_back(make_pair(pair[0], pair[1]));
8840 }
8841 return request_headers;
8842}
8843
lukasza6f8ac622017-06-06 03:10:208844void WebContentsImpl::SetOpenerForNewContents(FrameTreeNode* opener,
8845 bool opener_suppressed) {
Alexander Timin5fdeff22020-09-08 09:20:378846 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetOpenerForNewContents");
lukasza6f8ac622017-06-06 03:10:208847 if (opener) {
8848 FrameTreeNode* new_root = GetFrameTree()->root();
8849
8850 // For the "original opener", track the opener's main frame instead, because
8851 // if the opener is a subframe, the opener tracking could be easily bypassed
8852 // by spawning from a subframe and deleting the subframe.
8853 // https://crbug.com/705316
8854 new_root->SetOriginalOpener(opener->frame_tree()->root());
Wolfgang Beyerd8809db2020-09-30 15:29:398855 new_root->SetOpenerDevtoolsFrameToken(opener->devtools_frame_token());
lukasza6f8ac622017-06-06 03:10:208856
8857 if (!opener_suppressed) {
8858 new_root->SetOpener(opener);
8859 created_with_opener_ = true;
8860 }
8861 }
8862}
8863
Mounir Lamouri0f5bdf52019-04-04 16:32:358864void WebContentsImpl::MediaMutedStatusChanged(const MediaPlayerId& id,
8865 bool muted) {
Alexander Timin5fdeff22020-09-08 09:20:378866 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::MediaMutedStatusChanged",
8867 "muted", muted);
Alexander Timin90c20c32020-08-12 15:28:328868 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8869 observer->MediaMutedStatusChanged(id, muted);
8870 });
Becca Hughes9f6fd4b82017-06-15 10:01:408871}
8872
EhsanK2075c7e2017-08-21 02:42:398873void WebContentsImpl::SetVisibilityForChildViews(bool visible) {
Alexander Timin5fdeff22020-09-08 09:20:378874 OPTIONAL_TRACE_EVENT1("content",
8875 "WebContentsImpl::SetVisibilityForChildViews",
8876 "visible", visible);
EhsanK2075c7e2017-08-21 02:42:398877 GetMainFrame()->SetVisibilityForChildViews(visible);
8878}
8879
Alison Maher7f366dc62020-03-03 19:46:008880void WebContentsImpl::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) {
Alexander Timin5fdeff22020-09-08 09:20:378881 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnNativeThemeUpdated");
Alison Maher7f366dc62020-03-03 19:46:008882 DCHECK(native_theme_observer_.IsObserving(observed_theme));
8883
8884 bool using_dark_colors = observed_theme->ShouldUseDarkColors();
8885 ui::NativeTheme::PreferredColorScheme preferred_color_scheme =
8886 observed_theme->GetPreferredColorScheme();
8887 bool preferences_changed = false;
8888
8889 if (using_dark_colors_ != using_dark_colors) {
8890 using_dark_colors_ = using_dark_colors;
8891 preferences_changed = true;
8892 }
8893 if (preferred_color_scheme_ != preferred_color_scheme) {
8894 preferred_color_scheme_ = preferred_color_scheme;
8895 preferences_changed = true;
8896 }
8897
8898 if (preferences_changed)
8899 NotifyPreferencesChanged();
8900}
8901
Dave Tapuska58a099e2020-06-08 21:48:408902blink::mojom::FrameWidgetInputHandler*
8903WebContentsImpl::GetFocusedFrameWidgetInputHandler() {
8904 auto* focused_render_widget_host =
8905 GetFocusedRenderWidgetHost(GetMainFrame()->GetRenderWidgetHost());
8906 if (!focused_render_widget_host)
Dave Tapuskae782bea2019-07-09 16:21:518907 return nullptr;
Dave Tapuska58a099e2020-06-08 21:48:408908 return focused_render_widget_host->GetFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:518909}
8910
Alexander Timine3ec4192020-04-20 16:39:408911ukm::SourceId WebContentsImpl::GetCurrentPageUkmSourceId() {
8912 return GetMainFrame()->GetPageUkmSourceId();
8913}
8914
Yuzu Saijo232076f2020-05-29 07:14:028915std::set<RenderViewHostImpl*>
8916WebContentsImpl::GetRenderViewHostsIncludingBackForwardCached() {
8917 std::set<RenderViewHostImpl*> render_view_hosts;
8918
8919 // Add RenderViewHostImpls outside of BackForwardCache.
8920 for (auto& render_view_host : frame_tree_.render_view_hosts()) {
8921 render_view_hosts.insert(render_view_host.second);
8922 }
8923
8924 // Add RenderViewHostImpls in BackForwardCache.
8925 const auto& entries = GetController().GetBackForwardCache().GetEntries();
8926 for (const auto& entry : entries) {
8927 std::set<RenderViewHostImpl*> bfcached_hosts = entry->render_view_hosts;
8928 render_view_hosts.insert(bfcached_hosts.begin(), bfcached_hosts.end());
8929 }
8930
8931 return render_view_hosts;
8932}
8933
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:508934void WebContentsImpl::RenderFrameHostStateChanged(
8935 RenderFrameHost* render_frame_host,
8936 LifecycleState old_state,
8937 LifecycleState new_state) {
Alexander Timin5fdeff22020-09-08 09:20:378938 OPTIONAL_TRACE_EVENT2(
8939 "content", "WebContentsImpl::RenderFrameHostStateChanged",
8940 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host),
8941 "states",
8942 base::trace_event::TracedValue::Build(
8943 {{"old", base::trace_event::ValueToString(old_state)},
8944 {"new", base::trace_event::ValueToString(new_state)}}));
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:508945 if (render_frame_host->GetParent())
8946 return;
8947
8948 if (old_state == LifecycleState::kActive &&
8949 new_state != LifecycleState::kActive) {
8950 // TODO(sreejakshetty): Remove this reset when ColorChooser becomes
8951 // per-frame.
8952 // Close the color chooser popup when RenderFrameHost changes state from
8953 // kActive.
8954 color_chooser_.reset();
8955 }
8956}
8957
danakjc5ce67602020-09-23 20:06:578958void WebContentsImpl::GetFrameSequenceNumbersForDebugging(
8959 RenderFrameHostImpl* render_frame_host,
8960 int64_t& item_sequence_number,
8961 int64_t& document_sequence_number) {
8962 NavigationEntryImpl* entry =
8963 controller_.GetEntryWithUniqueID(render_frame_host->nav_entry_id());
8964 if (!entry)
8965 return;
8966
8967 FrameNavigationEntry* frame_entry =
8968 entry->GetFrameEntry(render_frame_host->frame_tree_node());
8969 if (frame_entry) {
8970 item_sequence_number = frame_entry->item_sequence_number();
8971 document_sequence_number = frame_entry->document_sequence_number();
8972 }
8973}
8974
[email protected]8ff00d72012-10-23 19:12:218975} // namespace content