blob: 478fee6e6d9b0b5d8c6fc9b65bba849d2b053b9a [file] [log] [blame]
[email protected]91854cd2012-01-10 19:43:571// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
[email protected]93ddb3c2012-04-11 21:44:295#include "content/browser/web_contents/web_contents_impl.h"
[email protected]39526562011-02-05 03:41:516
avib7348942015-12-25 20:57:107#include <stddef.h>
8
Avi Drissman33972942020-06-19 14:16:019#include <algorithm>
w.shackleton49bcd392016-01-06 17:38:2210#include <cmath>
[email protected]2bb171882012-03-07 02:09:4611#include <utility>
rkaplowe56a52032017-02-07 00:14:5412#include <vector>
[email protected]b75b8292010-10-01 07:28:2513
Sebastien Marchandf8cbfab2019-01-25 16:02:3014#include "base/bind.h"
[email protected]36fb2c7c2011-04-04 15:49:0815#include "base/command_line.h"
Avi Drissman33972942020-06-19 14:16:0116#include "base/containers/flat_set.h"
creisfafed882016-07-29 00:03:0917#include "base/debug/dump_without_crashing.h"
zqzhang181047e62016-07-01 13:37:1718#include "base/feature_list.h"
Marijn Kruisselbrink46fa4bd2019-07-11 18:15:4719#include "base/files/file_path.h"
[email protected]cbb1ef592013-06-05 19:49:4620#include "base/lazy_instance.h"
skyostil95082a62015-06-05 19:53:0721#include "base/location.h"
[email protected]6d636e62013-07-31 03:15:5622#include "base/logging.h"
avib7348942015-12-25 20:57:1023#include "base/macros.h"
fdorayba121422016-12-23 19:51:4824#include "base/memory/ptr_util.h"
dmazzonid95ae842016-04-12 21:17:3925#include "base/memory/ref_counted.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:2026#include "base/metrics/field_trial.h"
asvitkine8d51e9d2016-09-02 23:55:4327#include "base/metrics/histogram_macros.h"
bratell0a7406f2017-03-28 07:46:3728#include "base/metrics/user_metrics.h"
Avi Drissman4891b852018-09-25 18:12:5829#include "base/no_destructor.h"
Carlos Caballero1215f882019-10-29 15:58:4330#include "base/optional.h"
[email protected]04cbd3d2013-12-04 04:58:2031#include "base/process/process.h"
skyostil95082a62015-06-05 19:53:0732#include "base/single_thread_task_runner.h"
Arthur Sonzogni929d29f2018-09-17 14:19:4433#include "base/stl_util.h"
[email protected]348fbaac2013-06-11 06:31:5134#include "base/strings/string16.h"
35#include "base/strings/string_number_conversions.h"
Avi Drissman4891b852018-09-25 18:12:5836#include "base/strings/string_split.h"
[email protected]348fbaac2013-06-11 06:31:5137#include "base/strings/string_util.h"
[email protected]74ebfb12013-06-07 20:48:0038#include "base/strings/utf_string_conversions.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:2039#include "base/system/sys_info.h"
gab30f26df2016-05-11 19:37:5540#include "base/threading/thread_task_runner_handle.h"
[email protected]a43858f2013-06-28 15:18:3741#include "base/time/time.h"
ssid3e765612015-01-28 04:03:4242#include "base/trace_event/trace_event.h"
avib7348942015-12-25 20:57:1043#include "build/build_config.h"
Darin Fisher6cf20e782020-08-07 22:25:3644#include "build/lacros_buildflags.h"
Min Qinda0ed2062018-02-23 22:00:5345#include "components/download/public/common/download_stats.h"
nzolghadrd87a308d2016-12-07 15:45:5646#include "components/rappor/public/rappor_utils.h"
rsleevi24f64dc22015-08-07 21:39:2147#include "components/url_formatter/url_formatter.h"
Abigail Kleinaa898742019-11-01 02:31:2548#include "content/browser/accessibility/accessibility_event_recorder.h"
James Wallace-Leeeafc94cb92018-07-23 21:35:0949#include "content/browser/accessibility/accessibility_tree_formatter_blink.h"
jamescookda2505812015-03-20 18:01:1850#include "content/browser/bad_message.h"
Max Morinddebb972018-09-20 10:04:1451#include "content/browser/browser_main_loop.h"
[email protected]7a846df2012-09-20 19:17:3952#include "content/browser/browser_plugin/browser_plugin_embedder.h"
53#include "content/browser/browser_plugin/browser_plugin_guest.h"
[email protected]b9535422012-02-09 01:47:5954#include "content/browser/child_process_security_policy_impl.h"
John Delaney732721e92020-02-07 23:11:2755#include "content/browser/conversions/conversion_host.h"
Pavel Feldman3c1842b2017-08-02 05:00:1656#include "content/browser/devtools/protocol/page_handler.h"
dgozmanf00c4f72016-10-19 17:45:1557#include "content/browser/devtools/render_frame_devtools_agent_host.h"
Becca Hughes3b5a43482018-07-17 22:31:5558#include "content/browser/display_cutout/display_cutout_host_impl.h"
[email protected]5f2aa722013-08-07 16:59:4159#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
[email protected]1ea3c792012-04-17 01:25:0460#include "content/browser/dom_storage/session_storage_namespace_impl.h"
[email protected]aa4f3972012-03-01 18:12:1261#include "content/browser/download/mhtml_generation_manager.h"
[email protected]a53209b2012-01-20 16:48:1662#include "content/browser/download/save_package.h"
paulmeyerc0b762b2016-04-13 11:55:1763#include "content/browser/find_request_manager.h"
[email protected]bffc8302014-01-23 20:52:1664#include "content/browser/frame_host/cross_process_frame_connector.h"
ananta4b7467a52016-09-23 01:42:3865#include "content/browser/frame_host/frame_tree_node.h"
[email protected]d4a8ca482013-10-30 21:06:4066#include "content/browser/frame_host/navigation_entry_impl.h"
Arthur Hemeryc3380172018-01-22 14:00:1767#include "content/browser/frame_host/navigation_request.h"
Hiroki Nakagawa080f86c2020-05-13 10:56:4268#include "content/browser/frame_host/navigator.h"
[email protected]52913802013-12-10 05:52:1869#include "content/browser/frame_host/render_frame_host_impl.h"
lfgdb5c4ed2016-03-04 23:09:0770#include "content/browser/frame_host/render_frame_proxy_host.h"
Kenneth Russell954ed9ce2018-04-12 23:07:0171#include "content/browser/gpu/gpu_data_manager_impl.h"
mlamouriefdca9d2014-09-16 16:55:4072#include "content/browser/manifest/manifest_manager_host.h"
Max Morin5bc74f52018-05-09 07:00:2173#include "content/browser/media/audio_stream_broker.h"
dalecurtisbc6572e12014-09-12 19:22:3074#include "content/browser/media/audio_stream_monitor.h"
miu50f97892014-09-22 22:49:5275#include "content/browser/media/capture/web_contents_audio_muter.h"
dalecurtis88c240072015-12-09 02:11:1876#include "content/browser/media/media_web_contents_observer.h"
zqzhang1adf3cb2016-11-01 11:26:4577#include "content/browser/media/session/media_session_impl.h"
Mike Wassermandabad612020-08-13 04:26:2778#include "content/browser/permissions/permission_controller_impl.h"
Yuzu Saijoa11069a2020-04-22 10:56:5579#include "content/browser/plugin_content_origin_allowlist.h"
Kevin McNee94ea52f52020-06-23 17:42:0680#include "content/browser/portal/portal.h"
David Black9cca3592019-11-06 23:02:2281#include "content/browser/renderer_host/frame_token_message_queue.h"
[email protected]f3b1a082011-11-18 00:34:3082#include "content/browser/renderer_host/render_process_host_impl.h"
[email protected]21161032014-05-05 16:56:5083#include "content/browser/renderer_host/render_view_host_delegate_view.h"
[email protected]b3c41c0b2012-03-06 15:48:3284#include "content/browser/renderer_host/render_view_host_impl.h"
[email protected]bafe6cd2012-05-23 23:09:5085#include "content/browser/renderer_host/render_widget_host_impl.h"
kenrb2a565f82015-09-02 20:24:5986#include "content/browser/renderer_host/render_widget_host_input_event_router.h"
[email protected]cfd80b02014-05-01 17:46:4887#include "content/browser/renderer_host/render_widget_host_view_base.h"
Ken Buchanandaef006b2017-08-17 18:32:1588#include "content/browser/renderer_host/render_widget_host_view_child_frame.h"
ekaramadadd882292016-06-08 15:22:5689#include "content/browser/renderer_host/text_input_manager.h"
Mike Wassermanb213b9352020-04-16 00:32:3490#include "content/browser/screen_enumeration/screen_change_monitor.h"
leon.han552e9de2017-02-09 14:37:3091#include "content/browser/screen_orientation/screen_orientation_provider.h"
[email protected]b6583592012-01-25 19:52:3392#include "content/browser/site_instance_impl.h"
Charlie Reis96077362019-07-04 00:34:0493#include "content/browser/web_contents/javascript_dialog_navigation_deferrer.h"
lfgc740d4b22016-04-15 16:45:3394#include "content/browser/web_contents/web_contents_view_child_frame.h"
Tsuyoshi Horob0d8d902020-03-12 00:09:3995#include "content/browser/web_package/save_as_web_bundle_job.h"
[email protected]86a0a6e2013-01-28 06:33:0396#include "content/browser/webui/web_ui_controller_factory_registry.h"
[email protected]d2353452012-01-19 19:53:5697#include "content/browser/webui/web_ui_impl.h"
[email protected]8eb04562013-03-06 03:41:1498#include "content/common/browser_plugin/browser_plugin_constants.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:2099#include "content/common/content_switches_internal.h"
Paul Meyer0c58c3712016-11-17 22:59:51100#include "content/common/drag_messages.h"
[email protected]f114fa42013-12-06 17:06:44101#include "content/common/frame_messages.h"
[email protected]1f3fc1d2014-04-03 14:50:17102#include "content/common/input_messages.h"
lfgdb5c4ed2016-03-04 23:09:07103#include "content/common/page_messages.h"
nasko34634672016-07-29 18:46:06104#include "content/common/page_state_serialization.h"
rockot5c478a72016-09-28 23:14:18105#include "content/common/render_message_filter.mojom.h"
[email protected]2c5569662011-03-22 20:45:02106#include "content/common/view_messages.h"
Albert J. Wong3c93c182018-09-27 17:29:43107#include "content/common/widget_messages.h"
Abigail Kleinabb428332019-09-13 18:26:21108#include "content/public/browser/accessibility_tree_formatter.h"
[email protected]31a71eaf2014-03-13 01:47:36109#include "content/public/browser/ax_event_notification_details.h"
[email protected]ccb797302011-12-15 16:55:11110#include "content/public/browser/browser_context.h"
[email protected]139355f2014-05-11 14:21:28111#include "content/public/browser/browser_plugin_guest_manager.h"
Eric Seckler8652dcd52018-09-20 10:42:28112#include "content/public/browser/browser_task_traits.h"
Gabriel Charette790754c2018-03-16 21:32:59113#include "content/public/browser/browser_thread.h"
[email protected]87f3c082011-10-19 18:07:44114#include "content/public/browser/content_browser_client.h"
Lukasz Anforowicz8c4446dc2020-03-11 22:16:42115#include "content/public/browser/context_menu_params.h"
Ken Rockotce010f02019-12-12 23:32:32116#include "content/public/browser/device_service.h"
[email protected]e582fdd2011-12-20 16:48:17117#include "content/public/browser/download_manager.h"
Kent Tamura512a27e2018-10-04 00:49:32118#include "content/public/browser/file_select_listener.h"
ekaramada110f642016-12-21 19:47:28119#include "content/public/browser/focused_node_details.h"
Danyao Wanga78f3dd22020-03-05 05:31:27120#include "content/public/browser/global_routing_id.h"
[email protected]d9083482012-01-06 00:38:46121#include "content/public/browser/invalidate_type.h"
[email protected]71a88bb2013-02-01 22:05:15122#include "content/public/browser/javascript_dialog_manager.h"
skyf65d9bb2017-03-24 02:26:39123#include "content/public/browser/keyboard_event_processing_result.h"
[email protected]09d31d52012-03-11 22:30:27124#include "content/public/browser/load_notification_details.h"
[email protected]5b96836f2011-12-22 07:39:00125#include "content/public/browser/navigation_details.h"
[email protected]375fa1b2012-05-22 22:05:37126#include "content/public/browser/notification_details.h"
[email protected]be2510c02012-05-28 14:52:14127#include "content/public/browser/notification_service.h"
scottmg011d96e32016-06-29 19:15:08128#include "content/public/browser/notification_types.h"
[email protected]95640212014-07-26 18:14:30129#include "content/public/browser/render_widget_host_iterator.h"
Lukasz Anforowicze1b954d92017-10-30 21:28:06130#include "content/public/browser/restore_type.h"
estark5ea80e52015-06-19 18:43:12131#include "content/public/browser/security_style_explanations.h"
falken52a56e32016-12-08 05:02:40132#include "content/public/browser/ssl_status.h"
[email protected]4c3a23582012-08-18 08:54:34133#include "content/public/browser/storage_partition.h"
[email protected]674bc592011-12-20 23:00:42134#include "content/public/browser/web_contents_delegate.h"
Julie Jeongeun Kim7d0986172019-12-04 03:17:25135#include "content/public/browser/web_contents_receiver_set.h"
Lei Zhangee3b63ad2018-06-06 23:25:31136#include "content/public/browser/web_ui_controller.h"
[email protected]e091df82011-10-11 18:13:21137#include "content/public/common/bindings_policy.h"
alexmosc9e76ec2016-05-16 22:59:37138#include "content/public/common/child_process_host.h"
Hans Wennborg5ffd1392019-10-16 11:00:02139#include "content/public/common/content_client.h"
[email protected]54087fe2011-10-28 22:02:48140#include "content/public/common/content_constants.h"
Francois Doray3f2afbd2018-04-06 19:18:18141#include "content/public/common/content_features.h"
[email protected]64d69de42012-02-06 00:19:54142#include "content/public/common/content_switches.h"
Lukasz Anforowicze1b954d92017-10-30 21:28:06143#include "content/public/common/page_state.h"
Leon Han963dc182018-11-06 05:41:48144#include "content/public/common/referrer_type_converters.h"
[email protected]04cbd3d2013-12-04 04:58:20145#include "content/public/common/result_codes.h"
[email protected]f16cc6782013-12-16 23:42:57146#include "content/public/common/url_utils.h"
danakjffc8baf2019-10-10 23:49:42147#include "content/public/common/use_zoom_for_dsf_policy.h"
[email protected]b3a97b52014-07-09 06:25:05148#include "content/public/common/web_preferences.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"
Sergio Villar Senin9d9d4f52019-10-15 10:57:57165#include "third_party/blink/public/common/security/security_style.h"
Abhijeet Kandalkarde7348e2020-01-13 06:06:54166#include "third_party/blink/public/mojom/frame/frame.mojom.h"
Dave Tapuskaa4189512019-10-15 20:27:34167#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
Takuto Ikutaaa3b796c2019-02-06 02:54:56168#include "third_party/blink/public/mojom/loader/pause_subresource_loading_handle.mojom.h"
Antonio Gomes0d42960a2019-06-05 12:35:51169#include "third_party/blink/public/mojom/mediastream/media_stream.mojom-shared.h"
halton.huoca2eabd2015-07-06 08:17:40170#include "third_party/skia/include/core/SkBitmap.h"
dmazzonid95ae842016-04-12 21:17:39171#include "ui/accessibility/ax_tree_combiner.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20172#include "ui/base/device_form_factor.h"
Mugdha Lakhani0a0d7862020-07-29 09:58:45173#if defined(USE_AURA)
174#include "ui/aura/window.h"
175#endif
[email protected]a08412b62012-05-29 21:28:56176#include "ui/base/layout.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20177#include "ui/base/ui_base_features.h"
178#include "ui/base/ui_base_switches.h"
179#include "ui/display/screen.h"
Daniel Cheng90196c82018-04-25 21:49:14180#include "ui/events/base_event_utils.h"
chongz4a9751942016-08-17 17:49:39181#include "ui/events/blink/web_input_event_traits.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20182#include "ui/gfx/animation/animation.h"
[email protected]66bd5512012-08-01 02:02:52183#include "ui/gl/gl_switches.h"
[email protected]3c733bde2010-12-21 19:56:31184
ekaramada110f642016-12-21 19:47:28185#if defined(OS_WIN)
186#include "content/browser/renderer_host/dip_util.h"
187#include "ui/gfx/geometry/dip_util.h"
188#endif
189
[email protected]583418cc2013-01-17 14:01:10190#if defined(OS_ANDROID)
mfomitchev2b8b066a2016-01-28 19:23:15191#include "content/browser/android/date_time_chooser_android.h"
sammcf5f1b0f2016-09-20 23:05:11192#include "content/browser/android/java_interfaces_impl.h"
Leon Hanccb985f2019-08-26 02:43:24193#include "content/browser/android/nfc_host.h"
[email protected]155c7f22013-12-09 17:07:18194#include "content/browser/web_contents/web_contents_android.h"
Ke He31d0bb02018-02-24 07:16:24195#include "services/device/public/mojom/nfc.mojom.h"
Mugdha Lakhani0a0d7862020-07-29 09:58:45196#include "ui/android/view_android.h"
mcnee336ea2c2017-05-23 22:50:59197#else // !OS_ANDROID
198#include "content/browser/host_zoom_map_impl.h"
mfomitchev2b8b066a2016-01-28 19:23:15199#endif // OS_ANDROID
[email protected]583418cc2013-01-17 14:01:10200
brettw4b461082016-11-19 18:55:16201#if BUILDFLAG(ENABLE_PLUGINS)
zqzhang181047e62016-07-01 13:37:17202#include "content/browser/media/session/pepper_playback_observer.h"
Lei Zhangebcc6302018-01-12 19:46:45203#endif
zqzhang181047e62016-07-01 13:37:17204
[email protected]8ff00d72012-10-23 19:12:21205namespace content {
Abigail Kleinaa898742019-11-01 02:31:25206
207using AccessibilityEventCallback =
208 base::RepeatingCallback<void(const std::string&)>;
209
[email protected]420ae012009-04-24 05:16:32210namespace {
211
[email protected]960b0372014-05-19 18:01:00212const int kMinimumDelayBetweenLoadingUpdatesMS = 100;
[email protected]82114f52012-03-20 22:53:41213const char kDotGoogleDotCom[] = ".google.com";
[email protected]ca406032011-07-19 21:53:05214
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:50215using LifecycleState = RenderFrameHostImpl::LifecycleState;
216
Alexander Timin33bd754c02020-03-10 22:50:18217// TODO(crbug.com/1059903): Clean up after the initial investigation.
218constexpr base::Feature kCheckWebContentsAccessFromNonCurrentFrame{
219 "CheckWebContentsAccessFromNonCurrentFrame",
220 base::FEATURE_DISABLED_BY_DEFAULT};
221
Avi Drissmana9114822018-03-23 18:25:55222base::LazyInstance<std::vector<
223 WebContentsImpl::FriendWrapper::CreatedCallback>>::DestructorAtExit
224 g_created_callbacks = LAZY_INSTANCE_INITIALIZER;
[email protected]cbb1ef592013-06-05 19:49:46225
dcheng57e39e22016-01-21 00:25:38226bool HasMatchingProcess(FrameTree* tree, int render_process_id) {
227 for (FrameTreeNode* node : tree->Nodes()) {
228 if (node->current_frame_host()->GetProcess()->GetID() == render_process_id)
229 return true;
alexmos4cf2aa32015-07-15 23:40:43230 }
dcheng57e39e22016-01-21 00:25:38231 return false;
[email protected]95640212014-07-26 18:14:30232}
233
kenrb19221852016-04-29 17:21:40234bool HasMatchingWidgetHost(FrameTree* tree, RenderWidgetHost* host) {
235 // This method scans the frame tree rather than checking whether
236 // host->delegate() == this, which allows it to return false when the host
237 // for a frame that is pending or pending deletion.
238 if (!host)
239 return false;
240
241 for (FrameTreeNode* node : tree->Nodes()) {
242 if (node->current_frame_host()->GetRenderWidgetHost() == host)
243 return true;
244 }
245 return false;
246}
247
dmazzonif8a31042016-12-03 00:52:13248void UpdateAccessibilityModeOnFrame(RenderFrameHost* frame_host) {
249 static_cast<RenderFrameHostImpl*>(frame_host)->UpdateAccessibilityMode();
[email protected]95640212014-07-26 18:14:30250}
251
dtseng0dd3fa12015-07-22 19:00:52252void ResetAccessibility(RenderFrameHost* rfh) {
253 static_cast<RenderFrameHostImpl*>(rfh)->AccessibilityReset();
254}
255
Ian Clelland5cbaaf82017-11-27 22:00:03256RenderFrameHostImpl* FindOpenerRFH(const WebContents::CreateParams& params) {
257 RenderFrameHostImpl* opener_rfh = nullptr;
alexmose201c7cd2015-06-10 17:14:21258 if (params.opener_render_frame_id != MSG_ROUTING_NONE) {
Ian Clelland5cbaaf82017-11-27 22:00:03259 opener_rfh = RenderFrameHostImpl::FromID(params.opener_render_process_id,
260 params.opener_render_frame_id);
alexmose201c7cd2015-06-10 17:14:21261 }
Ian Clelland5cbaaf82017-11-27 22:00:03262 return opener_rfh;
lukasza6f8ac622017-06-06 03:10:20263}
264
Dominick Ng37a15052018-07-17 23:56:35265// Returns |true| if |type| is the kind of user input that should trigger the
266// user interaction observers.
267bool IsUserInteractionInputType(blink::WebInputEvent::Type type) {
268 // Ideally, this list would be based more off of
269 // https://whatwg.org/C/interaction.html#triggered-by-user-activation.
Dave Tapuska347d60a2020-04-21 23:55:47270 return type == blink::WebInputEvent::Type::kMouseDown ||
271 type == blink::WebInputEvent::Type::kGestureScrollBegin ||
272 type == blink::WebInputEvent::Type::kTouchStart ||
273 type == blink::WebInputEvent::Type::kRawKeyDown;
Dominick Ng37a15052018-07-17 23:56:35274}
275
Pavel Feldman3c1842b2017-08-02 05:00:16276// Ensures that OnDialogClosed is only called once.
277class CloseDialogCallbackWrapper
278 : public base::RefCountedThreadSafe<CloseDialogCallbackWrapper> {
279 public:
Avi Drissmane04d3992017-10-05 15:11:36280 using CloseCallback =
281 base::OnceCallback<void(bool, bool, const base::string16&)>;
282
283 explicit CloseDialogCallbackWrapper(CloseCallback callback)
284 : callback_(std::move(callback)) {}
Pavel Feldman3c1842b2017-08-02 05:00:16285
286 void Run(bool dialog_was_suppressed,
287 bool success,
288 const base::string16& user_input) {
Avi Drissmane04d3992017-10-05 15:11:36289 if (callback_.is_null())
Pavel Feldman3c1842b2017-08-02 05:00:16290 return;
Avi Drissmane04d3992017-10-05 15:11:36291 std::move(callback_).Run(dialog_was_suppressed, success, user_input);
Pavel Feldman3c1842b2017-08-02 05:00:16292 }
293
294 private:
295 friend class base::RefCountedThreadSafe<CloseDialogCallbackWrapper>;
296 ~CloseDialogCallbackWrapper() {}
Avi Drissmane04d3992017-10-05 15:11:36297
298 CloseCallback callback_;
Pavel Feldman3c1842b2017-08-02 05:00:16299};
300
Arthur Sonzogni929d29f2018-09-17 14:19:44301bool FrameCompareDepth(RenderFrameHostImpl* a, RenderFrameHostImpl* b) {
302 return a->frame_tree_node()->depth() < b->frame_tree_node()->depth();
303}
304
Raymes Khoury58373df2019-08-06 06:29:20305bool AreValidRegisterProtocolHandlerArguments(const std::string& protocol,
306 const GURL& url,
307 const url::Origin& origin) {
308 ChildProcessSecurityPolicyImpl* policy =
309 ChildProcessSecurityPolicyImpl::GetInstance();
310 if (policy->IsPseudoScheme(protocol))
311 return false;
312
313 url::Origin url_origin = url::Origin::Create(url);
314 if (url_origin.opaque())
315 return false;
316
317 if (!url_origin.IsSameOriginWith(origin))
318 return false;
319
320 return true;
321}
322
yilkal796e89e2019-10-02 23:58:28323void RecordMaxFrameCountUMA(size_t max_frame_count) {
324 UMA_HISTOGRAM_COUNTS_10000("Navigation.MainFrame.MaxFrameCount",
325 max_frame_count);
326}
327
Jeremy Roman03ce13ce2020-05-29 22:16:57328// Returns whether the condition provided applies to any inner contents.
329// This check is not recursive (however, the predicate provided may itself
330// recurse each contents' own inner contents).
331//
332// For example, if this is used to aggregate state from inner contents to outer
333// contents, then that propagation will gather transitive descendants without
334// need for this helper to do so. In fact, in such cases recursing on inner
335// contents here would make that operation quadratic rather than linear.
336template <typename Functor>
337bool AnyInnerWebContents(WebContents* web_contents, const Functor& f) {
338 const auto& inner_contents = web_contents->GetInnerWebContents();
339 return std::any_of(inner_contents.begin(), inner_contents.end(), f);
340}
341
Xuehui Xieb2300ae42020-06-09 20:25:05342std::vector<RenderFrameHost*> GetAllFramesImpl(FrameTree& frame_tree,
343 bool include_pending) {
344 std::vector<RenderFrameHost*> frame_hosts;
345 for (FrameTreeNode* node : frame_tree.Nodes()) {
346 frame_hosts.push_back(node->current_frame_host());
347 if (include_pending) {
348 RenderFrameHostImpl* pending_frame_host =
349 node->render_manager()->speculative_frame_host();
350 if (pending_frame_host)
351 frame_hosts.push_back(pending_frame_host);
352 }
353 }
354 return frame_hosts;
355}
356
357int SendToAllFramesImpl(FrameTree& frame_tree,
358 bool include_pending,
359 IPC::Message* message) {
360 int number_of_messages = 0;
361 std::vector<RenderFrameHost*> frame_hosts =
362 GetAllFramesImpl(frame_tree, include_pending);
363 for (RenderFrameHost* rfh : frame_hosts) {
364 if (!rfh->IsRenderFrameLive())
365 continue;
366
367 ++number_of_messages;
368 IPC::Message* message_copy = new IPC::Message(*message);
369 message_copy->set_routing_id(rfh->GetRoutingID());
370 rfh->Send(message_copy);
371 }
372 delete message;
373 return number_of_messages;
374}
375
Avi Drissman33972942020-06-19 14:16:01376// Returns the set of all WebContentses that are reachable from |web_contents|
377// by applying some combination of WebContents::GetOriginalOpener() and
378// WebContents::GetOuterWebContents(). The |web_contents| parameter will be
379// included in the returned set.
380base::flat_set<WebContentsImpl*> GetAllOpeningWebContents(
381 WebContentsImpl* web_contents) {
382 base::flat_set<WebContentsImpl*> result;
383 base::flat_set<WebContentsImpl*> current;
384
385 current.insert(web_contents);
386
387 while (!current.empty()) {
388 WebContentsImpl* current_contents = *current.begin();
389 current.erase(current.begin());
390 auto insert_result = result.insert(current_contents);
391
392 if (insert_result.second) {
393 RenderFrameHostImpl* opener_rfh = current_contents->GetOriginalOpener();
394 if (opener_rfh) {
395 current.insert(static_cast<WebContentsImpl*>(
396 WebContents::FromRenderFrameHost(opener_rfh)));
397 }
398
399 WebContentsImpl* outer_contents = current_contents->GetOuterWebContents();
400 if (outer_contents)
401 current.insert(outer_contents);
402 }
403 }
404
405 return result;
406}
407
Rakina Zata Amni4029b6d2020-07-28 02:36:20408#if defined(OS_ANDROID)
409float GetDeviceScaleAdjustment(int min_width) {
410 static const float kMinFSM = 1.05f;
411 static const int kWidthForMinFSM = 320;
412 static const float kMaxFSM = 1.3f;
413 static const int kWidthForMaxFSM = 800;
414
415 if (min_width <= kWidthForMinFSM)
416 return kMinFSM;
417 if (min_width >= kWidthForMaxFSM)
418 return kMaxFSM;
419
420 // The font scale multiplier varies linearly between kMinFSM and kMaxFSM.
421 float ratio = static_cast<float>(min_width - kWidthForMinFSM) /
422 (kWidthForMaxFSM - kWidthForMinFSM);
423 return ratio * (kMaxFSM - kMinFSM) + kMinFSM;
424}
425#endif
426
Avi Drissman33972942020-06-19 14:16:01427// Used to attach the "set of fullscreen contents" to a browser context. Storing
428// sets of WebContents on their browser context is done for two reasons. One,
429// related WebContentses must necessarily share a browser context, so this saves
430// lookup time by restricting to one specific browser context. Two, separating
431// by browser context is preemptive paranoia about keeping things separate.
432class FullscreenContentsHolder : public base::SupportsUserData::Data {
433 public:
434 FullscreenContentsHolder() = default;
435 ~FullscreenContentsHolder() override = default;
436
437 FullscreenContentsHolder(const FullscreenContentsHolder&) = delete;
438 FullscreenContentsHolder& operator=(const FullscreenContentsHolder&) = delete;
439
440 base::flat_set<WebContentsImpl*>* set() { return &set_; }
441
442 private:
443 base::flat_set<WebContentsImpl*> set_;
444};
445
446const char kFullscreenContentsSet[] = "fullscreen-contents";
447
448base::flat_set<WebContentsImpl*>* FullscreenContentsSet(
449 BrowserContext* browser_context) {
450 auto* set_holder = static_cast<FullscreenContentsHolder*>(
451 browser_context->GetUserData(kFullscreenContentsSet));
452 if (!set_holder) {
453 auto new_holder = std::make_unique<FullscreenContentsHolder>();
454 set_holder = new_holder.get();
455 browser_context->SetUserData(kFullscreenContentsSet, std::move(new_holder));
456 }
457
458 return set_holder->set();
459}
460
Mike Wassermandabad612020-08-13 04:26:27461// Adjust the requested |bounds| for opening or placing a window. The bounds
462// may not extend outside a single screen's work area, and the |host| requires
463// permission to specify bounds on a screen other than its current screen.
464// TODO(crbug.com/897300): These adjustments are inaccurate for window.open(),
465// which specifies the inner content size, and for window.moveTo, resizeTo, etc.
466// calls on newly created windows, which may pass empty sizes or positions to
467// indicate uninitialized placement information in the renderer. Constraints
468// enforced later should resolve most inaccuracies, but this early enforcement
469// is needed to ensure bounds indicate the appropriate display.
470gfx::Rect AdjustRequestedWindowBounds(gfx::Rect bounds, RenderFrameHost* host) {
471 auto* screen = display::Screen::GetScreen();
472 auto display = screen->GetDisplayMatching(bounds);
473
474 // Check, but do not prompt, for permission to place windows on other screens.
475 // Sites generally need permission to get such bounds in the first place.
476 // Also clamp offscreen bounds to the window's current screen.
477 auto* controller =
478 PermissionControllerImpl::FromBrowserContext(host->GetBrowserContext());
479 if (!bounds.Intersects(display.bounds()) || !controller ||
480 controller->GetPermissionStatusForFrame(PermissionType::WINDOW_PLACEMENT,
481 host,
482 host->GetLastCommittedURL()) !=
483 blink::mojom::PermissionStatus::GRANTED) {
484 display = screen->GetDisplayNearestView(host->GetNativeView());
485 }
486
487 bounds.AdjustToFit(display.work_area());
488 return bounds;
489}
490
lukasza6f8ac622017-06-06 03:10:20491} // namespace
492
Joel Hockey8c2011b22020-04-30 05:07:19493CreatedWindow::CreatedWindow() = default;
494CreatedWindow::CreatedWindow(std::unique_ptr<WebContentsImpl> contents,
495 GURL target_url)
496 : contents(std::move(contents)), target_url(std::move(target_url)) {}
497CreatedWindow::~CreatedWindow() = default;
498CreatedWindow::CreatedWindow(CreatedWindow&&) = default;
499CreatedWindow& CreatedWindow::operator=(CreatedWindow&&) = default;
500
Erik Chenbb8e738e2018-04-28 14:10:43501std::unique_ptr<WebContents> WebContents::Create(
502 const WebContents::CreateParams& params) {
Albert J. Wong65fe64d2019-09-20 02:48:14503 return WebContentsImpl::Create(params);
504}
505
506std::unique_ptr<WebContentsImpl> WebContentsImpl::Create(
507 const CreateParams& params) {
508 return CreateWithOpener(params, FindOpenerRFH(params));
[email protected]d1198fd2012-08-13 22:50:19509}
510
erikchenade1fef2018-05-02 22:07:57511std::unique_ptr<WebContents> WebContents::CreateWithSessionStorage(
[email protected]54944cde2012-12-09 09:24:59512 const WebContents::CreateParams& params,
[email protected]fdac6ade2013-07-20 01:06:30513 const SessionStorageNamespaceMap& session_storage_namespace_map) {
erikchenade1fef2018-05-02 22:07:57514 std::unique_ptr<WebContentsImpl> new_contents(
515 new WebContentsImpl(params.browser_context));
Ian Clelland5cbaaf82017-11-27 22:00:03516 RenderFrameHostImpl* opener_rfh = FindOpenerRFH(params);
517 FrameTreeNode* opener = nullptr;
518 if (opener_rfh)
519 opener = opener_rfh->frame_tree_node();
520 new_contents->SetOpenerForNewContents(opener, params.opener_suppressed);
[email protected]fdac6ade2013-07-20 01:06:30521
jdoerrie55ec69d2018-10-08 13:34:46522 for (auto it = session_storage_namespace_map.begin();
523 it != session_storage_namespace_map.end(); ++it) {
Fergal Daly09d6c762020-05-29 02:05:18524 new_contents->GetController().SetSessionStorageNamespace(it->first,
525 it->second.get());
[email protected]fdac6ade2013-07-20 01:06:30526 }
527
Sean Toppingbbc4a2bd2019-01-30 02:16:14528 WebContentsImpl* outer_web_contents = nullptr;
Sam McNally69a33772018-06-27 16:54:12529 if (params.guest_delegate) {
530 // This makes |new_contents| act as a guest.
531 // For more info, see comment above class BrowserPluginGuest.
Albert J. Wongc55cc64d2018-10-12 02:50:04532 BrowserPluginGuest::CreateInWebContents(new_contents.get(),
533 params.guest_delegate);
Sean Toppingbbc4a2bd2019-01-30 02:16:14534 outer_web_contents = static_cast<WebContentsImpl*>(
535 params.guest_delegate->GetOwnerWebContents());
Sam McNally69a33772018-06-27 16:54:12536 }
537
[email protected]54944cde2012-12-09 09:24:59538 new_contents->Init(params);
Sean Toppingbbc4a2bd2019-01-30 02:16:14539 if (outer_web_contents)
540 outer_web_contents->InnerWebContentsCreated(new_contents.get());
[email protected]d1198fd2012-08-13 22:50:19541 return new_contents;
[email protected]a81343d232011-12-27 07:39:20542}
[email protected]746d3052012-05-22 15:15:47543
benwells5e7260d2017-03-20 23:36:33544void WebContentsImpl::FriendWrapper::AddCreatedCallbackForTesting(
nickf9acfbe2014-12-23 19:12:37545 const CreatedCallback& callback) {
[email protected]cbb1ef592013-06-05 19:49:46546 g_created_callbacks.Get().push_back(callback);
547}
548
benwells5e7260d2017-03-20 23:36:33549void WebContentsImpl::FriendWrapper::RemoveCreatedCallbackForTesting(
nickf9acfbe2014-12-23 19:12:37550 const CreatedCallback& callback) {
[email protected]cbb1ef592013-06-05 19:49:46551 for (size_t i = 0; i < g_created_callbacks.Get().size(); ++i) {
Robert Liao1db5a352019-06-05 20:57:34552 if (g_created_callbacks.Get().at(i) == callback) {
[email protected]cbb1ef592013-06-05 19:49:46553 g_created_callbacks.Get().erase(g_created_callbacks.Get().begin() + i);
554 return;
555 }
556 }
557}
558
avidf38c952015-10-27 13:45:13559WebContents* WebContents::FromRenderViewHost(RenderViewHost* rvh) {
560 if (!rvh)
561 return nullptr;
[email protected]746d3052012-05-22 15:15:47562 return rvh->GetDelegate()->GetAsWebContents();
563}
564
[email protected]a86c0e962013-12-17 17:10:39565WebContents* WebContents::FromRenderFrameHost(RenderFrameHost* rfh) {
avidf38c952015-10-27 13:45:13566 if (!rfh)
567 return nullptr;
Alexander Timin33bd754c02020-03-10 22:50:18568 if (!rfh->IsCurrent() && base::FeatureList::IsEnabled(
569 kCheckWebContentsAccessFromNonCurrentFrame)) {
570 // TODO(crbug.com/1059903): return nullptr here eventually.
571 base::debug::DumpWithoutCrashing();
572 }
avidf38c952015-10-27 13:45:13573 return static_cast<RenderFrameHostImpl*>(rfh)->delegate()->GetAsWebContents();
[email protected]a86c0e962013-12-17 17:10:39574}
575
ananta4b7467a52016-09-23 01:42:38576WebContents* WebContents::FromFrameTreeNodeId(int frame_tree_node_id) {
577 FrameTreeNode* frame_tree_node =
578 FrameTreeNode::GloballyFindByID(frame_tree_node_id);
anantab8cfa3b2016-10-14 22:43:19579 if (!frame_tree_node)
580 return nullptr;
jam8c4edd02017-05-06 18:50:33581 return WebContentsImpl::FromFrameTreeNode(frame_tree_node);
ananta4b7467a52016-09-23 01:42:38582}
583
leon.han552e9de2017-02-09 14:37:30584void WebContents::SetScreenOrientationDelegate(
585 ScreenOrientationDelegate* delegate) {
586 ScreenOrientationProvider::SetDelegate(delegate);
587}
588
[email protected]7fff43e2013-05-21 20:21:10589// WebContentsImpl::DestructionObserver ----------------------------------------
590
591class WebContentsImpl::DestructionObserver : public WebContentsObserver {
592 public:
593 DestructionObserver(WebContentsImpl* owner, WebContents* watched_contents)
Fergal Daly09d6c762020-05-29 02:05:18594 : WebContentsObserver(watched_contents), owner_(owner) {}
[email protected]7fff43e2013-05-21 20:21:10595
596 // WebContentsObserver:
dchengc2282aa2014-10-21 12:07:58597 void WebContentsDestroyed() override {
[email protected]12a46832014-05-09 13:35:58598 owner_->OnWebContentsDestroyed(
599 static_cast<WebContentsImpl*>(web_contents()));
[email protected]7fff43e2013-05-21 20:21:10600 }
601
602 private:
603 WebContentsImpl* owner_;
604
605 DISALLOW_COPY_AND_ASSIGN(DestructionObserver);
606};
607
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:50608// TODO(sreejakshetty): Make |WebContentsImpl::ColorChooser| per-frame instead
609// of WebContents-owned.
Joel Hockey85b379d2017-12-11 10:42:13610// WebContentsImpl::ColorChooser ----------------------------------------------
Joel Hockey163835a2017-12-20 11:51:57611class WebContentsImpl::ColorChooser : public blink::mojom::ColorChooser {
Joel Hockey85b379d2017-12-11 10:42:13612 public:
613 ColorChooser(content::ColorChooser* chooser,
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20614 mojo::PendingReceiver<blink::mojom::ColorChooser> receiver,
615 mojo::PendingRemote<blink::mojom::ColorChooserClient> client)
Joel Hockey85b379d2017-12-11 10:42:13616 : chooser_(chooser),
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20617 receiver_(this, std::move(receiver)),
Joel Hockey85b379d2017-12-11 10:42:13618 client_(std::move(client)) {
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20619 receiver_.set_disconnect_handler(
Joel Hockey85b379d2017-12-11 10:42:13620 base::BindOnce([](content::ColorChooser* chooser) { chooser->End(); },
621 base::Unretained(chooser)));
622 }
[email protected]8ed16472014-04-11 19:02:48623
Joel Hockey85b379d2017-12-11 10:42:13624 ~ColorChooser() override { chooser_->End(); }
[email protected]8ed16472014-04-11 19:02:48625
Joel Hockey85b379d2017-12-11 10:42:13626 void SetSelectedColor(SkColor color) override {
627 chooser_->SetSelectedColor(color);
628 }
629
630 void DidChooseColorInColorChooser(SkColor color) {
631 client_->DidChooseColor(color);
632 }
633
634 private:
635 // Color chooser that was opened by this tab.
636 std::unique_ptr<content::ColorChooser> chooser_;
637
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20638 // mojo receiver.
639 mojo::Receiver<blink::mojom::ColorChooser> receiver_;
Joel Hockey85b379d2017-12-11 10:42:13640
641 // mojo renderer client.
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20642 mojo::Remote<blink::mojom::ColorChooserClient> client_;
Joel Hockey85b379d2017-12-11 10:42:13643};
nicka0ac8382016-12-15 23:59:23644
lazyboy6ec48b2a2015-06-29 15:18:14645// WebContentsImpl::WebContentsTreeNode ----------------------------------------
lfg601233692017-03-06 22:45:44646WebContentsImpl::WebContentsTreeNode::WebContentsTreeNode(
647 WebContentsImpl* current_web_contents)
648 : current_web_contents_(current_web_contents),
649 outer_web_contents_(nullptr),
lazyboy6ec48b2a2015-06-29 15:18:14650 outer_contents_frame_tree_node_id_(
avallee0206f782016-07-28 18:55:33651 FrameTreeNode::kFrameTreeNodeInvalidId),
lfg601233692017-03-06 22:45:44652 focused_web_contents_(current_web_contents) {}
lazyboy6ec48b2a2015-06-29 15:18:14653
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18654WebContentsImpl::WebContentsTreeNode::~WebContentsTreeNode() {}
lazyboy6ec48b2a2015-06-29 15:18:14655
Lucas Furukawa Gadani99125822019-01-03 15:41:49656std::unique_ptr<WebContents>
657WebContentsImpl::WebContentsTreeNode::DisconnectFromOuterWebContents() {
658 std::unique_ptr<WebContents> inner_contents =
659 outer_web_contents_->node_.DetachInnerWebContents(current_web_contents_);
660 OuterContentsFrameTreeNode()->RemoveObserver(this);
661 outer_contents_frame_tree_node_id_ = FrameTreeNode::kFrameTreeNodeInvalidId;
662 outer_web_contents_ = nullptr;
663 return inner_contents;
664}
665
paulmeyerfeafc2d2017-04-25 21:46:40666void WebContentsImpl::WebContentsTreeNode::AttachInnerWebContents(
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:50667 std::unique_ptr<WebContents> inner_web_contents,
668 RenderFrameHostImpl* render_frame_host) {
669 WebContentsImpl* inner_web_contents_impl =
670 static_cast<WebContentsImpl*>(inner_web_contents.get());
671 WebContentsTreeNode& inner_web_contents_node = inner_web_contents_impl->node_;
672
673 inner_web_contents_node.focused_web_contents_ = nullptr;
674 inner_web_contents_node.outer_web_contents_ = current_web_contents_;
675 inner_web_contents_node.outer_contents_frame_tree_node_id_ =
676 render_frame_host->frame_tree_node()->frame_tree_node_id();
677
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18678 inner_web_contents_.push_back(std::move(inner_web_contents));
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:50679
680 render_frame_host->frame_tree_node()->AddObserver(&inner_web_contents_node);
Jeremy Roman03ce13ce2020-05-29 22:16:57681 current_web_contents_->InnerWebContentsAttached(inner_web_contents_impl);
paulmeyerfeafc2d2017-04-25 21:46:40682}
683
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18684std::unique_ptr<WebContents>
685WebContentsImpl::WebContentsTreeNode::DetachInnerWebContents(
paulmeyerfeafc2d2017-04-25 21:46:40686 WebContentsImpl* inner_web_contents) {
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18687 std::unique_ptr<WebContents> detached_contents;
688 for (std::unique_ptr<WebContents>& web_contents : inner_web_contents_) {
689 if (web_contents.get() == inner_web_contents) {
690 detached_contents = std::move(web_contents);
691 std::swap(web_contents, inner_web_contents_.back());
692 inner_web_contents_.pop_back();
Jeremy Roman03ce13ce2020-05-29 22:16:57693 current_web_contents_->InnerWebContentsDetached(inner_web_contents);
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18694 return detached_contents;
695 }
696 }
697
698 NOTREACHED();
699 return nullptr;
paulmeyerfeafc2d2017-04-25 21:46:40700}
701
lfga3e2bdc2017-03-07 20:44:01702FrameTreeNode*
703WebContentsImpl::WebContentsTreeNode::OuterContentsFrameTreeNode() const {
704 return FrameTreeNode::GloballyFindByID(outer_contents_frame_tree_node_id_);
lfg601233692017-03-06 22:45:44705}
706
lfga3e2bdc2017-03-07 20:44:01707void WebContentsImpl::WebContentsTreeNode::OnFrameTreeNodeDestroyed(
708 FrameTreeNode* node) {
709 DCHECK_EQ(outer_contents_frame_tree_node_id_, node->frame_tree_node_id())
710 << "WebContentsTreeNode should only receive notifications for the "
711 "FrameTreeNode in its outer WebContents that hosts it.";
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18712
713 // Deletes |this| too.
714 outer_web_contents_->node_.DetachInnerWebContents(current_web_contents_);
lazyboy6ec48b2a2015-06-29 15:18:14715}
716
avallee0206f782016-07-28 18:55:33717void WebContentsImpl::WebContentsTreeNode::SetFocusedWebContents(
718 WebContentsImpl* web_contents) {
719 DCHECK(!outer_web_contents())
720 << "Only the outermost WebContents tracks focus.";
721 focused_web_contents_ = web_contents;
722}
723
paulmeyerfeafc2d2017-04-25 21:46:40724WebContentsImpl*
725WebContentsImpl::WebContentsTreeNode::GetInnerWebContentsInFrame(
726 const FrameTreeNode* frame) {
727 auto ftn_id = frame->frame_tree_node_id();
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18728 for (auto& contents : inner_web_contents_) {
729 WebContentsImpl* impl = static_cast<WebContentsImpl*>(contents.get());
730 if (impl->node_.outer_contents_frame_tree_node_id() == ftn_id) {
731 return impl;
paulmeyerfeafc2d2017-04-25 21:46:40732 }
733 }
734 return nullptr;
735}
736
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18737std::vector<WebContentsImpl*>
738WebContentsImpl::WebContentsTreeNode::GetInnerWebContents() const {
739 std::vector<WebContentsImpl*> inner_web_contents;
740 for (auto& contents : inner_web_contents_)
741 inner_web_contents.push_back(static_cast<WebContentsImpl*>(contents.get()));
742
743 return inner_web_contents;
paulmeyerfeafc2d2017-04-25 21:46:40744}
745
Alexander Timin90c20c32020-08-12 15:28:32746// WebContentsObserverList -----------------------------------------------------
747WebContentsImpl::WebContentsObserverList::WebContentsObserverList() = default;
748WebContentsImpl::WebContentsObserverList::~WebContentsObserverList() = default;
749
750void WebContentsImpl::WebContentsObserverList::AddObserver(
751 WebContentsObserver* observer) {
752 observers_.AddObserver(observer);
753}
754
755void WebContentsImpl::WebContentsObserverList::RemoveObserver(
756 WebContentsObserver* observer) {
757 observers_.RemoveObserver(observer);
758}
759
[email protected]b172aee2012-04-10 17:05:26760// WebContentsImpl -------------------------------------------------------------
[email protected]420ae012009-04-24 05:16:32761
alexmose201c7cd2015-06-10 17:14:21762WebContentsImpl::WebContentsImpl(BrowserContext* browser_context)
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28763 : delegate_(nullptr),
[email protected]69e797f2013-04-30 01:10:22764 controller_(this, browser_context),
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28765 render_view_host_delegate_view_(nullptr),
alexmose201c7cd2015-06-10 17:14:21766 created_with_opener_(false),
Lucas Furukawa Gadani99125822019-01-03 15:41:49767 node_(this),
Fergal Daly09d6c762020-05-29 02:05:18768 frame_tree_(&controller_, this, this, this, this, this),
[email protected]6dfed692014-05-22 04:18:03769 is_load_to_different_document_(false),
[email protected]443b80e2010-12-14 00:42:23770 crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING),
771 crashed_error_code_(0),
[email protected]d5f942ba2008-09-26 19:30:34772 waiting_for_response_(false),
[email protected]fcf75d42013-12-03 20:11:26773 load_state_(net::LOAD_STATE_IDLE, base::string16()),
[email protected]094e5b22009-09-25 04:23:56774 upload_size_(0),
775 upload_position_(0),
dfalcantarae6b7b46752015-07-10 18:14:16776 is_resume_pending_(false),
[email protected]b4c84012014-04-28 19:51:10777 has_accessed_initial_document_(false),
Collin Bakerc5259962019-11-14 17:51:58778 visible_capturer_count_(0),
779 hidden_capturer_count_(0),
[email protected]fdd61c62009-04-22 19:22:57780 is_being_destroyed_(false),
[email protected]fdd61c62009-04-22 19:22:57781 notify_disconnection_(false),
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28782 dialog_manager_(nullptr),
[email protected]7ab1e7d62009-10-14 23:32:01783 is_showing_before_unload_dialog_(false),
gab0dccfef2015-05-20 18:43:39784 last_active_time_(base::TimeTicks::Now()),
[email protected]ebf40a72010-07-22 01:46:38785 closed_by_user_gesture_(false),
danakj938b37a62019-09-24 18:35:54786 minimum_zoom_percent_(
787 static_cast<int>(blink::kMinimumPageZoomFactor * 100)),
788 maximum_zoom_percent_(
789 static_cast<int>(blink::kMaximumPageZoomFactor * 100)),
w.shackleton49bcd392016-01-06 17:38:22790 zoom_scroll_remainder_(0),
alexmosc9e76ec2016-05-16 22:59:37791 fullscreen_widget_process_id_(ChildProcessHost::kInvalidUniqueID),
[email protected]5dcaf8e2013-12-28 01:31:42792 fullscreen_widget_routing_id_(MSG_ROUTING_NONE),
[email protected]0b431992014-06-24 00:08:03793 fullscreen_widget_had_focus_at_shutdown_(false),
[email protected]34ff1cfc2014-08-20 06:16:05794 force_disable_overscroll_content_(false),
[email protected]95640212014-07-26 18:14:30795 last_dialog_suppressed_(false),
waffles1c12bf402016-02-10 17:45:48796 accessibility_mode_(
Dominic Mazzoni21fb0282019-02-13 18:32:47797 GetContentClient()->browser()->GetAXModeForBrowserContext(
798 browser_context)),
avayvodcc85bbd2015-08-28 19:11:15799 audio_stream_monitor_(this),
Thomas Guilbert882c4cec2019-02-14 05:55:45800 media_web_contents_observer_(
801 std::make_unique<MediaWebContentsObserver>(this)),
mcnee336ea2c2017-05-23 22:50:59802#if !defined(OS_ANDROID)
mcnee432e47d2015-11-09 19:37:46803 page_scale_factor_is_one_(true),
mcnee336ea2c2017-05-23 22:50:59804#endif // !defined(OS_ANDROID)
qinmin72e8bd02016-10-21 19:35:37805 is_overlay_content_(false),
ekaramadf6750aa2017-06-06 18:29:42806 showing_context_menu_(false),
W. James MacLean62198672019-06-04 16:46:10807 text_autosizer_page_info_({0, 0, 1.f}),
shivanigithubcceeacf2020-03-06 20:00:27808 native_theme_observer_(this) {
danakjf4b9e942019-11-29 15:43:04809 frame_tree_.SetFrameRemoveListener(base::BindRepeating(
810 &WebContentsImpl::OnFrameRemoved, base::Unretained(this)));
brettw4b461082016-11-19 18:55:16811#if BUILDFLAG(ENABLE_PLUGINS)
zqzhang181047e62016-07-01 13:37:17812 pepper_playback_observer_.reset(new PepperPlaybackObserver(this));
813#endif
blundelle75a8f92017-03-27 08:11:17814
Becca Hughes86334622018-07-09 21:29:38815#if defined(OS_ANDROID)
Elly Fong-Jonescdd7ae82019-02-20 23:26:33816 display_cutout_host_impl_ = std::make_unique<DisplayCutoutHostImpl>(this);
Becca Hughes86334622018-07-09 21:29:38817#endif
John Delaney732721e92020-02-07 23:11:27818
Alison Maher7f366dc62020-03-03 19:46:00819 ui::NativeTheme* native_theme = ui::NativeTheme::GetInstanceForWeb();
820 native_theme_observer_.Add(native_theme);
821 using_dark_colors_ = native_theme->ShouldUseDarkColors();
822 preferred_color_scheme_ = native_theme->GetPreferredColorScheme();
823
Mike Wassermanb213b9352020-04-16 00:32:34824 screen_change_monitor_ =
825 std::make_unique<ScreenChangeMonitor>(base::BindRepeating(
826 &WebContentsImpl::OnScreensChange, base::Unretained(this)));
827
John Delaney732721e92020-02-07 23:11:27828 // ConversionHost takes a weak ref on |this|, so it must be created outside of
829 // the initializer list.
Charlie Harrison405f6212020-04-14 21:57:32830 if (base::FeatureList::IsEnabled(features::kConversionMeasurement)) {
831 conversion_host_ = std::make_unique<ConversionHost>(this);
832 }
[email protected]332af7732009-03-11 13:21:35833}
initial.commit09911bf2008-07-26 23:55:29834
[email protected]b172aee2012-04-10 17:05:26835WebContentsImpl::~WebContentsImpl() {
creisba91ba82017-05-12 22:56:19836 // Imperfect sanity check against double free, given some crashes unexpectedly
837 // observed in the wild.
838 CHECK(!is_being_destroyed_);
839
840 // We generally keep track of is_being_destroyed_ to let other features know
841 // to avoid certain actions during destruction.
[email protected]420ae012009-04-24 05:16:32842 is_being_destroyed_ = true;
843
creis97867aa2017-02-17 18:39:45844 // A WebContents should never be deleted while it is notifying observers,
creisba91ba82017-05-12 22:56:19845 // since this will lead to a use-after-free as it continues to notify later
creis97867aa2017-02-17 18:39:45846 // observers.
Alexander Timin90c20c32020-08-12 15:28:32847 CHECK(!observers_.is_notifying_observers());
creis97867aa2017-02-17 18:39:45848
Avi Drissman33972942020-06-19 14:16:01849 FullscreenContentsSet(GetBrowserContext())->erase(this);
850
kenrb2a565f82015-09-02 20:24:59851 rwh_input_event_router_.reset();
852
Julie Jeongeun Kim7d0986172019-12-04 03:17:25853 for (auto& entry : receiver_sets_)
854 entry.second->CloseAllReceivers();
rockotf62002a2016-09-15 00:08:59855
avallee0206f782016-07-28 18:55:33856 WebContentsImpl* outermost = GetOutermostWebContents();
avallee9993fca2016-11-17 06:16:50857 if (this != outermost && ContainsOrIsFocusedWebContents()) {
avallee0206f782016-07-28 18:55:33858 // If the current WebContents is in focus, unset it.
avallee9993fca2016-11-17 06:16:50859 outermost->SetAsFocusedWebContentsIfNecessary();
avallee0206f782016-07-28 18:55:33860 }
861
Nick Carterd73635b2018-03-13 18:31:41862 if (mouse_lock_widget_)
James Hollyerd5c9de462020-03-10 19:02:45863 mouse_lock_widget_->RejectMouseLockOrUnlockIfNecessary(
864 blink::mojom::PointerLockResult::kElementDestroyed);
Nick Carterd73635b2018-03-13 18:31:41865
dcheng72be33c2016-01-21 04:11:31866 for (FrameTreeNode* node : frame_tree_.Nodes()) {
867 // Delete all RFHs pending shutdown, which will lead the corresponding RVHs
868 // to be shutdown and be deleted as well.
dcheng57e39e22016-01-21 00:25:38869 node->render_manager()->ClearRFHsPendingShutdown();
dcheng57e39e22016-01-21 00:25:38870 node->render_manager()->ClearWebUIInstances();
dcheng72be33c2016-01-21 04:11:31871 }
carlosk35f35af2015-12-01 10:55:40872
dcheng57e39e22016-01-21 00:25:38873 for (RenderWidgetHostImpl* widget : created_widgets_)
874 widget->DetachDelegate();
[email protected]b24b68a2012-09-24 21:57:26875 created_widgets_.clear();
876
[email protected]3ab9cb82011-06-03 18:02:07877 // Clear out any JavaScript state.
avi5d3b8692016-10-12 22:00:46878 if (dialog_manager_) {
avi6879fcf2017-01-21 05:27:53879 dialog_manager_->CancelDialogs(this, /*reset_state=*/true);
avi5d3b8692016-10-12 22:00:46880 }
[email protected]3ab9cb82011-06-03 18:02:07881
Joel Hockey85b379d2017-12-11 10:42:13882 color_chooser_.reset();
Rakina Zata Amni16196122018-11-14 02:14:00883 find_request_manager_.reset();
[email protected]da8543762012-03-20 08:52:20884
[email protected]420ae012009-04-24 05:16:32885 NotifyDisconnected();
[email protected]420ae012009-04-24 05:16:32886
[email protected]ca13a442012-04-17 14:00:12887 // Notify any observer that have a reference on this WebContents.
[email protected]8ff00d72012-10-23 19:12:21888 NotificationService::current()->Notify(
889 NOTIFICATION_WEB_CONTENTS_DESTROYED,
890 Source<WebContents>(this),
891 NotificationService::NoDetails());
[email protected]420ae012009-04-24 05:16:32892
Arthur Sonzogni5a9a88c2018-10-18 13:16:00893 // Destroy all subframes now. This notifies observers.
894 GetMainFrame()->ResetChildren();
[email protected]df0c843f2014-05-23 20:37:23895 GetRenderManager()->ResetProxyHosts();
[email protected]c06c58c2014-03-12 20:31:59896
clamy0e119882015-07-31 16:12:33897 // Manually call the observer methods for the root frame tree node. It is
898 // necessary to manually delete all objects tracking navigations
899 // (NavigationHandle, NavigationRequest) for observers to be properly
900 // notified of these navigations stopping before the WebContents is
901 // destroyed.
[email protected]df0c843f2014-05-23 20:37:23902 RenderFrameHostManager* root = GetRenderManager();
naskob21fe4872015-02-24 14:15:56903
Lowell Manners20250112019-10-18 15:06:15904 GetController().GetBackForwardCache().Shutdown();
905
naskob21fe4872015-02-24 14:15:56906 root->current_frame_host()->SetRenderFrameCreated(false);
clamyfc3850d2018-02-23 14:35:28907 root->current_frame_host()->ResetNavigationRequests();
clamy0e119882015-07-31 16:12:33908
Arthur Hemeryc3380172018-01-22 14:00:17909 // Do not update state as the WebContents is being destroyed.
Arthur Hemery241b9392019-10-24 11:08:41910 frame_tree_.root()->ResetNavigationRequest(true);
Arthur Hemeryc3380172018-01-22 14:00:17911 if (root->speculative_frame_host()) {
danakjf2342432019-05-15 21:46:09912 root->speculative_frame_host()->DeleteRenderFrame(
913 FrameDeleteIntention::kSpeculativeMainFrameForShutdown);
Arthur Hemeryc3380172018-01-22 14:00:17914 root->speculative_frame_host()->SetRenderFrameCreated(false);
clamyfc3850d2018-02-23 14:35:28915 root->speculative_frame_host()->ResetNavigationRequests();
clamy0e119882015-07-31 16:12:33916 }
[email protected]f273ee52013-10-18 16:05:27917
brettw4b461082016-11-19 18:55:16918#if BUILDFLAG(ENABLE_PLUGINS)
zqzhang181047e62016-07-01 13:37:17919 // Call this before WebContentsDestroyed() is broadcasted since
920 // AudioFocusManager will be destroyed after that.
921 pepper_playback_observer_.reset();
922#endif // defined(ENABLED_PLUGINS)
923
Chris Hamiltondf0d72cd2018-05-29 16:23:53924 // If audio is playing then notify external observers of the audio stream
925 // disappearing.
926 if (is_currently_audible_) {
927 is_currently_audible_ = false;
Alexander Timin90c20c32020-08-12 15:28:32928 observers_.ForEachObserver([&](WebContentsObserver* observer) {
929 observer->OnAudioStateChanged(false);
930 });
Chris Hamiltondf0d72cd2018-05-29 16:23:53931 if (GetOuterWebContents())
932 GetOuterWebContents()->OnAudioStateChanged();
933 }
934
Alexander Timin90c20c32020-08-12 15:28:32935 observers_.ForEachObserver([&](WebContentsObserver* observer) {
936 observer->FrameDeleted(root->current_frame_host());
937 });
938 observers_.ForEachObserver([&](WebContentsObserver* observer) {
939 observer->RenderViewDeleted(root->current_host());
940 });
Kevin McNee576bb5d82019-05-29 16:47:51941#if defined(OS_ANDROID)
942 // For simplicity, destroy the Java WebContents before we notify of the
943 // destruction of the WebContents.
944 ClearWebContentsAndroid();
945#endif
946
Alexander Timin90c20c32020-08-12 15:28:32947 observers_.ForEachObserver(
948 [&](WebContentsObserver* observer) { observer->WebContentsDestroyed(); });
Becca Hughesd11d6502018-07-31 17:01:28949 if (display_cutout_host_impl_)
950 display_cutout_host_impl_->WebContentsDestroyed();
951
Alexander Timin90c20c32020-08-12 15:28:32952 observers_.ForEachObserver(
953 [&](WebContentsObserver* observer) { observer->ResetWebContents(); });
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28954 SetDelegate(nullptr);
[email protected]b5a1d11c2011-02-17 03:09:42955}
956
erikchen50735fd2018-05-05 15:08:33957std::unique_ptr<WebContentsImpl> WebContentsImpl::CreateWithOpener(
[email protected]54944cde2012-12-09 09:24:59958 const WebContents::CreateParams& params,
Ian Clelland5cbaaf82017-11-27 22:00:03959 RenderFrameHostImpl* opener_rfh) {
[email protected]e11f0e92013-06-12 15:12:03960 TRACE_EVENT0("browser", "WebContentsImpl::CreateWithOpener");
Ian Clelland5cbaaf82017-11-27 22:00:03961 FrameTreeNode* opener = nullptr;
962 if (opener_rfh)
963 opener = opener_rfh->frame_tree_node();
erikchen50735fd2018-05-05 15:08:33964 std::unique_ptr<WebContentsImpl> new_contents(
965 new WebContentsImpl(params.browser_context));
lukasza6f8ac622017-06-06 03:10:20966 new_contents->SetOpenerForNewContents(opener, params.opener_suppressed);
alexmose201c7cd2015-06-10 17:14:21967
alexmosaedfc6f2016-01-21 23:57:38968 // If the opener is sandboxed, a new popup must inherit the opener's sandbox
969 // flags, and these flags take effect immediately. An exception is if the
970 // opener's sandbox flags lack the PropagatesToAuxiliaryBrowsingContexts
971 // bit (which is controlled by the "allow-popups-to-escape-sandbox" token).
972 // See https://html.spec.whatwg.org/#attr-iframe-sandbox.
lukasza6f8ac622017-06-06 03:10:20973 FrameTreeNode* new_root = new_contents->GetFrameTree()->root();
alexmosaedfc6f2016-01-21 23:57:38974 if (opener) {
arthursonzognib93a4472020-04-10 07:38:00975 network::mojom::WebSandboxFlags opener_flags =
Antonio Gomes7096ac02020-02-14 14:29:54976 opener_rfh->active_sandbox_flags();
arthursonzognib93a4472020-04-10 07:38:00977 const network::mojom::WebSandboxFlags inherit_flag =
978 network::mojom::WebSandboxFlags::kPropagatesToAuxiliaryBrowsingContexts;
Ehsan Karamad39407082019-02-19 23:38:19979 bool sandbox_propagates_to_auxilary_context =
980 (opener_flags & inherit_flag) == inherit_flag;
981 if (sandbox_propagates_to_auxilary_context)
Charlie Hue1b77ac2019-12-13 21:30:17982 new_root->SetPendingFramePolicy({opener_flags,
983 {} /* container_policy */,
984 {} /* required_document_policy */});
arthursonzognib93a4472020-04-10 07:38:00985 if (opener_flags == network::mojom::WebSandboxFlags::kNone ||
Ehsan Karamad39407082019-02-19 23:38:19986 sandbox_propagates_to_auxilary_context) {
987 // TODO(ekaramad, iclelland): Do not propagate feature policies from non-
988 // sandboxed disowned openers (rel=noopener).
989 // If the current page is not sandboxed, or if the sandbox is to propagate
990 // to the popups then opener's feature policy will apply to the new popup
991 // as well.
992 new_root->SetOpenerFeaturePolicyState(
Ehsan Karamad34d10682019-02-26 20:55:04993 opener_rfh->feature_policy()->GetFeatureState());
alexmosaedfc6f2016-01-21 23:57:38994 }
995 }
996
mark a. foltzef394fce2017-10-21 09:11:02997 // Apply starting sandbox flags.
Luna Luc3fdacdf2017-11-08 04:48:53998 blink::FramePolicy frame_policy(new_root->pending_frame_policy());
mark a. foltzef394fce2017-10-21 09:11:02999 frame_policy.sandbox_flags |= params.starting_sandbox_flags;
1000 new_root->SetPendingFramePolicy(frame_policy);
Charlie Hu5ffc0152019-12-06 15:59:531001 new_root->CommitFramePolicy(frame_policy);
mark a. foltzef394fce2017-10-21 09:11:021002
alexmose201c7cd2015-06-10 17:14:211003 // This may be true even when opener is null, such as when opening blocked
1004 // popups.
alexmos090fae8e2015-05-28 17:09:281005 if (params.created_with_opener)
1006 new_contents->created_with_opener_ = true;
1007
Sean Toppingbbc4a2bd2019-01-30 02:16:141008 WebContentsImpl* outer_web_contents = nullptr;
[email protected]4858e432014-06-23 18:14:171009 if (params.guest_delegate) {
[email protected]83100cd2014-05-10 11:50:061010 // This makes |new_contents| act as a guest.
1011 // For more info, see comment above class BrowserPluginGuest.
Albert J. Wongc55cc64d2018-10-12 02:50:041012 BrowserPluginGuest::CreateInWebContents(new_contents.get(),
1013 params.guest_delegate);
Sean Toppingbbc4a2bd2019-01-30 02:16:141014 outer_web_contents = static_cast<WebContentsImpl*>(
1015 params.guest_delegate->GetOwnerWebContents());
[email protected]83100cd2014-05-10 11:50:061016 }
mark a. foltzef394fce2017-10-21 09:11:021017
[email protected]54944cde2012-12-09 09:24:591018 new_contents->Init(params);
Sean Toppingbbc4a2bd2019-01-30 02:16:141019 if (outer_web_contents)
1020 outer_web_contents->InnerWebContentsCreated(new_contents.get());
[email protected]d1198fd2012-08-13 22:50:191021 return new_contents;
1022}
1023
[email protected]95640212014-07-26 18:14:301024// static
1025std::vector<WebContentsImpl*> WebContentsImpl::GetAllWebContents() {
1026 std::vector<WebContentsImpl*> result;
dcheng59716272016-04-09 05:19:081027 std::unique_ptr<RenderWidgetHostIterator> widgets(
[email protected]95640212014-07-26 18:14:301028 RenderWidgetHostImpl::GetRenderWidgetHosts());
[email protected]95640212014-07-26 18:14:301029 while (RenderWidgetHost* rwh = widgets->GetNextHost()) {
[email protected]95640212014-07-26 18:14:301030 RenderViewHost* rvh = RenderViewHost::From(rwh);
1031 if (!rvh)
1032 continue;
1033 WebContents* web_contents = WebContents::FromRenderViewHost(rvh);
1034 if (!web_contents)
1035 continue;
avidf38c952015-10-27 13:45:131036 if (web_contents->GetRenderViewHost() != rvh)
1037 continue;
1038 // Because a WebContents can only have one current RVH at a time, there will
1039 // be no duplicate WebContents here.
1040 result.push_back(static_cast<WebContentsImpl*>(web_contents));
[email protected]95640212014-07-26 18:14:301041 }
1042 return result;
1043}
1044
clamya16aa8172015-05-26 13:07:251045// static
1046WebContentsImpl* WebContentsImpl::FromFrameTreeNode(
paulmeyerfeafc2d2017-04-25 21:46:401047 const FrameTreeNode* frame_tree_node) {
clamya16aa8172015-05-26 13:07:251048 return static_cast<WebContentsImpl*>(
1049 WebContents::FromRenderFrameHost(frame_tree_node->current_frame_host()));
1050}
1051
clamy0d32d6d2015-11-24 11:16:261052// static
Patrick Monette275a6f92b2020-01-09 21:05:041053WebContents* WebContentsImpl::FromRenderFrameHostID(
1054 GlobalFrameRoutingId render_frame_host_id) {
1055 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI) ||
1056 !BrowserThread::IsThreadInitialized(BrowserThread::UI));
Patrick Monette7364e6972020-01-09 22:56:021057 RenderFrameHost* render_frame_host =
1058 RenderFrameHost::FromID(render_frame_host_id);
1059 if (!render_frame_host)
1060 return nullptr;
1061
1062 return WebContents::FromRenderFrameHost(render_frame_host);
Patrick Monette275a6f92b2020-01-09 21:05:041063}
1064
1065// static
clamy0d32d6d2015-11-24 11:16:261066WebContents* WebContentsImpl::FromRenderFrameHostID(int render_process_host_id,
1067 int render_frame_host_id) {
Patrick Monette7364e6972020-01-09 22:56:021068 return FromRenderFrameHostID(
1069 GlobalFrameRoutingId(render_process_host_id, render_frame_host_id));
clamy0d32d6d2015-11-24 11:16:261070}
1071
paulmeyerfeafc2d2017-04-25 21:46:401072// static
1073WebContentsImpl* WebContentsImpl::FromOuterFrameTreeNode(
1074 const FrameTreeNode* frame_tree_node) {
1075 return WebContentsImpl::FromFrameTreeNode(frame_tree_node)
1076 ->node_.GetInnerWebContentsInFrame(frame_tree_node);
1077}
1078
[email protected]b0936d22013-11-28 06:47:361079RenderFrameHostManager* WebContentsImpl::GetRenderManagerForTesting() {
[email protected]fa944cb82013-11-15 17:51:211080 return GetRenderManager();
[email protected]765187182012-01-11 23:59:281081}
1082
nicka0ac8382016-12-15 23:59:231083bool WebContentsImpl::OnMessageReceived(RenderViewHostImpl* render_view_host,
[email protected]7bb761892012-07-20 09:32:471084 const IPC::Message& message) {
Alexander Timin90c20c32020-08-12 15:28:321085 for (auto& observer : observers_.observer_list()) {
Lukasz Anforowicz89f2c1b2017-08-30 21:36:461086 // TODO(nick, creis): https://crbug.com/758026: Replace all uses of this
1087 // variant of OnMessageReceived with the version that takes a
1088 // RenderFrameHost, and then delete it.
nicka0ac8382016-12-15 23:59:231089 if (observer.OnMessageReceived(message))
1090 return true;
[email protected]64ffefa2014-05-10 12:06:331091 }
[email protected]403415a2011-01-10 18:57:531092
Henrique Ferreiroba535472020-04-21 11:38:361093#if BUILDFLAG(ENABLE_PLUGINS)
[email protected]724159a2010-12-30 01:11:181094 bool handled = true;
nicka0ac8382016-12-15 23:59:231095 IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(WebContentsImpl, message, render_view_host)
nicka0ac8382016-12-15 23:59:231096 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission,
1097 OnRequestPpapiBrokerPermission)
nicka0ac8382016-12-15 23:59:231098 IPC_MESSAGE_UNHANDLED(handled = false)
1099 IPC_END_MESSAGE_MAP()
nicka0ac8382016-12-15 23:59:231100 return handled;
Henrique Ferreiroba535472020-04-21 11:38:361101#else
1102 return false;
1103#endif
nicka0ac8382016-12-15 23:59:231104}
1105
1106bool WebContentsImpl::OnMessageReceived(RenderFrameHostImpl* render_frame_host,
1107 const IPC::Message& message) {
Alexander Timin90c20c32020-08-12 15:28:321108 for (auto& observer : observers_.observer_list()) {
nicka0ac8382016-12-15 23:59:231109 if (observer.OnMessageReceived(message, render_frame_host))
1110 return true;
1111 }
1112
1113 bool handled = true;
brettw4b461082016-11-19 18:55:161114#if BUILDFLAG(ENABLE_PLUGINS)
Hiroki Nakagawa761b9b02020-07-13 11:12:021115 IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(WebContentsImpl, message, render_frame_host)
emaxxe70f5e12015-05-29 11:26:001116 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceCreated,
1117 OnPepperInstanceCreated)
1118 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceDeleted,
1119 OnPepperInstanceDeleted)
tommyclie6633ca72014-10-31 00:40:421120 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung, OnPepperPluginHung)
zqzhang181047e62016-07-01 13:37:171121 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperStartsPlayback,
1122 OnPepperStartsPlayback)
1123 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperStopsPlayback,
1124 OnPepperStopsPlayback)
tommyclie6633ca72014-10-31 00:40:421125 IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed, OnPluginCrashed)
[email protected]724159a2010-12-30 01:11:181126 IPC_MESSAGE_UNHANDLED(handled = false)
[email protected]e44d1342014-05-16 21:29:331127 IPC_END_MESSAGE_MAP()
Hiroki Nakagawa761b9b02020-07-13 11:12:021128#else
1129 handled = false;
1130#endif
[email protected]724159a2010-12-30 01:11:181131
[email protected]724159a2010-12-30 01:11:181132 return handled;
1133}
1134
[email protected]d1198fd2012-08-13 22:50:191135NavigationControllerImpl& WebContentsImpl::GetController() {
[email protected]f5fa20e2011-12-21 22:35:561136 return controller_;
1137}
1138
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411139BrowserContext* WebContentsImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:551140 return controller_.GetBrowserContext();
[email protected]627e0512011-12-21 22:55:301141}
1142
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411143const GURL& WebContentsImpl::GetURL() {
Peter Boström101d7672018-12-15 00:43:591144 return GetVisibleURL();
[email protected]be1f56ab2011-12-22 06:55:311145}
1146
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411147const GURL& WebContentsImpl::GetVisibleURL() {
[email protected]c854a7e2013-05-21 16:42:241148 // We may not have a navigation entry yet.
[email protected]59167c22013-06-03 18:07:321149 NavigationEntry* entry = controller_.GetVisibleEntry();
[email protected]c854a7e2013-05-21 16:42:241150 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
1151}
1152
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411153const GURL& WebContentsImpl::GetLastCommittedURL() {
[email protected]c854a7e2013-05-21 16:42:241154 // We may not have a navigation entry yet.
1155 NavigationEntry* entry = controller_.GetLastCommittedEntry();
1156 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
1157}
1158
[email protected]8ff00d72012-10-23 19:12:211159WebContentsDelegate* WebContentsImpl::GetDelegate() {
[email protected]be1f56ab2011-12-22 06:55:311160 return delegate_;
1161}
1162
[email protected]8ff00d72012-10-23 19:12:211163void WebContentsImpl::SetDelegate(WebContentsDelegate* delegate) {
[email protected]be1f56ab2011-12-22 06:55:311164 // TODO(cbentzel): remove this debugging code?
1165 if (delegate == delegate_)
1166 return;
1167 if (delegate_)
1168 delegate_->Detach(this);
1169 delegate_ = delegate;
[email protected]a6b73c62013-02-11 23:05:081170 if (delegate_) {
[email protected]be1f56ab2011-12-22 06:55:311171 delegate_->Attach(this);
[email protected]a6b73c62013-02-11 23:05:081172 // Ensure the visible RVH reflects the new delegate's preferences.
[email protected]86f98a22013-03-20 14:35:001173 if (view_)
[email protected]e85165c642014-06-10 14:34:311174 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
Joel Einbinder848001c2017-09-19 21:39:311175 if (GetRenderViewHost())
1176 RenderFrameDevToolsAgentHost::WebContentsCreated(this);
[email protected]a6b73c62013-02-11 23:05:081177 }
[email protected]be1f56ab2011-12-22 06:55:311178}
1179
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411180RenderFrameHostImpl* WebContentsImpl::GetMainFrame() {
[email protected]94d0cc12013-12-18 00:07:411181 return frame_tree_.root()->current_frame_host();
[email protected]60eca4eb2013-12-06 00:02:161182}
1183
nick53d5cbf2015-04-23 22:50:141184RenderFrameHostImpl* WebContentsImpl::GetFocusedFrame() {
1185 FrameTreeNode* focused_node = frame_tree_.GetFocusedFrame();
1186 if (!focused_node)
1187 return nullptr;
1188 return focused_node->current_frame_host();
[email protected]9c9343b2014-03-08 02:56:071189}
1190
rob3e2a0732016-01-06 21:22:091191RenderFrameHostImpl* WebContentsImpl::FindFrameByFrameTreeNodeId(
creisf71a2632017-05-04 19:03:501192 int frame_tree_node_id,
1193 int process_id) {
1194 FrameTreeNode* frame = frame_tree_.FindByID(frame_tree_node_id);
1195
1196 // Sanity check that this is in the caller's expected process. Otherwise a
1197 // recent cross-process navigation may have led to a privilege change that the
1198 // caller is not expecting.
1199 if (!frame ||
1200 frame->current_frame_host()->GetProcess()->GetID() != process_id)
1201 return nullptr;
1202
1203 return frame->current_frame_host();
1204}
1205
1206RenderFrameHostImpl* WebContentsImpl::UnsafeFindFrameByFrameTreeNodeId(
rob3e2a0732016-01-06 21:22:091207 int frame_tree_node_id) {
creisf71a2632017-05-04 19:03:501208 // Beware using this! The RenderFrameHost may have changed since the caller
1209 // obtained frame_tree_node_id.
rob3e2a0732016-01-06 21:22:091210 FrameTreeNode* frame = frame_tree_.FindByID(frame_tree_node_id);
1211 return frame ? frame->current_frame_host() : nullptr;
1212}
1213
[email protected]a86c0e962013-12-17 17:10:391214void WebContentsImpl::ForEachFrame(
Lei Zhangebcc6302018-01-12 19:46:451215 const base::RepeatingCallback<void(RenderFrameHost*)>& on_frame) {
dcheng57e39e22016-01-21 00:25:381216 for (FrameTreeNode* node : frame_tree_.Nodes()) {
1217 on_frame.Run(node->current_frame_host());
1218 }
[email protected]a86c0e962013-12-17 17:10:391219}
1220
dchengafb53e22016-02-04 08:11:081221std::vector<RenderFrameHost*> WebContentsImpl::GetAllFrames() {
Xuehui Xieb2300ae42020-06-09 20:25:051222 return GetAllFramesImpl(frame_tree_, /*include_pending=*/false);
1223}
1224
1225std::vector<RenderFrameHost*> WebContentsImpl::GetAllFramesIncludingPending() {
1226 return GetAllFramesImpl(frame_tree_, /*include_pending=*/true);
dchengafb53e22016-02-04 08:11:081227}
1228
lukaszacbdf52e2016-01-15 21:19:511229int WebContentsImpl::SendToAllFrames(IPC::Message* message) {
Xuehui Xieb2300ae42020-06-09 20:25:051230 return SendToAllFramesImpl(frame_tree_, /*include_pending=*/false, message);
1231}
lukasza1a9ab2422016-03-02 18:47:251232
Xuehui Xieb2300ae42020-06-09 20:25:051233int WebContentsImpl::SendToAllFramesIncludingPending(IPC::Message* message) {
1234 return SendToAllFramesImpl(frame_tree_, /*include_pending=*/true, message);
[email protected]a86c0e962013-12-17 17:10:391235}
1236
lfgdb5c4ed2016-03-04 23:09:071237void WebContentsImpl::SendPageMessage(IPC::Message* msg) {
alexmos136fd6e62016-08-15 20:58:411238 frame_tree_.root()->render_manager()->SendPageMessage(msg, nullptr);
lfgdb5c4ed2016-03-04 23:09:071239}
1240
Gyuyoung Kim877e86d2020-07-21 04:01:021241void WebContentsImpl::ExecutePageBroadcastMethod(
1242 PageBroadcastMethodCallback callback) {
1243 frame_tree_.root()->render_manager()->ExecutePageBroadcastMethod(callback);
1244}
1245
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411246RenderViewHostImpl* WebContentsImpl::GetRenderViewHost() {
[email protected]fa944cb82013-11-15 17:51:211247 return GetRenderManager()->current_host();
[email protected]be1f56ab2011-12-22 06:55:311248}
1249
creis89a0f782015-05-27 16:13:171250void WebContentsImpl::CancelActiveAndPendingDialogs() {
Evan Stade753fc202020-07-13 18:09:541251 if (dialog_manager_) {
avi6879fcf2017-01-21 05:27:531252 dialog_manager_->CancelDialogs(this, /*reset_state=*/false);
Evan Stade753fc202020-07-13 18:09:541253 }
creis89a0f782015-05-27 16:13:171254 if (browser_plugin_embedder_)
1255 browser_plugin_embedder_->CancelGuestDialogs();
1256}
1257
naskoc0fceff2015-04-30 15:53:521258void WebContentsImpl::ClosePage() {
1259 GetRenderViewHost()->ClosePage();
1260}
1261
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411262RenderWidgetHostView* WebContentsImpl::GetRenderWidgetHostView() {
[email protected]fa944cb82013-11-15 17:51:211263 return GetRenderManager()->GetRenderWidgetHostView();
[email protected]be1f56ab2011-12-22 06:55:311264}
1265
lfg265a2672016-04-23 03:11:021266RenderWidgetHostView* WebContentsImpl::GetTopLevelRenderWidgetHostView() {
1267 if (GetOuterWebContents())
1268 return GetOuterWebContents()->GetTopLevelRenderWidgetHostView();
1269 return GetRenderManager()->GetRenderWidgetHostView();
1270}
1271
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411272RenderWidgetHostView* WebContentsImpl::GetFullscreenRenderWidgetHostView() {
vmpstr6d9996c82017-02-23 00:43:251273 if (auto* widget_host = GetFullscreenRenderWidgetHost())
ekaramadaeb3c5c2016-11-09 03:22:351274 return widget_host->GetView();
1275 return nullptr;
[email protected]4aebbca2013-09-17 22:26:491276}
1277
[email protected]8ff00d72012-10-23 19:12:211278WebContentsView* WebContentsImpl::GetView() const {
[email protected]be1f56ab2011-12-22 06:55:311279 return view_.get();
1280}
1281
Mike Wassermanb213b9352020-04-16 00:32:341282void WebContentsImpl::OnScreensChange() {
1283 for (FrameTreeNode* node : frame_tree_.Nodes()) {
1284 RenderFrameHostImpl* rfh = node->current_frame_host();
1285 rfh->GetAssociatedLocalFrame()->OnScreensChange();
1286 }
1287}
1288
leon.han552e9de2017-02-09 14:37:301289void WebContentsImpl::OnScreenOrientationChange() {
1290 DCHECK(screen_orientation_provider_);
Lan Weif81c6e7c2020-02-12 16:46:091291 DidChangeScreenOrientation();
Becca Hughese9e27952018-06-25 17:08:271292 screen_orientation_provider_->OnOrientationChange();
leon.hane4db177a2017-02-07 14:19:161293}
1294
Alan Cutter92d59252019-03-29 02:32:331295base::Optional<SkColor> WebContentsImpl::GetThemeColor() {
Carlos Caballero1215f882019-10-29 15:58:431296 return GetRenderViewHost()->theme_color();
yusufod41c5f92015-03-06 00:14:281297}
1298
Doug Turner63f3c7b2017-07-29 05:10:011299void WebContentsImpl::SetAccessibilityMode(ui::AXMode mode) {
[email protected]95640212014-07-26 18:14:301300 if (mode == accessibility_mode_)
1301 return;
1302
dmazzonif8a31042016-12-03 00:52:131303 // Don't allow accessibility to be enabled for WebContents that are never
danakj77eb7e82020-01-09 19:38:461304 // user-visible, like background pages.
1305 if (IsNeverComposited())
dmazzonif8a31042016-12-03 00:52:131306 return;
1307
[email protected]95640212014-07-26 18:14:301308 accessibility_mode_ = mode;
dcheng57e39e22016-01-21 00:25:381309
1310 for (FrameTreeNode* node : frame_tree_.Nodes()) {
dmazzonif8a31042016-12-03 00:52:131311 UpdateAccessibilityModeOnFrame(node->current_frame_host());
clamy610c63b32017-12-22 15:05:181312 // Also update accessibility mode on the speculative RenderFrameHost for
1313 // this FrameTreeNode, if one exists.
Alex Moshchuk3d8a1f392017-10-24 19:01:261314 RenderFrameHost* speculative_frame_host =
1315 node->render_manager()->speculative_frame_host();
1316 if (speculative_frame_host)
1317 UpdateAccessibilityModeOnFrame(speculative_frame_host);
dcheng57e39e22016-01-21 00:25:381318 }
[email protected]95640212014-07-26 18:14:301319}
1320
Doug Turner63f3c7b2017-07-29 05:10:011321void WebContentsImpl::AddAccessibilityMode(ui::AXMode mode) {
1322 ui::AXMode new_mode(accessibility_mode_);
dougtcd3dad732017-03-14 03:26:231323 new_mode |= mode;
1324 SetAccessibilityMode(new_mode);
[email protected]95640212014-07-26 18:14:301325}
1326
Avi Drissman1e620f32018-03-16 13:57:291327// Helper class used by WebContentsImpl::RequestAXTreeSnapshot.
1328// Handles the callbacks from parallel snapshot requests to each frame,
1329// and feeds the results to an AXTreeCombiner, which converts them into a
1330// single combined accessibility tree.
1331class WebContentsImpl::AXTreeSnapshotCombiner
1332 : public base::RefCounted<AXTreeSnapshotCombiner> {
1333 public:
1334 explicit AXTreeSnapshotCombiner(AXTreeSnapshotCallback callback)
1335 : callback_(std::move(callback)) {}
1336
1337 AXTreeSnapshotCallback AddFrame(bool is_root) {
1338 // Adds a reference to |this|.
1339 return base::BindOnce(&AXTreeSnapshotCombiner::ReceiveSnapshot, this,
1340 is_root);
1341 }
1342
1343 void ReceiveSnapshot(bool is_root, const ui::AXTreeUpdate& snapshot) {
1344 combiner_.AddTree(snapshot, is_root);
1345 }
1346
1347 private:
1348 friend class base::RefCounted<AXTreeSnapshotCombiner>;
1349
1350 // This is called automatically after the last call to ReceiveSnapshot
1351 // when there are no more references to this object.
1352 ~AXTreeSnapshotCombiner() {
1353 combiner_.Combine();
1354 std::move(callback_).Run(combiner_.combined());
1355 }
1356
1357 ui::AXTreeCombiner combiner_;
1358 AXTreeSnapshotCallback callback_;
1359};
1360
1361void WebContentsImpl::RequestAXTreeSnapshot(AXTreeSnapshotCallback callback,
1362 ui::AXMode ax_mode) {
dmazzonid95ae842016-04-12 21:17:391363 // Send a request to each of the frames in parallel. Each one will return
1364 // an accessibility tree snapshot, and AXTreeSnapshotCombiner will combine
1365 // them into a single tree and call |callback| with that result, then
1366 // delete |combiner|.
Avi Drissman1e620f32018-03-16 13:57:291367 FrameTreeNode* root_node = frame_tree_.root();
tzik58faa742018-08-01 10:54:181368 auto combiner =
1369 base::MakeRefCounted<AXTreeSnapshotCombiner>(std::move(callback));
Avi Drissman1e620f32018-03-16 13:57:291370
tzik58faa742018-08-01 10:54:181371 RecursiveRequestAXTreeSnapshotOnFrame(root_node, combiner.get(), ax_mode);
Avi Drissman1e620f32018-03-16 13:57:291372}
1373
1374void WebContentsImpl::RecursiveRequestAXTreeSnapshotOnFrame(
1375 FrameTreeNode* root_node,
1376 AXTreeSnapshotCombiner* combiner,
1377 ui::AXMode ax_mode) {
dmazzonid95ae842016-04-12 21:17:391378 for (FrameTreeNode* frame_tree_node : frame_tree_.Nodes()) {
Avi Drissman1e620f32018-03-16 13:57:291379 WebContentsImpl* inner_contents =
1380 node_.GetInnerWebContentsInFrame(frame_tree_node);
1381 if (inner_contents) {
1382 inner_contents->RecursiveRequestAXTreeSnapshotOnFrame(root_node, combiner,
1383 ax_mode);
1384 } else {
1385 bool is_root = frame_tree_node == root_node;
1386 frame_tree_node->current_frame_host()->RequestAXTreeSnapshot(
1387 combiner->AddFrame(is_root), ax_mode);
1388 }
dmazzonid95ae842016-04-12 21:17:391389 }
dmazzoni83ba5c82015-04-14 07:11:511390}
1391
Becca Hughes3b5a43482018-07-17 22:31:551392void WebContentsImpl::NotifyViewportFitChanged(
1393 blink::mojom::ViewportFit value) {
Alexander Timin90c20c32020-08-12 15:28:321394 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1395 observer->ViewportFitChanged(value);
1396 });
Becca Hughes3b5a43482018-07-17 22:31:551397}
1398
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411399FindRequestManager* WebContentsImpl::GetFindRequestManagerForTesting() {
Ehsan Karamad6beb2ea2018-11-25 18:15:131400 return GetFindRequestManager();
1401}
1402
mcnee336ea2c2017-05-23 22:50:591403#if !defined(OS_ANDROID)
akabac6bd1212018-06-25 20:10:481404void WebContentsImpl::UpdateZoom() {
1405 RenderWidgetHostImpl* rwh = GetRenderViewHost()->GetWidget();
1406 if (rwh->GetView())
1407 rwh->SynchronizeVisualProperties();
wjmaclean64951902016-04-29 20:59:121408}
1409
wjmaclean64951902016-04-29 20:59:121410
1411void WebContentsImpl::UpdateZoomIfNecessary(const std::string& scheme,
akabac6bd1212018-06-25 20:10:481412 const std::string& host) {
wjmaclean64951902016-04-29 20:59:121413 NavigationEntry* entry = GetController().GetLastCommittedEntry();
1414 if (!entry)
1415 return;
1416
1417 GURL url = HostZoomMap::GetURLFromEntry(entry);
1418 if (host != net::GetHostOrSpecFromURL(url) ||
1419 (!scheme.empty() && !url.SchemeIs(scheme))) {
1420 return;
1421 }
1422
akabac6bd1212018-06-25 20:10:481423 UpdateZoom();
wjmaclean64951902016-04-29 20:59:121424}
mcnee336ea2c2017-05-23 22:50:591425#endif // !defined(OS_ANDROID)
wjmaclean64951902016-04-29 20:59:121426
Julie Jeongeun Kim7d0986172019-12-04 03:17:251427base::OnceClosure WebContentsImpl::AddReceiverSet(
rockotf62002a2016-09-15 00:08:591428 const std::string& interface_name,
Julie Jeongeun Kim7d0986172019-12-04 03:17:251429 WebContentsReceiverSet* receiver_set) {
rockotf62002a2016-09-15 00:08:591430 auto result =
Julie Jeongeun Kim7d0986172019-12-04 03:17:251431 receiver_sets_.insert(std::make_pair(interface_name, receiver_set));
rockotf62002a2016-09-15 00:08:591432 DCHECK(result.second);
Julie Jeongeun Kim7d0986172019-12-04 03:17:251433 return base::BindOnce(&WebContentsImpl::RemoveReceiverSet,
danakjf4b9e942019-11-29 15:43:041434 weak_factory_.GetWeakPtr(), interface_name);
rockotf62002a2016-09-15 00:08:591435}
1436
Julie Jeongeun Kim7d0986172019-12-04 03:17:251437WebContentsReceiverSet* WebContentsImpl::GetReceiverSet(
rockot8bbad222017-03-22 04:34:051438 const std::string& interface_name) {
Julie Jeongeun Kim7d0986172019-12-04 03:17:251439 auto it = receiver_sets_.find(interface_name);
1440 if (it == receiver_sets_.end())
rockot8bbad222017-03-22 04:34:051441 return nullptr;
1442 return it->second;
1443}
1444
John Delaney732721e92020-02-07 23:11:271445void WebContentsImpl::RemoveReceiverSetForTesting(
1446 const std::string& interface_name) {
1447 RemoveReceiverSet(interface_name);
1448}
1449
paulmeyerfeafc2d2017-04-25 21:46:401450std::vector<WebContentsImpl*> WebContentsImpl::GetWebContentsAndAllInner() {
1451 std::vector<WebContentsImpl*> all_contents(1, this);
1452
1453 for (size_t i = 0; i != all_contents.size(); ++i) {
1454 for (auto* inner_contents : all_contents[i]->GetInnerWebContents()) {
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:161455 all_contents.push_back(static_cast<WebContentsImpl*>(inner_contents));
paulmeyerfeafc2d2017-04-25 21:46:401456 }
1457 }
1458
1459 return all_contents;
1460}
1461
Sam McNally145fb172017-05-10 00:13:231462void WebContentsImpl::NotifyManifestUrlChanged(
Yuzu Saijo0c263c702020-06-08 03:41:241463 RenderFrameHost* rfh,
Sam McNally145fb172017-05-10 00:13:231464 const base::Optional<GURL>& manifest_url) {
Alexander Timin90c20c32020-08-12 15:28:321465 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1466 observer->DidUpdateWebManifestURL(rfh, manifest_url);
1467 });
Sam McNally145fb172017-05-10 00:13:231468}
1469
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411470WebUI* WebContentsImpl::GetWebUI() {
Nasko Oskov2f7d2112019-10-29 03:26:571471 WebUI* committed_web_ui = GetCommittedWebUI();
1472 if (committed_web_ui)
1473 return committed_web_ui;
1474
1475 if (GetRenderManager()->speculative_frame_host())
1476 return GetRenderManager()->speculative_frame_host()->web_ui();
1477
1478 return nullptr;
[email protected]be1f56ab2011-12-22 06:55:311479}
1480
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411481WebUI* WebContentsImpl::GetCommittedWebUI() {
carlosk35f35af2015-12-01 10:55:401482 return frame_tree_.root()->current_frame_host()->web_ui();
[email protected]d5f942ba2008-09-26 19:30:341483}
1484
Maks Orlovich73f374d2020-04-02 12:46:131485void WebContentsImpl::SetUserAgentOverride(
1486 const blink::UserAgentOverride& ua_override,
1487 bool override_in_new_tabs) {
1488 DCHECK(!ua_override.ua_metadata_override.has_value() ||
1489 !ua_override.ua_string_override.empty());
1490
1491 if (GetUserAgentOverride() == ua_override)
[email protected]bf70edce2012-06-20 22:32:221492 return;
1493
Changwan Ryuc1134a82018-03-07 02:10:141494 should_override_user_agent_in_new_tabs_ = override_in_new_tabs;
1495
Maks Orlovich73f374d2020-04-02 12:46:131496 renderer_preferences_.user_agent_override = ua_override;
[email protected]bf70edce2012-06-20 22:32:221497
Bruce Long1e3e1f542019-10-16 17:56:281498 // Send the new override string to all renderers in the current page.
1499 SyncRendererPrefs();
[email protected]bf70edce2012-06-20 22:32:221500
1501 // Reload the page if a load is currently in progress to avoid having
1502 // different parts of the page loaded using different user agents.
Scott Violete1d58cc2020-04-28 23:07:171503 // No need to reload if the current entry matches that of the
1504 // NavigationRequest supplied to DidStartNavigation() as NavigationRequest
1505 // handles it.
[email protected]6286a372013-10-09 04:03:271506 NavigationEntry* entry = controller_.GetVisibleEntry();
Scott Violete1d58cc2020-04-28 23:07:171507 if (IsLoading() && entry != nullptr && entry->GetIsOverridingUserAgent() &&
1508 (!frame_tree_.root()->navigation_request() ||
1509 frame_tree_.root()->navigation_request()->ua_change_requires_reload())) {
toyoshim6142d96f2016-12-19 09:07:251510 controller_.Reload(ReloadType::BYPASSING_CACHE, true);
Scott Violete1d58cc2020-04-28 23:07:171511 }
[email protected]8d0f3312012-08-18 01:47:531512
Alexander Timin90c20c32020-08-12 15:28:321513 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1514 observer->UserAgentOverrideSet(ua_override);
1515 });
[email protected]86ef6a392012-05-11 22:03:111516}
1517
Scott Violet2a6c5bff2020-04-29 23:59:061518void WebContentsImpl::SetRendererInitiatedUserAgentOverrideOption(
1519 NavigationController::UserAgentOverrideOption option) {
1520 renderer_initiated_user_agent_override_option_ = option;
1521}
1522
Maks Orlovich73f374d2020-04-02 12:46:131523const blink::UserAgentOverride& WebContentsImpl::GetUserAgentOverride() {
[email protected]bf70edce2012-06-20 22:32:221524 return renderer_preferences_.user_agent_override;
[email protected]86ef6a392012-05-11 22:03:111525}
1526
Scott Violet2a6c5bff2020-04-29 23:59:061527bool WebContentsImpl::ShouldOverrideUserAgentForRendererInitiatedNavigation() {
1528 NavigationEntryImpl* current_entry = controller_.GetLastCommittedEntry();
1529 if (!current_entry)
1530 return should_override_user_agent_in_new_tabs_;
1531
1532 switch (renderer_initiated_user_agent_override_option_) {
1533 case NavigationController::UA_OVERRIDE_INHERIT:
1534 return current_entry->GetIsOverridingUserAgent();
1535 case NavigationController::UA_OVERRIDE_TRUE:
1536 return true;
1537 case NavigationController::UA_OVERRIDE_FALSE:
1538 return false;
1539 default:
1540 break;
1541 }
1542 return false;
Changwan Ryuc1134a82018-03-07 02:10:141543}
1544
dmazzonidd3d51a72016-12-14 18:41:011545void WebContentsImpl::EnableWebContentsOnlyAccessibilityMode() {
Dominic Mazzonid9fda172019-03-07 17:12:071546 // If accessibility is already enabled, we'll need to force a reset
1547 // in order to ensure new observers of accessibility events get the
1548 // full accessibility tree from scratch.
1549 bool need_reset = GetAccessibilityMode().has_mode(ui::AXMode::kWebContents);
1550
1551 ui::AXMode desired_mode =
1552 GetContentClient()->browser()->GetAXModeForBrowserContext(
1553 GetBrowserContext());
1554 desired_mode |= ui::kAXModeWebContentsOnly;
1555 AddAccessibilityMode(desired_mode);
1556
1557 if (need_reset) {
dchengafb53e22016-02-04 08:11:081558 for (RenderFrameHost* rfh : GetAllFrames())
1559 ResetAccessibility(rfh);
dchengafb53e22016-02-04 08:11:081560 }
[email protected]95640212014-07-26 18:14:301561}
1562
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411563bool WebContentsImpl::IsWebContentsOnlyAccessibilityModeForTesting() {
Doug Turner63f3c7b2017-07-29 05:10:011564 return accessibility_mode_ == ui::kAXModeWebContentsOnly;
[email protected]95640212014-07-26 18:14:301565}
1566
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411567bool WebContentsImpl::IsFullAccessibilityModeForTesting() {
Doug Turner63f3c7b2017-07-29 05:10:011568 return accessibility_mode_ == ui::kAXModeComplete;
[email protected]95640212014-07-26 18:14:301569}
1570
Becca Hughes6daf5662018-06-27 16:50:541571#if defined(OS_ANDROID)
1572
1573void WebContentsImpl::SetDisplayCutoutSafeArea(gfx::Insets insets) {
Becca Hughes86334622018-07-09 21:29:381574 if (display_cutout_host_impl_)
1575 display_cutout_host_impl_->SetDisplayCutoutSafeArea(insets);
Becca Hughes6daf5662018-06-27 16:50:541576}
1577
1578#endif
1579
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411580const base::string16& WebContentsImpl::GetTitle() {
Nasko Oskov2f7d2112019-10-29 03:26:571581 WebUI* our_web_ui =
1582 GetRenderManager()->speculative_frame_host()
1583 ? GetRenderManager()->speculative_frame_host()->web_ui()
1584 : GetRenderManager()->current_frame_host()->web_ui();
[email protected]7ade2732011-02-10 00:13:581585 if (our_web_ui) {
[email protected]96d185d2009-04-24 03:28:541586 // Don't override the title in view source mode.
Carlos IL4dea8902020-05-26 15:14:291587 NavigationEntry* entry = controller_.GetVisibleEntry();
[email protected]96d185d2009-04-24 03:28:541588 if (!(entry && entry->IsViewSourceMode())) {
[email protected]e0112912011-02-02 22:54:351589 // Give the Web UI the chance to override our title.
[email protected]fcf75d42013-12-03 20:11:261590 const base::string16& title = our_web_ui->GetOverriddenTitle();
[email protected]96d185d2009-04-24 03:28:541591 if (!title.empty())
1592 return title;
1593 }
1594 }
1595
1596 // We use the title for the last committed entry rather than a pending
1597 // navigation entry. For example, when the user types in a URL, we want to
1598 // keep the old page's title until the new load has committed and we get a new
1599 // title.
Carlos IL4dea8902020-05-26 15:14:291600 NavigationEntry* entry = controller_.GetLastCommittedEntry();
[email protected]59167c22013-06-03 18:07:321601
creis072b61f2015-09-28 20:52:241602 // We make an exception for initial navigations. We only want to use the title
1603 // from the visible entry if:
1604 // 1. The pending entry has been explicitly assigned a title to display.
1605 // 2. The user is doing a history navigation in a new tab (e.g., Ctrl+Back),
1606 // which case there is a pending entry index other than -1.
1607 //
1608 // Otherwise, we want to stick with the last committed entry's title during
1609 // new navigations, which have pending entries at index -1 with no title.
1610 if (controller_.IsInitialNavigation() &&
1611 ((controller_.GetVisibleEntry() &&
1612 !controller_.GetVisibleEntry()->GetTitle().empty()) ||
1613 controller_.GetPendingEntryIndex() != -1)) {
1614 entry = controller_.GetVisibleEntry();
[email protected]9eeafc012013-11-25 23:49:471615 }
[email protected]59167c22013-06-03 18:07:321616
[email protected]45d0ef7f2011-01-05 13:46:231617 if (entry) {
jshin1fb76462016-04-05 22:13:031618 return entry->GetTitleForDisplay();
[email protected]45d0ef7f2011-01-05 13:46:231619 }
[email protected]987fc3a2011-05-26 14:18:091620
1621 // |page_title_when_no_navigation_entry_| is finally used
1622 // if no title cannot be retrieved.
1623 return page_title_when_no_navigation_entry_;
[email protected]96d185d2009-04-24 03:28:541624}
1625
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411626SiteInstanceImpl* WebContentsImpl::GetSiteInstance() {
[email protected]fa944cb82013-11-15 17:51:211627 return GetRenderManager()->current_host()->GetSiteInstance();
[email protected]96d185d2009-04-24 03:28:541628}
1629
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411630bool WebContentsImpl::IsLoading() {
Carlos ILd51e7702020-05-07 18:51:391631 return frame_tree_.IsLoading();
[email protected]3c9e1872010-11-18 16:17:491632}
1633
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411634double WebContentsImpl::GetLoadProgress() {
Peter Boström18a40fa2018-10-31 19:03:501635 return frame_tree_.load_progress();
1636}
1637
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411638bool WebContentsImpl::IsLoadingToDifferentDocument() {
clamy44e84ce2016-02-22 15:38:251639 return IsLoading() && is_load_to_different_document_;
[email protected]6dfed692014-05-22 04:18:031640}
1641
Alexander Timindd0fa0c52019-11-06 13:03:371642bool WebContentsImpl::IsDocumentOnLoadCompletedInMainFrame() {
1643 return GetRenderViewHost()->IsDocumentOnLoadCompletedInMainFrame();
1644}
1645
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411646bool WebContentsImpl::IsWaitingForResponse() {
Peter Boströma9a27f6e2018-11-21 13:12:191647 NavigationRequest* ongoing_navigation_request =
1648 frame_tree_.root()->navigation_request();
1649
1650 // An ongoing navigation request means we're waiting for a response.
1651 return ongoing_navigation_request != nullptr;
[email protected]be1f56ab2011-12-22 06:55:311652}
1653
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411654const net::LoadStateWithParam& WebContentsImpl::GetLoadState() {
[email protected]be1f56ab2011-12-22 06:55:311655 return load_state_;
1656}
1657
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411658const base::string16& WebContentsImpl::GetLoadStateHost() {
[email protected]be1f56ab2011-12-22 06:55:311659 return load_state_host_;
1660}
1661
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411662uint64_t WebContentsImpl::GetUploadSize() {
[email protected]be1f56ab2011-12-22 06:55:311663 return upload_size_;
1664}
1665
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411666uint64_t WebContentsImpl::GetUploadPosition() {
[email protected]be1f56ab2011-12-22 06:55:311667 return upload_position_;
1668}
1669
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411670const std::string& WebContentsImpl::GetEncoding() {
Alexander Timine5f20e22019-10-09 23:22:351671 return GetMainFrame()->GetEncoding();
[email protected]be1f56ab2011-12-22 06:55:311672}
1673
Charles Zhaod72f99d2018-09-17 14:18:271674bool WebContentsImpl::WasDiscarded() {
1675 return GetFrameTree()->root()->was_discarded();
1676}
1677
Shubhie Panickerddf2a4e2018-03-06 00:09:061678void WebContentsImpl::SetWasDiscarded(bool was_discarded) {
1679 GetFrameTree()->root()->set_was_discarded();
1680}
1681
Collin Bakerc5259962019-11-14 17:51:581682void WebContentsImpl::IncrementCapturerCount(const gfx::Size& capture_size,
1683 bool stay_hidden) {
[email protected]5a652232013-02-12 06:15:251684 DCHECK(!is_being_destroyed_);
Collin Bakerc5259962019-11-14 17:51:581685 if (stay_hidden)
1686 ++hidden_capturer_count_;
1687 else
1688 ++visible_capturer_count_;
[email protected]222f5822014-02-05 23:40:491689
1690 // Note: This provides a hint to upstream code to size the views optimally
1691 // for quality (e.g., to avoid scaling).
1692 if (!capture_size.IsEmpty() && preferred_size_for_capture_.IsEmpty()) {
1693 preferred_size_for_capture_ = capture_size;
1694 OnPreferredSizeChanged(preferred_size_);
1695 }
ccameron8807c38f2015-01-17 00:29:191696
Collin Bakerc5259962019-11-14 17:51:581697 UpdateVisibilityAndNotifyPageAndView(GetVisibility());
[email protected]54597982013-02-06 01:59:551698}
1699
Collin Bakerc5259962019-11-14 17:51:581700void WebContentsImpl::DecrementCapturerCount(bool stay_hidden) {
1701 if (stay_hidden)
1702 --hidden_capturer_count_;
1703 else
1704 --visible_capturer_count_;
1705 DCHECK_GE(hidden_capturer_count_, 0);
1706 DCHECK_GE(visible_capturer_count_, 0);
[email protected]54597982013-02-06 01:59:551707
[email protected]5a652232013-02-12 06:15:251708 if (is_being_destroyed_)
1709 return;
1710
Francois Doray24fc62c2017-12-11 17:27:331711 if (!IsBeingCaptured()) {
[email protected]222f5822014-02-05 23:40:491712 const gfx::Size old_size = preferred_size_for_capture_;
1713 preferred_size_for_capture_ = gfx::Size();
1714 OnPreferredSizeChanged(old_size);
[email protected]54597982013-02-06 01:59:551715 }
Collin Bakerc5259962019-11-14 17:51:581716
1717 UpdateVisibilityAndNotifyPageAndView(GetVisibility());
[email protected]be1f56ab2011-12-22 06:55:311718}
1719
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411720bool WebContentsImpl::IsBeingCaptured() {
Collin Bakerc5259962019-11-14 17:51:581721 return visible_capturer_count_ + hidden_capturer_count_ > 0;
[email protected]f2bd40812013-07-20 04:30:441722}
1723
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411724bool WebContentsImpl::IsAudioMuted() {
Guido Urdanetaf8372942019-11-15 09:47:211725 return audio_stream_factory_ && audio_stream_factory_->IsMuted();
miu50f97892014-09-22 22:49:521726}
1727
1728void WebContentsImpl::SetAudioMuted(bool mute) {
1729 DVLOG(1) << "SetAudioMuted(mute=" << mute << "), was " << IsAudioMuted()
1730 << " for WebContentsImpl@" << this;
1731
1732 if (mute == IsAudioMuted())
1733 return;
1734
Guido Urdanetaf8372942019-11-15 09:47:211735 GetAudioStreamFactory()->SetMuted(mute);
miu50f97892014-09-22 22:49:521736
Alexander Timin90c20c32020-08-12 15:28:321737 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1738 observer->DidUpdateAudioMutingState(mute);
1739 });
Jan Rucka442c83f2017-08-08 13:27:541740 // Notification for UI updates in response to the changed muting state.
Collin Bakeraf540cf2019-09-20 20:54:161741 NotifyNavigationStateChanged(INVALIDATE_TYPE_AUDIO);
Jan Rucka442c83f2017-08-08 13:27:541742}
1743
1744bool WebContentsImpl::IsCurrentlyAudible() {
Chris Hamiltondf0d72cd2018-05-29 16:23:531745 return is_currently_audible_;
miu50f97892014-09-22 22:49:521746}
1747
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411748bool WebContentsImpl::IsConnectedToBluetoothDevice() {
ortunodf4d7982016-04-08 02:33:351749 return bluetooth_connected_device_count_ > 0;
ortuno32e7db3c2016-03-29 16:14:201750}
1751
Ovidio Henriquez76696f62020-07-08 03:06:591752bool WebContentsImpl::IsScanningForBluetoothDevices() {
1753 return bluetooth_scanning_sessions_count_ > 0;
1754}
1755
Lucas Furukawa Gadani4b4eed02019-06-04 23:12:041756bool WebContentsImpl::IsConnectedToSerialPort() {
Reilly Grant5e7c79b22019-04-09 17:26:201757 return serial_active_frame_count_ > 0;
1758}
1759
Matt Reynoldse8c6c1f2019-11-02 09:53:531760bool WebContentsImpl::IsConnectedToHidDevice() {
1761 return hid_active_frame_count_ > 0;
1762}
1763
Marijn Kruisselbrink29051042019-08-06 22:56:551764bool WebContentsImpl::HasNativeFileSystemHandles() {
1765 return native_file_system_handle_count_ > 0;
1766}
Marijn Kruisselbrinkf1714aa22019-07-02 03:45:331767
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411768bool WebContentsImpl::HasPictureInPictureVideo() {
sawtellea7333a82018-05-31 02:36:361769 return has_picture_in_picture_video_;
1770}
1771
1772void WebContentsImpl::SetHasPictureInPictureVideo(
1773 bool has_picture_in_picture_video) {
1774 // If status of |this| is already accurate, there is no need to update.
1775 if (has_picture_in_picture_video == has_picture_in_picture_video_)
1776 return;
1777 has_picture_in_picture_video_ = has_picture_in_picture_video;
1778 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
Alexander Timin90c20c32020-08-12 15:28:321779 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1780 observer->MediaPictureInPictureChanged(has_picture_in_picture_video_);
1781 });
sawtellea7333a82018-05-31 02:36:361782}
1783
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411784bool WebContentsImpl::IsCrashed() {
Dominic Mazzoni73a48322018-05-25 18:14:071785 switch (crashed_status_) {
1786 case base::TERMINATION_STATUS_PROCESS_CRASHED:
1787 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
1788 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED:
1789 case base::TERMINATION_STATUS_OOM:
1790 case base::TERMINATION_STATUS_LAUNCH_FAILED:
Darin Fisher6cf20e782020-08-07 22:25:361791#if defined(OS_CHROMEOS) || BUILDFLAG(IS_LACROS)
Dominic Mazzoni73a48322018-05-25 18:14:071792 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM:
oshima620225722015-06-04 19:45:271793#endif
Dominic Mazzoni73a48322018-05-25 18:14:071794#if defined(OS_ANDROID)
1795 case base::TERMINATION_STATUS_OOM_PROTECTED:
1796#endif
Will Harris07925d12019-10-31 03:03:051797#if defined(OS_WIN)
1798 case base::TERMINATION_STATUS_INTEGRITY_FAILURE:
1799#endif
Dominic Mazzoni73a48322018-05-25 18:14:071800 return true;
1801 case base::TERMINATION_STATUS_NORMAL_TERMINATION:
1802 case base::TERMINATION_STATUS_STILL_RUNNING:
1803 return false;
1804 case base::TERMINATION_STATUS_MAX_ENUM:
1805 NOTREACHED();
1806 return false;
1807 }
1808
1809 NOTREACHED();
1810 return false;
[email protected]3c9e1872010-11-18 16:17:491811}
1812
[email protected]b172aee2012-04-10 17:05:261813void WebContentsImpl::SetIsCrashed(base::TerminationStatus status,
1814 int error_code) {
[email protected]443b80e2010-12-14 00:42:231815 if (status == crashed_status_)
[email protected]d5f942ba2008-09-26 19:30:341816 return;
1817
[email protected]443b80e2010-12-14 00:42:231818 crashed_status_ = status;
1819 crashed_error_code_ = error_code;
[email protected]8ff00d72012-10-23 19:12:211820 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
[email protected]d5f942ba2008-09-26 19:30:341821}
1822
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411823base::TerminationStatus WebContentsImpl::GetCrashedStatus() {
[email protected]be1f56ab2011-12-22 06:55:311824 return crashed_status_;
1825}
1826
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411827int WebContentsImpl::GetCrashedErrorCode() {
afakhry98241832016-03-11 19:27:471828 return crashed_error_code_;
1829}
1830
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411831bool WebContentsImpl::IsBeingDestroyed() {
[email protected]be1f56ab2011-12-22 06:55:311832 return is_being_destroyed_;
1833}
1834
[email protected]7f924832014-08-09 05:57:221835void WebContentsImpl::NotifyNavigationStateChanged(
1836 InvalidateTypes changed_flags) {
dalecurtis88c240072015-12-09 02:11:181837 // Notify the media observer of potential audibility changes.
Collin Bakeraf540cf2019-09-20 20:54:161838 if (changed_flags & INVALIDATE_TYPE_AUDIO) {
mlamouri44e4ef42016-01-20 18:42:271839 media_web_contents_observer_->MaybeUpdateAudibleState();
dalecurtisbc6572e12014-09-12 19:22:301840 }
1841
[email protected]d5f942ba2008-09-26 19:30:341842 if (delegate_)
1843 delegate_->NavigationStateChanged(this, changed_flags);
wjmaclean1dabf3e32016-05-13 23:34:441844
1845 if (GetOuterWebContents())
1846 GetOuterWebContents()->NotifyNavigationStateChanged(changed_flags);
[email protected]d5f942ba2008-09-26 19:30:341847}
1848
W. James MacLean6f34b042019-07-12 19:25:301849RenderFrameHostImpl* WebContentsImpl::GetFocusedFrameFromFocusedDelegate() {
1850 FrameTreeNode* focused_node =
1851 GetFocusedWebContents()->frame_tree_.GetFocusedFrame();
1852 return focused_node ? focused_node->current_frame_host() : nullptr;
1853}
1854
David Black9cca3592019-11-06 23:02:221855void WebContentsImpl::OnVerticalScrollDirectionChanged(
1856 viz::VerticalScrollDirection scroll_direction) {
Alexander Timin90c20c32020-08-12 15:28:321857 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1858 observer->DidChangeVerticalScrollDirection(scroll_direction);
1859 });
David Black9cca3592019-11-06 23:02:221860}
1861
Chris Hamiltondf0d72cd2018-05-29 16:23:531862void WebContentsImpl::OnAudioStateChanged() {
1863 // This notification can come from any embedded contents or from this
1864 // WebContents' stream monitor. Aggregate these signals to get the actual
1865 // state.
Jeremy Roman03ce13ce2020-05-29 22:16:571866 //
1867 // Note that guests may not be attached as inner contents, and so may need to
1868 // be checked separately.
Chris Hamiltondf0d72cd2018-05-29 16:23:531869 bool is_currently_audible =
1870 audio_stream_monitor_.IsCurrentlyAudible() ||
1871 (browser_plugin_embedder_ &&
Jeremy Roman03ce13ce2020-05-29 22:16:571872 browser_plugin_embedder_->AreAnyGuestsCurrentlyAudible()) ||
1873 AnyInnerWebContents(this, [](WebContents* inner_contents) {
1874 return inner_contents->IsCurrentlyAudible();
1875 });
Chris Hamiltondf0d72cd2018-05-29 16:23:531876 if (is_currently_audible == is_currently_audible_)
1877 return;
1878
1879 // Update internal state.
1880 is_currently_audible_ = is_currently_audible;
1881 was_ever_audible_ = was_ever_audible_ || is_currently_audible_;
1882
Gyuyoung Kim877e86d2020-07-21 04:01:021883 ExecutePageBroadcastMethod(base::BindRepeating(
1884 [](bool is_currently_audible, RenderViewHostImpl* rvh) {
1885 if (auto& broadcast = rvh->GetAssociatedPageBroadcast())
1886 broadcast->AudioStateChanged(is_currently_audible);
1887 },
1888 is_currently_audible_));
altimind8bd26c2016-11-04 11:44:541889
altiminec87fd1f2016-11-17 20:22:491890 // Notification for UI updates in response to the changed audio state.
Collin Bakeraf540cf2019-09-20 20:54:161891 NotifyNavigationStateChanged(INVALIDATE_TYPE_AUDIO);
Jan Rucka442c83f2017-08-08 13:27:541892
Chris Hamiltondf0d72cd2018-05-29 16:23:531893 // Ensure that audio state changes propagate from innermost to outermost
1894 // WebContents.
1895 if (GetOuterWebContents())
1896 GetOuterWebContents()->OnAudioStateChanged();
Tommy Steimel18360512017-11-01 00:38:191897
Alexander Timin90c20c32020-08-12 15:28:321898 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1899 observer->OnAudioStateChanged(is_currently_audible_);
1900 });
altimind8bd26c2016-11-04 11:44:541901}
1902
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411903base::TimeTicks WebContentsImpl::GetLastActiveTime() {
[email protected]9a890452014-02-13 22:21:021904 return last_active_time_;
[email protected]3e324142012-06-25 18:26:331905}
1906
[email protected]9e2e4632012-07-27 16:38:411907void WebContentsImpl::WasShown() {
Collin Baker989e0882019-11-01 01:27:171908 UpdateVisibilityAndNotifyPageAndView(Visibility::VISIBLE);
[email protected]be1f56ab2011-12-22 06:55:311909}
1910
[email protected]b172aee2012-04-10 17:05:261911void WebContentsImpl::WasHidden() {
Collin Baker989e0882019-11-01 01:27:171912 UpdateVisibilityAndNotifyPageAndView(Visibility::HIDDEN);
[email protected]375fa1b2012-05-22 22:05:371913}
1914
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411915bool WebContentsImpl::HasRecentInteractiveInputEvent() {
Daniel Cheng90196c82018-04-25 21:49:141916 static constexpr base::TimeDelta kMaxInterval =
1917 base::TimeDelta::FromSeconds(5);
1918 base::TimeDelta delta =
1919 ui::EventTimeForNow() - last_interactive_input_event_time_;
1920 // Note: the expectation is that the caller is typically expecting an input
1921 // event, e.g. validating that a WebUI message that requires a gesture is
Daniel Chenge81030b32019-07-17 20:20:231922 // actually attached to a gesture.
Daniel Cheng90196c82018-04-25 21:49:141923 return delta <= kMaxInterval;
1924}
1925
Avi Drissman738ea192018-08-29 20:24:161926void WebContentsImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1927 ignore_input_events_ = ignore_input_events;
1928}
1929
Bo Liu168c8642017-08-28 18:26:021930#if defined(OS_ANDROID)
Bo Liu16dd7b8322018-05-02 21:19:501931void WebContentsImpl::SetMainFrameImportance(
1932 ChildProcessImportance importance) {
1933 GetMainFrame()->GetRenderWidgetHost()->SetImportance(importance);
Bo Liu7c6779e92017-08-16 02:02:281934}
Bo Liu168c8642017-08-28 18:26:021935#endif
Bo Liu7c6779e92017-08-16 02:02:281936
ccameron8807c38f2015-01-17 00:29:191937void WebContentsImpl::WasOccluded() {
Collin Baker989e0882019-11-01 01:27:171938 UpdateVisibilityAndNotifyPageAndView(Visibility::OCCLUDED);
ccameron8807c38f2015-01-17 00:29:191939}
1940
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411941Visibility WebContentsImpl::GetVisibility() {
Francois Doraye6161152018-03-27 22:05:371942 return visibility_;
Francois Dorayfe4a1772018-02-17 04:17:091943}
1944
Rakina Zata Amni26e8d8a2020-08-05 06:06:061945bool WebContentsImpl::NeedToFireBeforeUnloadOrUnloadEvents() {
Alexander Timinc7bee322020-05-19 17:54:341946 if (!notify_disconnection_)
Alex Moshchuk6fcaca752018-07-14 02:13:591947 return false;
1948
1949 // Don't fire if the main frame's RenderViewHost indicates that beforeunload
1950 // and unload have already executed (e.g., after receiving a ClosePage ACK)
1951 // or should be ignored.
1952 if (GetRenderViewHost()->SuddenTerminationAllowed())
1953 return false;
1954
Alex Moshchukc78dbc722019-10-31 20:00:501955 // Check whether any frame in the frame tree needs to run beforeunload or
Rakina Zata Amni26e8d8a2020-08-05 06:06:061956 // unload-time event handlers.
Alex Moshchukc78dbc722019-10-31 20:00:501957 for (FrameTreeNode* node : frame_tree_.Nodes()) {
1958 RenderFrameHostImpl* rfh = node->current_frame_host();
1959
Rakina Zata Amni26e8d8a2020-08-05 06:06:061960 // No need to run beforeunload/unload-time events if the RenderFrame isn't
1961 // live.
Alex Moshchukc78dbc722019-10-31 20:00:501962 if (!rfh->IsRenderFrameLive())
1963 continue;
Rakina Zata Amni26e8d8a2020-08-05 06:06:061964 bool should_run_before_unload_handler =
Dave Tapuska97d22ab2019-12-03 17:56:361965 rfh->GetSuddenTerminationDisablerState(
Rakina Zata Amni26e8d8a2020-08-05 06:06:061966 blink::mojom::SuddenTerminationDisablerType::kBeforeUnloadHandler);
1967 bool should_run_unload_handler = rfh->GetSuddenTerminationDisablerState(
1968 blink::mojom::SuddenTerminationDisablerType::kUnloadHandler);
1969 bool should_run_page_hide_handler = rfh->GetSuddenTerminationDisablerState(
1970 blink::mojom::SuddenTerminationDisablerType::kPageHideHandler);
1971 auto* rvh = static_cast<RenderViewHostImpl*>(rfh->GetRenderViewHost());
1972 // If the tab is already hidden, we should not run visibilitychange
1973 // handlers.
1974 bool is_page_visible = rvh->GetPageLifecycleStateManager()
1975 ->CalculatePageLifecycleState()
1976 ->visibility == PageVisibilityState::kVisible;
1977
1978 bool should_run_visibility_change_handler =
1979 is_page_visible && rfh->GetSuddenTerminationDisablerState(
1980 blink::mojom::SuddenTerminationDisablerType::
1981 kVisibilityChangeHandler);
1982 if (should_run_before_unload_handler || should_run_unload_handler ||
1983 should_run_page_hide_handler || should_run_visibility_change_handler) {
Alex Moshchukc78dbc722019-10-31 20:00:501984 return true;
1985 }
Aditya Keerthi34f37e62019-03-08 15:54:531986 }
Alex Moshchuk6fcaca752018-07-14 02:13:591987
Alex Moshchukc78dbc722019-10-31 20:00:501988 return false;
[email protected]be1f56ab2011-12-22 06:55:311989}
1990
Chris Hamilton3b3e315d2018-09-19 13:16:211991void WebContentsImpl::DispatchBeforeUnload(bool auto_cancel) {
1992 auto before_unload_type =
1993 auto_cancel ? RenderFrameHostImpl::BeforeUnloadType::DISCARD
1994 : RenderFrameHostImpl::BeforeUnloadType::TAB_CLOSE;
1995 GetMainFrame()->DispatchBeforeUnload(before_unload_type, false);
[email protected]1c3f80bd2014-04-08 23:02:061996}
1997
W. James MacLean2539adb32019-12-13 00:40:441998bool WebContentsImpl::IsInnerWebContentsForGuest() {
1999 return !!browser_plugin_guest_;
2000}
2001
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502002void WebContentsImpl::AttachInnerWebContents(
2003 std::unique_ptr<WebContents> inner_web_contents,
W. James MacLean62883982019-11-12 20:39:002004 RenderFrameHost* render_frame_host,
2005 bool is_full_page) {
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502006 WebContentsImpl* inner_web_contents_impl =
2007 static_cast<WebContentsImpl*>(inner_web_contents.get());
2008 DCHECK(!inner_web_contents_impl->node_.outer_web_contents());
2009 auto* render_frame_host_impl =
2010 static_cast<RenderFrameHostImpl*>(render_frame_host);
Fergal Daly445af932020-06-02 06:37:232011 DCHECK_EQ(&frame_tree_, render_frame_host_impl->frame_tree());
Lucas Furukawa Gadani105de1e812018-05-31 19:38:392012
Yuzu Saijo3f86fb22020-06-11 03:51:102013 // Mark |render_frame_host_impl| as outer delegate frame.
2014 render_frame_host_impl->SetIsOuterDelegateFrame(true);
2015
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502016 RenderFrameHostManager* inner_render_manager =
2017 inner_web_contents_impl->GetRenderManager();
2018 RenderFrameHostImpl* inner_main_frame =
2019 inner_render_manager->current_frame_host();
2020 RenderViewHostImpl* inner_render_view_host =
2021 inner_render_manager->current_host();
2022 auto* outer_render_manager =
2023 render_frame_host_impl->frame_tree_node()->render_manager();
lfg91a79e12016-04-01 23:52:192024
Lucas Furukawa Gadani105de1e812018-05-31 19:38:392025 // When attaching a WebContents as an inner WebContents, we need to replace
2026 // the Webcontents' view with a WebContentsViewChildFrame.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502027 inner_web_contents_impl->view_.reset(new WebContentsViewChildFrame(
2028 inner_web_contents_impl,
2029 GetContentClient()->browser()->GetWebContentsViewDelegate(
2030 inner_web_contents_impl),
2031 &inner_web_contents_impl->render_view_host_delegate_view_));
Lucas Furukawa Gadani105de1e812018-05-31 19:38:392032
lfg91a79e12016-04-01 23:52:192033 // When the WebContents being initialized has an opener, the browser side
2034 // Render{View,Frame}Host must be initialized and the RenderWidgetHostView
2035 // created. This is needed because the usual initialization happens during
2036 // the first navigation, but when attaching a new window we don't navigate
2037 // before attaching. If the browser side is already initialized, the calls
2038 // below will just early return.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502039 inner_render_manager->InitRenderView(inner_render_view_host, nullptr);
2040 inner_main_frame->Init();
2041 if (!inner_render_manager->GetRenderWidgetHostView()) {
2042 inner_web_contents_impl->CreateRenderWidgetHostViewForRenderManager(
2043 inner_render_view_host);
2044 }
lfg91a79e12016-04-01 23:52:192045
Adithya Srinivasane6e7f842019-12-16 18:41:362046 inner_web_contents_impl->RecursivelyUnregisterFrameSinkIds();
2047
lazyboy6ec48b2a2015-06-29 15:18:142048 // Create a link to our outer WebContents.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502049 node_.AttachInnerWebContents(std::move(inner_web_contents),
2050 render_frame_host_impl);
lazyboy6ec48b2a2015-06-29 15:18:142051
lazyboy6ec48b2a2015-06-29 15:18:142052 // Create a proxy in top-level RenderFrameHostManager, pointing to the
2053 // SiteInstance of the outer WebContents. The proxy will be used to send
2054 // postMessage to the inner WebContents.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502055 auto* proxy = inner_render_manager->CreateOuterDelegateProxy(
2056 render_frame_host_impl->GetSiteInstance());
lazyboy6ec48b2a2015-06-29 15:18:142057
Lucas Furukawa Gadani99125822019-01-03 15:41:492058 // When attaching a GuestView as an inner WebContents, there should already be
2059 // a live RenderFrame, which has to be swapped. When attaching a portal, there
2060 // will not be a live RenderFrame before creating the proxy.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502061 if (render_frame_host_impl->IsRenderFrameLive()) {
2062 inner_render_manager->SwapOuterDelegateFrame(render_frame_host_impl, proxy);
Lucas Furukawa Gadani99125822019-01-03 15:41:492063
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502064 inner_web_contents_impl->ReattachToOuterWebContentsFrame();
Lucas Furukawa Gadani99125822019-01-03 15:41:492065 }
ekaramadadd882292016-06-08 15:22:562066
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502067 if (frame_tree_.GetFocusedFrame() ==
2068 render_frame_host_impl->frame_tree_node()) {
2069 inner_web_contents_impl->SetFocusedFrame(
2070 inner_web_contents_impl->frame_tree_.root(),
2071 render_frame_host_impl->GetSiteInstance());
avallee7529b2a2017-04-26 11:37:512072 }
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502073 outer_render_manager->set_attach_complete();
W. James MacLean62883982019-11-12 20:39:002074
2075 // If the inner WebContents is full frame, give it focus.
2076 if (is_full_page) {
2077 // There should only ever be one inner WebContents when |is_full_page| is
2078 // true, and it is the one we just attached.
2079 DCHECK_EQ(1u, node_.GetInnerWebContents().size());
2080 inner_web_contents_impl->SetAsFocusedWebContentsIfNecessary();
2081 }
Chris Hamilton16b5d1d2020-06-04 00:08:122082
Alexander Timin90c20c32020-08-12 15:28:322083 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2084 observer->InnerWebContentsAttached(inner_web_contents_impl,
2085 render_frame_host, is_full_page);
2086 });
lazyboy6ec48b2a2015-06-29 15:18:142087}
2088
Lucas Furukawa Gadani99125822019-01-03 15:41:492089std::unique_ptr<WebContents> WebContentsImpl::DetachFromOuterWebContents() {
Chris Hamilton16b5d1d2020-06-04 00:08:122090 auto* outer_web_contents = GetOuterWebContents();
2091 DCHECK(outer_web_contents);
Yuzu Saijo3f86fb22020-06-11 03:51:102092 GetMainFrame()->ParentOrOuterDelegateFrame()->SetIsOuterDelegateFrame(false);
Chris Hamilton16b5d1d2020-06-04 00:08:122093
Adithya Srinivasane6e7f842019-12-16 18:41:362094 RecursivelyUnregisterFrameSinkIds();
Lucas Gadanid29952582020-06-09 21:24:002095
2096 // Each RenderViewHost has a RenderWidgetHost which can have a
2097 // RenderWidgetHostView, and it needs to be re-created with the appropriate
2098 // platform view. It is important to re-create all child views, not only the
2099 // current one, since the view can be swapped due to a cross-origin
2100 // navigation.
2101 std::set<RenderViewHostImpl*> render_view_hosts;
2102 for (auto& render_view_host : GetFrameTree()->render_view_hosts()) {
2103 if (render_view_host.second->GetWidget() &&
2104 render_view_host.second->GetWidget()->GetView()) {
2105 DCHECK(render_view_host.second->GetWidget()
2106 ->GetView()
2107 ->IsRenderWidgetHostViewChildFrame());
2108 render_view_hosts.insert(render_view_host.second);
Kevin McNee6471a702020-01-27 18:23:072109 }
2110 }
Lucas Gadanid29952582020-06-09 21:24:002111
2112 for (auto* render_view_host : render_view_hosts)
2113 render_view_host->GetWidget()->GetView()->Destroy();
2114
Lucas Furukawa Gadani99125822019-01-03 15:41:492115 GetRenderManager()->DeleteOuterDelegateProxy(
2116 node_.OuterContentsFrameTreeNode()
2117 ->current_frame_host()
2118 ->GetSiteInstance());
2119 view_.reset(CreateWebContentsView(
2120 this, GetContentClient()->browser()->GetWebContentsViewDelegate(this),
2121 &render_view_host_delegate_view_));
danakjfc5184932019-09-12 18:08:322122 view_->CreateView(nullptr);
Lucas Furukawa Gadani99125822019-01-03 15:41:492123 std::unique_ptr<WebContents> web_contents =
2124 node_.DisconnectFromOuterWebContents();
2125 DCHECK_EQ(web_contents.get(), this);
2126 node_.SetFocusedWebContents(this);
Lucas Gadanid29952582020-06-09 21:24:002127
2128 for (auto* render_view_host : render_view_hosts)
2129 CreateRenderWidgetHostViewForRenderManager(render_view_host);
2130
Adithya Srinivasane6e7f842019-12-16 18:41:362131 RecursivelyRegisterFrameSinkIds();
Adithya Srinivasan6f0f67b2019-12-19 01:26:462132 // TODO(adithyas): |browser_plugin_embedder_ax_tree_id| should either not be
2133 // used for portals, or it should get a different name.
2134 GetMainFrame()->set_browser_plugin_embedder_ax_tree_id(ui::AXTreeIDUnknown());
2135 GetMainFrame()->UpdateAXTreeData();
Chris Hamilton16b5d1d2020-06-04 00:08:122136
2137 // Invoke on the *outer* web contents observers for symmetry.
Alexander Timin90c20c32020-08-12 15:28:322138 outer_web_contents->observers_.ForEachObserver(
2139 [&](WebContentsObserver* observer) {
2140 observer->InnerWebContentsDetached(this);
2141 });
Chris Hamilton16b5d1d2020-06-04 00:08:122142
Lucas Furukawa Gadani99125822019-01-03 15:41:492143 return web_contents;
2144}
2145
W. James MacLean2dc75ed42019-03-06 14:31:092146void WebContentsImpl::RecursivelyRegisterFrameSinkIds() {
Adithya Srinivasane6e7f842019-12-16 18:41:362147 for (auto* view : GetRenderWidgetHostViewsInWebContentsTree()) {
2148 auto* rwhvb = static_cast<RenderWidgetHostViewBase*>(view);
2149 if (rwhvb->IsRenderWidgetHostViewChildFrame())
2150 static_cast<RenderWidgetHostViewChildFrame*>(view)->RegisterFrameSinkId();
2151 }
2152}
W. James MacLean2dc75ed42019-03-06 14:31:092153
Adithya Srinivasane6e7f842019-12-16 18:41:362154void WebContentsImpl::RecursivelyUnregisterFrameSinkIds() {
2155 for (auto* view : GetRenderWidgetHostViewsInWebContentsTree()) {
2156 auto* rwhvb = static_cast<RenderWidgetHostViewBase*>(view);
2157 if (rwhvb->IsRenderWidgetHostViewChildFrame()) {
2158 static_cast<RenderWidgetHostViewChildFrame*>(view)
2159 ->UnregisterFrameSinkId();
2160 }
W. James MacLean2dc75ed42019-03-06 14:31:092161 }
2162}
2163
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:142164void WebContentsImpl::ReattachToOuterWebContentsFrame() {
2165 DCHECK(node_.outer_web_contents());
2166 auto* render_manager = GetRenderManager();
2167 auto* parent_frame =
2168 node_.OuterContentsFrameTreeNode()->current_frame_host()->GetParent();
2169 render_manager->SetRWHViewForInnerContents(
2170 render_manager->GetRenderWidgetHostView());
2171
W. James MacLean2dc75ed42019-03-06 14:31:092172 RecursivelyRegisterFrameSinkIds();
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:142173
2174 // Set up the the guest's AX tree to point back at the embedder's AX tree.
2175 GetMainFrame()->set_browser_plugin_embedder_ax_tree_id(
2176 parent_frame->GetAXTreeID());
2177 GetMainFrame()->UpdateAXTreeData();
2178}
2179
Lucas Gadani972985622020-05-28 20:52:512180void WebContentsImpl::DidActivatePortal(
2181 WebContentsImpl* predecessor_web_contents,
2182 base::TimeTicks activation_time) {
2183 DCHECK(predecessor_web_contents);
Kevin McNeef8eb64c2020-04-21 21:36:062184 NotifyInsidePortal(false);
Alexander Timin90c20c32020-08-12 15:28:322185 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2186 observer->DidActivatePortal(predecessor_web_contents, activation_time);
2187 });
Lucas Gadani972985622020-05-28 20:52:512188 GetDelegate()->WebContentsBecamePortal(predecessor_web_contents);
Kevin McNeef8eb64c2020-04-21 21:36:062189}
2190
Adithya Srinivasan11af2c52019-12-16 22:52:552191void WebContentsImpl::NotifyInsidePortal(bool inside_portal) {
Gyuyoung Kim1c029712020-07-22 09:21:062192 ExecutePageBroadcastMethod(base::BindRepeating(
2193 [](bool inside_portal, RenderViewHostImpl* rvh) {
2194 if (auto& broadcast = rvh->GetAssociatedPageBroadcast())
2195 broadcast->SetInsidePortal(inside_portal);
2196 },
2197 inside_portal));
Adithya Srinivasan11af2c52019-12-16 22:52:552198}
2199
dalecurtis6c58ed02016-10-28 23:02:372200void WebContentsImpl::DidChangeVisibleSecurityState() {
Emily Starkc663b0242019-04-26 19:34:452201 if (delegate_)
dalecurtis6c58ed02016-10-28 23:02:372202 delegate_->VisibleSecurityStateChanged(this);
Alexander Timin90c20c32020-08-12 15:28:322203 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2204 observer->DidChangeVisibleSecurityState();
2205 });
dalecurtis6c58ed02016-10-28 23:02:372206}
2207
Rakina Zata Amni4029b6d2020-07-28 02:36:202208const WebPreferences WebContentsImpl::ComputeWebPreferences() {
2209 TRACE_EVENT0("browser", "WebContentsImpl::ComputeWebPreferences");
2210 WebPreferences prefs;
2211
2212 const base::CommandLine& command_line =
2213 *base::CommandLine::ForCurrentProcess();
2214
2215 SetSlowWebPreferences(command_line, &prefs);
2216
2217 prefs.web_security_enabled =
2218 !command_line.HasSwitch(switches::kDisableWebSecurity);
2219
2220 prefs.remote_fonts_enabled =
2221 !command_line.HasSwitch(switches::kDisableRemoteFonts);
2222 prefs.application_cache_enabled =
2223 base::FeatureList::IsEnabled(blink::features::kAppCache);
2224 prefs.local_storage_enabled =
2225 !command_line.HasSwitch(switches::kDisableLocalStorage);
2226 prefs.databases_enabled =
2227 !command_line.HasSwitch(switches::kDisableDatabases);
2228
2229 prefs.webgl1_enabled = !command_line.HasSwitch(switches::kDisable3DAPIs) &&
2230 !command_line.HasSwitch(switches::kDisableWebGL);
2231 prefs.webgl2_enabled = !command_line.HasSwitch(switches::kDisable3DAPIs) &&
2232 !command_line.HasSwitch(switches::kDisableWebGL) &&
2233 !command_line.HasSwitch(switches::kDisableWebGL2);
2234
2235 prefs.pepper_3d_enabled = !command_line.HasSwitch(switches::kDisablePepper3d);
2236
2237 prefs.flash_3d_enabled = !command_line.HasSwitch(switches::kDisableFlash3d);
2238 prefs.flash_stage3d_enabled =
2239 !command_line.HasSwitch(switches::kDisableFlashStage3d);
2240 prefs.flash_stage3d_baseline_enabled =
2241 !command_line.HasSwitch(switches::kDisableFlashStage3d);
2242
2243 prefs.allow_file_access_from_file_urls =
2244 command_line.HasSwitch(switches::kAllowFileAccessFromFiles);
2245
2246 prefs.accelerated_2d_canvas_enabled =
2247 !command_line.HasSwitch(switches::kDisableAccelerated2dCanvas);
2248 prefs.new_canvas_2d_api_enabled =
Rakina Zata Amniea8d0c22020-07-30 17:22:502249 command_line.HasSwitch(switches::kEnableNewCanvas2DAPI) ||
2250 base::FeatureList::IsEnabled(features::kEnableNewCanvas2DAPI);
Rakina Zata Amni4029b6d2020-07-28 02:36:202251 prefs.antialiased_2d_canvas_disabled =
2252 command_line.HasSwitch(switches::kDisable2dCanvasAntialiasing);
2253 prefs.antialiased_clips_2d_canvas_enabled =
2254 !command_line.HasSwitch(switches::kDisable2dCanvasClipAntialiasing);
2255
2256 prefs.disable_ipc_flooding_protection =
2257 command_line.HasSwitch(switches::kDisableIpcFloodingProtection) ||
2258 command_line.HasSwitch(switches::kDisablePushStateThrottle);
2259
2260 prefs.accelerated_video_decode_enabled =
2261 !command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode);
2262
2263 std::string autoplay_policy = media::GetEffectiveAutoplayPolicy(command_line);
2264 if (autoplay_policy == switches::autoplay::kNoUserGestureRequiredPolicy) {
2265 prefs.autoplay_policy = AutoplayPolicy::kNoUserGestureRequired;
2266 } else if (autoplay_policy ==
2267 switches::autoplay::kUserGestureRequiredPolicy) {
2268 prefs.autoplay_policy = AutoplayPolicy::kUserGestureRequired;
2269 } else if (autoplay_policy ==
2270 switches::autoplay::kDocumentUserActivationRequiredPolicy) {
2271 prefs.autoplay_policy = AutoplayPolicy::kDocumentUserActivationRequired;
2272 } else {
2273 NOTREACHED();
2274 }
2275
2276 prefs.dont_send_key_events_to_javascript =
2277 base::FeatureList::IsEnabled(features::kDontSendKeyEventsToJavascript);
2278
2279// TODO(dtapuska): Enable barrel button selection drag support on Android.
2280// crbug.com/758042
2281#if defined(OS_WIN)
2282 prefs.barrel_button_for_drag_enabled =
2283 base::FeatureList::IsEnabled(features::kDirectManipulationStylus);
2284#endif // defined(OS_WIN)
2285
Rakina Zata Amni4029b6d2020-07-28 02:36:202286 prefs.enable_scroll_animator =
2287 command_line.HasSwitch(switches::kEnableSmoothScrolling) ||
2288 (!command_line.HasSwitch(switches::kDisableSmoothScrolling) &&
2289 gfx::Animation::ScrollAnimationsEnabledBySystem());
2290
2291 prefs.prefers_reduced_motion = gfx::Animation::PrefersReducedMotion();
2292
2293 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
2294 GetRenderViewHost()->GetProcess()->GetID())) {
2295 prefs.loads_images_automatically = true;
2296 prefs.javascript_enabled = true;
2297 }
2298
2299 prefs.viewport_enabled = command_line.HasSwitch(switches::kEnableViewport);
2300
2301 if (IsOverridingUserAgent())
2302 prefs.viewport_meta_enabled = false;
2303
2304 prefs.main_frame_resizes_are_orientation_changes =
2305 command_line.HasSwitch(switches::kMainFrameResizesAreOrientationChanges);
2306
2307 prefs.spatial_navigation_enabled =
2308 command_line.HasSwitch(switches::kEnableSpatialNavigation);
2309
2310 if (IsSpatialNavigationDisabled())
2311 prefs.spatial_navigation_enabled = false;
2312
Rakina Zata Amni4029b6d2020-07-28 02:36:202313 prefs.disable_reading_from_canvas =
2314 command_line.HasSwitch(switches::kDisableReadingFromCanvas);
2315
2316 prefs.strict_mixed_content_checking =
2317 command_line.HasSwitch(switches::kEnableStrictMixedContentChecking);
2318
2319 prefs.strict_powerful_feature_restrictions = command_line.HasSwitch(
2320 switches::kEnableStrictPowerfulFeatureRestrictions);
2321
2322 const std::string blockable_mixed_content_group =
2323 base::FieldTrialList::FindFullName("BlockableMixedContent");
2324 prefs.strictly_block_blockable_mixed_content =
2325 blockable_mixed_content_group == "StrictlyBlockBlockableMixedContent";
2326
2327 const std::string plugin_mixed_content_status =
2328 base::FieldTrialList::FindFullName("PluginMixedContentStatus");
2329 prefs.block_mixed_plugin_content =
2330 plugin_mixed_content_status == "BlockableMixedContent";
2331
2332 prefs.v8_cache_options = GetV8CacheOptions();
2333
2334 prefs.user_gesture_required_for_presentation = !command_line.HasSwitch(
2335 switches::kDisableGestureRequirementForPresentation);
2336
2337 if (HideDownloadUI())
2338 prefs.hide_download_ui = true;
2339
2340 // `media_controls_enabled` is `true` by default.
2341 if (HasPersistentVideo())
2342 prefs.media_controls_enabled = false;
2343
2344#if defined(OS_ANDROID)
2345 display::Display display = display::Screen::GetScreen()->GetPrimaryDisplay();
2346 gfx::Size size = display.GetSizeInPixel();
2347 int min_width = size.width() < size.height() ? size.width() : size.height();
2348 prefs.device_scale_adjustment = GetDeviceScaleAdjustment(
2349 static_cast<int>(min_width / display.device_scale_factor()));
2350#endif // OS_ANDROID
2351
2352 GetContentClient()->browser()->OverrideWebkitPrefs(GetRenderViewHost(),
2353 &prefs);
2354 return prefs;
2355}
2356
2357void WebContentsImpl::SetSlowWebPreferences(
2358 const base::CommandLine& command_line,
2359 WebPreferences* prefs) {
2360 if (web_preferences_.get()) {
2361#define SET_FROM_CACHE(prefs, field) prefs->field = web_preferences_->field
2362
2363 SET_FROM_CACHE(prefs, touch_event_feature_detection_enabled);
2364 SET_FROM_CACHE(prefs, available_pointer_types);
2365 SET_FROM_CACHE(prefs, available_hover_types);
2366 SET_FROM_CACHE(prefs, primary_pointer_type);
2367 SET_FROM_CACHE(prefs, primary_hover_type);
2368 SET_FROM_CACHE(prefs, pointer_events_max_touch_points);
2369 SET_FROM_CACHE(prefs, number_of_cpu_cores);
2370
2371#if defined(OS_ANDROID)
2372 SET_FROM_CACHE(prefs, video_fullscreen_orientation_lock_enabled);
2373 SET_FROM_CACHE(prefs, video_rotate_to_fullscreen_enabled);
2374#endif
2375
2376#undef SET_FROM_CACHE
2377 } else {
2378 // Every prefs->field modified below should have a SET_FROM_CACHE entry
2379 // above.
2380
2381 // On Android, Touch event feature detection is enabled by default,
2382 // Otherwise default is disabled.
2383 std::string touch_enabled_default_switch =
2384 switches::kTouchEventFeatureDetectionDisabled;
2385#if defined(OS_ANDROID)
2386 touch_enabled_default_switch = switches::kTouchEventFeatureDetectionEnabled;
2387#endif // defined(OS_ANDROID)
2388 const std::string touch_enabled_switch =
2389 command_line.HasSwitch(switches::kTouchEventFeatureDetection)
2390 ? command_line.GetSwitchValueASCII(
2391 switches::kTouchEventFeatureDetection)
2392 : touch_enabled_default_switch;
2393
2394 prefs->touch_event_feature_detection_enabled =
2395 (touch_enabled_switch == switches::kTouchEventFeatureDetectionAuto)
2396 ? (ui::GetTouchScreensAvailability() ==
2397 ui::TouchScreensAvailability::ENABLED)
2398 : (touch_enabled_switch.empty() ||
2399 touch_enabled_switch ==
2400 switches::kTouchEventFeatureDetectionEnabled);
2401
2402 std::tie(prefs->available_pointer_types, prefs->available_hover_types) =
2403 ui::GetAvailablePointerAndHoverTypes();
2404 prefs->primary_pointer_type =
2405 ui::GetPrimaryPointerType(prefs->available_pointer_types);
2406 prefs->primary_hover_type =
2407 ui::GetPrimaryHoverType(prefs->available_hover_types);
2408
2409 prefs->pointer_events_max_touch_points = ui::MaxTouchPoints();
2410
2411 prefs->number_of_cpu_cores = base::SysInfo::NumberOfProcessors();
2412
2413#if defined(OS_ANDROID)
2414 const bool device_is_phone =
2415 ui::GetDeviceFormFactor() == ui::DEVICE_FORM_FACTOR_PHONE;
2416 prefs->video_fullscreen_orientation_lock_enabled = device_is_phone;
2417 prefs->video_rotate_to_fullscreen_enabled = device_is_phone;
2418#endif
2419 }
2420}
2421
2422void WebContentsImpl::OnWebPreferencesChanged() {
2423 // This is defensive code to avoid infinite loops due to code run inside
2424 // SetWebPreferences() accidentally updating more preferences and thus
2425 // calling back into this code. See crbug.com/398751 for one past example.
2426 if (updating_web_preferences_)
2427 return;
2428 updating_web_preferences_ = true;
2429 SetWebPreferences(ComputeWebPreferences());
2430#if defined(OS_ANDROID)
2431 for (FrameTreeNode* node : frame_tree_.Nodes()) {
2432 RenderFrameHostImpl* rfh = node->current_frame_host();
2433 if (rfh->is_local_root()) {
2434 if (auto* rwh = rfh->GetRenderWidgetHost())
2435 rwh->SetForceEnableZoom(web_preferences_->force_enable_zoom);
2436 }
2437 }
2438#endif
2439 updating_web_preferences_ = false;
2440}
2441
Ahmed Fakhryd70bf37b2018-04-04 17:07:242442void WebContentsImpl::NotifyPreferencesChanged() {
Rakina Zata Amni347b70902020-07-22 10:49:042443 // Recompute the WebPreferences based on the current state of the WebContents,
Rakina Zata Amni4029b6d2020-07-28 02:36:202444 // etc. Note that OnWebPreferencesChanged will also call SetWebPreferences and
2445 // send the updated WebPreferences to all RenderViews for this WebContents.
2446 OnWebPreferencesChanged();
Ahmed Fakhryd70bf37b2018-04-04 17:07:242447}
2448
Bruce Long1e3e1f542019-10-16 17:56:282449void WebContentsImpl::SyncRendererPrefs() {
Peter Marshall2dc74e92020-07-29 20:02:302450 blink::mojom::RendererPreferences renderer_preferences = GetRendererPrefs();
Bruce Long1e3e1f542019-10-16 17:56:282451 RenderViewHostImpl::GetPlatformSpecificPrefs(&renderer_preferences);
2452 SendPageMessage(
2453 new PageMsg_SetRendererPrefs(MSG_ROUTING_NONE, renderer_preferences));
2454}
2455
Alexander Timin1cc31f42020-05-12 16:26:012456void WebContentsImpl::OnCookiesAccessed(NavigationHandle* navigation,
2457 const CookieAccessDetails& details) {
Alexander Timin90c20c32020-08-12 15:28:322458 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2459 observer->OnCookiesAccessed(navigation, details);
2460 });
Alexander Timin1cc31f42020-05-12 16:26:012461}
2462
2463void WebContentsImpl::OnCookiesAccessed(RenderFrameHostImpl* rfh,
2464 const CookieAccessDetails& details) {
Alexander Timin90c20c32020-08-12 15:28:322465 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2466 observer->OnCookiesAccessed(rfh, details);
2467 });
Josh Karlindaba39322019-07-17 23:24:332468}
2469
[email protected]b172aee2012-04-10 17:05:262470void WebContentsImpl::Stop() {
dcheng57e39e22016-01-21 00:25:382471 for (FrameTreeNode* node : frame_tree_.Nodes())
2472 node->StopLoading();
Alexander Timin90c20c32020-08-12 15:28:322473 observers_.ForEachObserver(
2474 [&](WebContentsObserver* observer) { observer->NavigationStopped(); });
[email protected]0bfbf882011-12-22 18:19:272475}
2476
Francois Doray47f759d2018-06-11 18:13:512477void WebContentsImpl::SetPageFrozen(bool frozen) {
2478 // A visible page is never frozen.
2479 DCHECK_NE(Visibility::VISIBLE, GetVisibility());
2480
Yuzu Saijo4fa1e9a2020-05-20 02:53:262481 for (auto& entry : frame_tree_.render_view_hosts()) {
2482 entry.second->SetIsFrozen(frozen);
2483 }
Fadi Meawada6573e02018-03-10 00:52:112484}
2485
erikchen6c7df7f7a2018-05-03 18:13:592486std::unique_ptr<WebContents> WebContentsImpl::Clone() {
[email protected]14392a52012-05-02 20:28:442487 // We use our current SiteInstance since the cloned entry will use it anyway.
alexmose201c7cd2015-06-10 17:14:212488 // We pass our own opener so that the cloned page can access it if it was set
[email protected]ed245db2012-12-18 08:00:452489 // before.
[email protected]54944cde2012-12-09 09:24:592490 CreateParams create_params(GetBrowserContext(), GetSiteInstance());
Ian Clelland5cbaaf82017-11-27 22:00:032491 FrameTreeNode* opener = frame_tree_.root()->opener();
2492 RenderFrameHostImpl* opener_rfh = nullptr;
2493 if (opener)
2494 opener_rfh = opener->current_frame_host();
erikchen6c7df7f7a2018-05-03 18:13:592495 std::unique_ptr<WebContentsImpl> tc =
erikchen50735fd2018-05-05 15:08:332496 CreateWithOpener(create_params, opener_rfh);
Lucas Furukawa Gadani5553a152019-01-08 18:55:572497 tc->GetController().CopyStateFrom(&controller_, true);
Alexander Timin90c20c32020-08-12 15:28:322498 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2499 observer->DidCloneToNewWebContents(this, tc.get());
2500 });
[email protected]0bfbf882011-12-22 18:19:272501 return tc;
2502}
2503
[email protected]14392a52012-05-02 20:28:442504void WebContentsImpl::Observe(int type,
[email protected]8ff00d72012-10-23 19:12:212505 const NotificationSource& source,
2506 const NotificationDetails& details) {
[email protected]14392a52012-05-02 20:28:442507 switch (type) {
[email protected]8ff00d72012-10-23 19:12:212508 case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: {
2509 RenderWidgetHost* host = Source<RenderWidgetHost>(source).ptr();
[email protected]0b431992014-06-24 00:08:032510 RenderWidgetHostView* view = host->GetView();
2511 if (view == GetFullscreenRenderWidgetHostView()) {
2512 // We cannot just call view_->RestoreFocus() here. On some platforms,
2513 // attempting to focus the currently-invisible WebContentsView will be
2514 // flat-out ignored. Therefore, this boolean is used to track whether
2515 // we will request focus after the fullscreen widget has been
2516 // destroyed.
2517 fullscreen_widget_had_focus_at_shutdown_ = (view && view->HasFocus());
2518 } else {
alexmosc2a8cec2016-05-23 22:19:532519 for (auto i = pending_widget_views_.begin();
[email protected]0b431992014-06-24 00:08:032520 i != pending_widget_views_.end(); ++i) {
2521 if (host->GetView() == i->second) {
2522 pending_widget_views_.erase(i);
2523 break;
2524 }
[email protected]bafe6cd2012-05-23 23:09:502525 }
2526 }
2527 break;
2528 }
[email protected]14392a52012-05-02 20:28:442529 default:
2530 NOTREACHED();
2531 }
2532}
2533
[email protected]ec6c05f2013-10-23 18:41:572534WebContents* WebContentsImpl::GetWebContents() {
2535 return this;
2536}
2537
[email protected]54944cde2012-12-09 09:24:592538void WebContentsImpl::Init(const WebContents::CreateParams& params) {
[email protected]fa944cb82013-11-15 17:51:212539 // This is set before initializing the render manager since
[email protected]b0936d22013-11-28 06:47:362540 // RenderFrameHostManager::Init calls back into us via its delegate to ask if
[email protected]fa944cb82013-11-15 17:51:212541 // it should be hidden.
Francois Doraye6161152018-03-27 22:05:372542 visibility_ =
2543 params.initially_hidden ? Visibility::HIDDEN : Visibility::VISIBLE;
[email protected]d6fa88f2013-10-18 16:00:432544
Sebastien Marchand28cf23182018-06-20 02:39:352545 if (!params.last_active_time.is_null())
2546 last_active_time_ = params.last_active_time;
2547
dcheng3ce04b62015-10-26 23:30:552548 scoped_refptr<SiteInstance> site_instance = params.site_instance;
2549 if (!site_instance)
2550 site_instance = SiteInstance::Create(params.browser_context);
Lukasz Anforowicz3caa8372018-06-05 17:22:072551 if (params.desired_renderer_state == CreateParams::kNoRendererProcess) {
2552 static_cast<SiteInstanceImpl*>(site_instance.get())
2553 ->PreventAssociationWithSpareProcess();
2554 }
dcheng3ce04b62015-10-26 23:30:552555
Fergal Dalycb0c1fdf2020-03-16 07:13:492556 GetRenderManager()->InitRoot(site_instance.get(),
2557 params.renderer_initiated_creation);
lukasza464d8692016-02-22 19:26:322558
lukasza5140a412016-09-15 21:12:302559 // blink::FrameTree::setName always keeps |unique_name| empty in case of a
2560 // main frame - let's do the same thing here.
2561 std::string unique_name;
lukasza464d8692016-02-22 19:26:322562 frame_tree_.root()->SetFrameName(params.main_frame_name, unique_name);
[email protected]d1198fd2012-08-13 22:50:192563
[email protected]fc2b46b2014-05-03 16:33:452564 WebContentsViewDelegate* delegate =
2565 GetContentClient()->browser()->GetWebContentsViewDelegate(this);
2566
W. James MacLean2539adb32019-12-13 00:40:442567 if (browser_plugin_guest_) {
sky52a39e342016-12-17 17:23:222568 view_.reset(new WebContentsViewChildFrame(
2569 this, delegate, &render_view_host_delegate_view_));
2570 } else {
2571 view_.reset(CreateWebContentsView(this, delegate,
2572 &render_view_host_delegate_view_));
[email protected]d1198fd2012-08-13 22:50:192573 }
[email protected]fc2b46b2014-05-03 16:33:452574 CHECK(render_view_host_delegate_view_);
[email protected]d1198fd2012-08-13 22:50:192575 CHECK(view_.get());
2576
danakjfc5184932019-09-12 18:08:322577 view_->CreateView(params.context);
[email protected]d1198fd2012-08-13 22:50:192578
brettw4b461082016-11-19 18:55:162579#if BUILDFLAG(ENABLE_PLUGINS)
Yuzu Saijoa11069a2020-04-22 10:56:552580 plugin_content_origin_allowlist_.reset(
2581 new PluginContentOriginAllowlist(this));
tommyclieb25b2a2014-11-03 19:45:092582#endif
2583
[email protected]d1198fd2012-08-13 22:50:192584 registrar_.Add(this,
[email protected]8ff00d72012-10-23 19:12:212585 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
2586 NotificationService::AllBrowserContextsAndSources());
[email protected]f28ef9a32014-05-12 16:36:102587
leon.hane4db177a2017-02-07 14:19:162588 screen_orientation_provider_.reset(new ScreenOrientationProvider(this));
[email protected]01f83f92014-06-17 14:41:542589
mfomitchev2b8b066a2016-01-28 19:23:152590#if defined(OS_ANDROID)
Oksana Zhuravlova0b634332019-10-28 23:04:222591 DateTimeChooserAndroid::CreateForWebContents(this);
[email protected]583418cc2013-01-17 14:01:102592#endif
fsamuel7310a4262014-12-05 05:06:442593
2594 // BrowserPluginGuest::Init needs to be called after this WebContents has
W. James MacLean6e78da342019-12-13 15:13:232595 // a RenderWidgetHostViewChildFrame. That is, |view_->CreateView| above.
fsamuel7310a4262014-12-05 05:06:442596 if (browser_plugin_guest_)
2597 browser_plugin_guest_->Init();
nickf9acfbe2014-12-23 19:12:372598
2599 for (size_t i = 0; i < g_created_callbacks.Get().size(); i++)
2600 g_created_callbacks.Get().at(i).Run(this);
naskob21fe4872015-02-24 14:15:562601
2602 // If the WebContents creation was renderer-initiated, it means that the
2603 // corresponding RenderView and main RenderFrame have already been created.
2604 // Ensure observers are notified about this.
2605 if (params.renderer_initiated_creation) {
Fergal Dalybb2d6592020-06-02 05:02:332606 GetRenderViewHost()->GetWidget()->set_renderer_initialized(true);
Alex Moshchuk27caae82017-09-11 23:11:182607 GetRenderViewHost()->DispatchRenderViewCreated();
naskob21fe4872015-02-24 14:15:562608 GetRenderManager()->current_frame_host()->SetRenderFrameCreated(true);
2609 }
naskof5940b9f2015-03-02 23:04:052610
lof84501da082016-05-23 21:22:542611 // Create the renderer process in advance if requested.
Lukasz Anforowicz3caa8372018-06-05 17:22:072612 if (params.desired_renderer_state ==
2613 CreateParams::kInitializeAndWarmupRendererProcess) {
lof84501da082016-05-23 21:22:542614 if (!GetRenderManager()->current_frame_host()->IsRenderFrameLive()) {
2615 GetRenderManager()->InitRenderView(GetRenderViewHost(), nullptr);
2616 }
2617 }
2618
naskof5940b9f2015-03-02 23:04:052619 // Ensure that observers are notified of the creation of this WebContents's
2620 // main RenderFrameHost. It must be done here for main frames, since the
2621 // NotifySwappedFromRenderManager expects view_ to already be created and that
2622 // happens after RenderFrameHostManager::Init.
2623 NotifySwappedFromRenderManager(
2624 nullptr, GetRenderManager()->current_frame_host(), true);
Albert J. Wonge76bf0b82019-09-27 07:47:062625
2626 // For WebContents that are never shown, do critical initialization here which
2627 // would normally only happen when the WebContents is shown.
2628 if (params.is_never_visible) {
2629 // This has just been created so there can only be one frame. Thus it is
2630 // safe to initialize the root.
2631 GetMainFrame()->Init();
2632 }
[email protected]d1198fd2012-08-13 22:50:192633}
2634
[email protected]7fff43e2013-05-21 20:21:102635void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl* web_contents) {
2636 RemoveDestructionObserver(web_contents);
2637
[email protected]ceee8cd2013-03-08 04:59:512638 // Clear a pending contents that has been closed before being shown.
alexmosc2a8cec2016-05-23 22:19:532639 for (auto iter = pending_contents_.begin(); iter != pending_contents_.end();
[email protected]ceee8cd2013-03-08 04:59:512640 ++iter) {
Joel Hockey8c2011b22020-04-30 05:07:192641 if (iter->second.contents.get() != web_contents)
[email protected]ceee8cd2013-03-08 04:59:512642 continue;
erikchenbee5c9622018-04-27 19:30:252643
2644 // Someone else has deleted the WebContents. That should never happen!
2645 // TODO(erikchen): Fix semantics here. https://crbug.com/832879.
Joel Hockey8c2011b22020-04-30 05:07:192646 iter->second.contents.release();
[email protected]ceee8cd2013-03-08 04:59:512647 pending_contents_.erase(iter);
[email protected]ceee8cd2013-03-08 04:59:512648 return;
2649 }
2650 NOTREACHED();
[email protected]14392a52012-05-02 20:28:442651}
2652
[email protected]7fff43e2013-05-21 20:21:102653void WebContentsImpl::AddDestructionObserver(WebContentsImpl* web_contents) {
Jan Wilken Dörrie73c901e2019-06-12 09:02:322654 if (!base::Contains(destruction_observers_, web_contents)) {
[email protected]7fff43e2013-05-21 20:21:102655 destruction_observers_[web_contents] =
Jeremy Roman04f27c372017-10-27 15:20:552656 std::make_unique<DestructionObserver>(this, web_contents);
[email protected]7fff43e2013-05-21 20:21:102657 }
2658}
2659
2660void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl* web_contents) {
avia8cf81982016-08-12 20:28:462661 destruction_observers_.erase(web_contents);
[email protected]7fff43e2013-05-21 20:21:102662}
2663
[email protected]b172aee2012-04-10 17:05:262664void WebContentsImpl::AddObserver(WebContentsObserver* observer) {
[email protected]be1f56ab2011-12-22 06:55:312665 observers_.AddObserver(observer);
2666}
2667
[email protected]b172aee2012-04-10 17:05:262668void WebContentsImpl::RemoveObserver(WebContentsObserver* observer) {
[email protected]be1f56ab2011-12-22 06:55:312669 observers_.RemoveObserver(observer);
2670}
2671
[email protected]948481d2014-06-11 18:32:222672std::set<RenderWidgetHostView*>
2673WebContentsImpl::GetRenderWidgetHostViewsInTree() {
2674 std::set<RenderWidgetHostView*> set;
Carlos IL07f282f2020-05-15 22:58:292675 for (RenderFrameHost* rfh : GetAllFrames()) {
2676 if (RenderWidgetHostView* rwhv = static_cast<RenderFrameHostImpl*>(rfh)
2677 ->frame_tree_node()
2678 ->render_manager()
2679 ->GetRenderWidgetHostView()) {
lfgf949e0e2017-05-10 22:18:112680 set.insert(rwhv);
dchengafb53e22016-02-04 08:11:082681 }
[email protected]948481d2014-06-11 18:32:222682 }
[email protected]de3c5d82014-05-28 22:12:592683 return set;
2684}
2685
Adithya Srinivasane6e7f842019-12-16 18:41:362686std::set<RenderWidgetHostView*>
2687WebContentsImpl::GetRenderWidgetHostViewsInWebContentsTree() {
2688 std::set<RenderWidgetHostView*> result;
2689 GetRenderWidgetHostViewsInWebContentsTree(result);
2690 return result;
2691}
2692
2693void WebContentsImpl::GetRenderWidgetHostViewsInWebContentsTree(
2694 std::set<RenderWidgetHostView*>& result) {
2695 std::set<RenderWidgetHostView*> views = GetRenderWidgetHostViewsInTree();
2696 result.insert(views.begin(), views.end());
2697 for (auto* inner_web_contents : GetInnerWebContents()) {
2698 static_cast<WebContentsImpl*>(inner_web_contents)
2699 ->GetRenderWidgetHostViewsInWebContentsTree(result);
2700 }
2701}
2702
[email protected]b172aee2012-04-10 17:05:262703void WebContentsImpl::Activate() {
[email protected]d5f942ba2008-09-26 19:30:342704 if (delegate_)
2705 delegate_->ActivateContents(this);
2706}
2707
avi3e4b8512015-11-11 01:55:492708void WebContentsImpl::LostCapture(RenderWidgetHostImpl* render_widget_host) {
2709 if (!RenderViewHostImpl::From(render_widget_host))
2710 return;
2711
[email protected]63954792011-07-11 04:17:482712 if (delegate_)
2713 delegate_->LostCapture();
2714}
2715
Yue Ru Sun979c4b162019-11-06 16:11:042716ukm::SourceId
2717WebContentsImpl::GetUkmSourceIdForLastCommittedSourceIncludingSameDocument()
2718 const {
2719 return last_committed_source_id_including_same_document_;
2720}
2721
Ahmed Fakhryfaa32d22018-10-05 15:56:162722void WebContentsImpl::SetTopControlsShownRatio(
2723 RenderWidgetHostImpl* render_widget_host,
2724 float ratio) {
2725 if (!delegate_)
2726 return;
2727
2728 RenderFrameHostImpl* rfh = GetMainFrame();
2729 if (!rfh || render_widget_host != rfh->GetRenderWidgetHost())
2730 return;
2731
2732 delegate_->SetTopControlsShownRatio(this, ratio);
Ahmed Fakhry58e6ef542018-09-04 18:05:382733}
2734
Ahmed Fakhry58e6ef542018-09-04 18:05:382735void WebContentsImpl::SetTopControlsGestureScrollInProgress(bool in_progress) {
2736 if (delegate_)
2737 delegate_->SetTopControlsGestureScrollInProgress(in_progress);
2738}
2739
lazyboy63f5b312015-11-23 20:19:522740void WebContentsImpl::RenderWidgetCreated(
2741 RenderWidgetHostImpl* render_widget_host) {
2742 created_widgets_.insert(render_widget_host);
2743}
2744
[email protected]b24b68a2012-09-24 21:57:262745void WebContentsImpl::RenderWidgetDeleted(
2746 RenderWidgetHostImpl* render_widget_host) {
lazyboy63f5b312015-11-23 20:19:522747 // Note that |is_being_destroyed_| can be true at this point as
2748 // ~WebContentsImpl() calls RFHM::ClearRFHsPendingShutdown(), which might lead
2749 // us here.
2750 created_widgets_.erase(render_widget_host);
[email protected]b24b68a2012-09-24 21:57:262751
lazyboy63f5b312015-11-23 20:19:522752 if (is_being_destroyed_)
2753 return;
[email protected]44470a22013-01-24 01:21:542754
2755 if (render_widget_host &&
alexmosc9e76ec2016-05-16 22:59:372756 render_widget_host->GetRoutingID() == fullscreen_widget_routing_id_ &&
2757 render_widget_host->GetProcess()->GetID() ==
2758 fullscreen_widget_process_id_) {
[email protected]4aebbca2013-09-17 22:26:492759 if (delegate_ && delegate_->EmbedsFullscreenWidget())
mlamouri7a78d6fd2015-01-17 13:23:532760 delegate_->ExitFullscreenModeForTab(this);
Alexander Timin90c20c32020-08-12 15:28:322761 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2762 observer->DidDestroyFullscreenWidget();
2763 });
alexmosc9e76ec2016-05-16 22:59:372764 fullscreen_widget_process_id_ = ChildProcessHost::kInvalidUniqueID;
[email protected]44470a22013-01-24 01:21:542765 fullscreen_widget_routing_id_ = MSG_ROUTING_NONE;
[email protected]0b431992014-06-24 00:08:032766 if (fullscreen_widget_had_focus_at_shutdown_)
2767 view_->RestoreFocus();
[email protected]44470a22013-01-24 01:21:542768 }
lfgbee1e0a2016-06-08 21:24:212769
lfg7d4caad2017-03-22 09:01:452770 if (render_widget_host == mouse_lock_widget_)
lfgff8dfc8d2016-10-21 17:42:322771 LostMouseLock(mouse_lock_widget_);
Joe Downing192998b22018-03-22 15:51:362772
Joe Downingc1a57efe2018-05-09 18:23:542773 CancelKeyboardLock(render_widget_host);
[email protected]b24b68a2012-09-24 21:57:262774}
2775
miu9e14e492014-10-25 02:39:042776void WebContentsImpl::RenderWidgetGotFocus(
2777 RenderWidgetHostImpl* render_widget_host) {
calamity7fe55ce2015-04-10 03:59:372778 // Notify the observers if an embedded fullscreen widget was focused.
2779 if (delegate_ && render_widget_host && delegate_->EmbedsFullscreenWidget() &&
2780 render_widget_host->GetView() == GetFullscreenRenderWidgetHostView()) {
Michael Thiessen896405db2017-07-20 17:52:322781 NotifyWebContentsFocused(render_widget_host);
calamity7fe55ce2015-04-10 03:59:372782 }
miu9e14e492014-10-25 02:39:042783}
2784
zijiehe3bee08e22017-05-17 04:14:462785void WebContentsImpl::RenderWidgetLostFocus(
2786 RenderWidgetHostImpl* render_widget_host) {
Michael Thiessen896405db2017-07-20 17:52:322787 // Notify the observers if an embedded fullscreen widget lost focus.
2788 if (delegate_ && render_widget_host && delegate_->EmbedsFullscreenWidget() &&
2789 render_widget_host->GetView() == GetFullscreenRenderWidgetHostView()) {
2790 NotifyWebContentsLostFocus(render_widget_host);
2791 }
zijiehe3bee08e22017-05-17 04:14:462792}
2793
estaded0a0c992015-01-21 14:12:062794void WebContentsImpl::RenderWidgetWasResized(
rouslan2f5993f2015-01-29 00:18:312795 RenderWidgetHostImpl* render_widget_host,
2796 bool width_changed) {
creisc014b402015-04-23 16:41:452797 RenderFrameHostImpl* rfh = GetMainFrame();
estadece344ec2015-01-23 00:12:292798 if (!rfh || render_widget_host != rfh->GetRenderWidgetHost())
estaded0a0c992015-01-21 14:12:062799 return;
estaded0a0c992015-01-21 14:12:062800
Alexander Timin90c20c32020-08-12 15:28:322801 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2802 observer->MainFrameWasResized(width_changed);
2803 });
estaded0a0c992015-01-21 14:12:062804}
2805
skyf65d9bb2017-03-24 02:26:392806KeyboardEventProcessingResult WebContentsImpl::PreHandleKeyboardEvent(
2807 const NativeWebKeyboardEvent& event) {
W. James MacLeane1187272019-11-12 03:42:482808 auto* outermost_contents = GetOutermostWebContents();
2809 // TODO(wjmaclean): Generalize this to forward all key events to the outermost
2810 // delegate's handler.
Avi Drissman97aef042020-06-30 21:04:482811 if (outermost_contents != this && IsFullscreen() &&
W. James MacLeane1187272019-11-12 03:42:482812 event.windows_key_code == ui::VKEY_ESCAPE) {
2813 // When an inner WebContents has focus and is fullscreen, redirect <esc>
2814 // key events to the outermost WebContents so it can be handled by that
2815 // WebContents' delegate.
2816 if (outermost_contents->PreHandleKeyboardEvent(event) ==
2817 KeyboardEventProcessingResult::HANDLED) {
2818 return KeyboardEventProcessingResult::HANDLED;
2819 }
2820 }
skyf65d9bb2017-03-24 02:26:392821 return delegate_ ? delegate_->PreHandleKeyboardEvent(this, event)
2822 : KeyboardEventProcessingResult::NOT_HANDLED;
[email protected]63954792011-07-11 04:17:482823}
2824
Dave Tapuska344399e2019-09-09 15:18:262825bool WebContentsImpl::HandleMouseEvent(const blink::WebMouseEvent& event) {
2826 // Handle mouse button back/forward in the browser process after the render
2827 // process is done with the event. This ensures all renderer-initiated history
2828 // navigations can be treated consistently.
2829 if (event.GetType() == blink::WebInputEvent::Type::kMouseUp) {
2830 WebContentsImpl* outermost = GetOutermostWebContents();
2831 if (event.button == blink::WebPointerProperties::Button::kBack &&
2832 outermost->controller_.CanGoBack()) {
2833 outermost->controller_.GoBack();
2834 return true;
2835 } else if (event.button == blink::WebPointerProperties::Button::kForward &&
2836 outermost->controller_.CanGoForward()) {
2837 outermost->controller_.GoForward();
2838 return true;
2839 }
2840 }
2841 return false;
2842}
2843
Scott Violetd5caa872018-10-16 22:00:512844bool WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
[email protected]0b094002014-08-20 18:28:102845 if (browser_plugin_embedder_ &&
2846 browser_plugin_embedder_->HandleKeyboardEvent(event)) {
Scott Violetd5caa872018-10-16 22:00:512847 return true;
[email protected]0b094002014-08-20 18:28:102848 }
Scott Violetd5caa872018-10-16 22:00:512849 return delegate_ && delegate_->HandleKeyboardEvent(this, event);
[email protected]63954792011-07-11 04:17:482850}
2851
[email protected]d92026ef2014-03-03 21:04:132852bool WebContentsImpl::HandleWheelEvent(
[email protected]180ef242013-11-07 06:50:462853 const blink::WebMouseWheelEvent& event) {
Avi Drissman7c57be72020-07-29 20:09:462854#if !defined(OS_MAC)
lanweia93644f2015-01-21 22:00:332855 // On platforms other than Mac, control+mousewheel may change zoom. On Mac,
2856 // this isn't done for two reasons:
[email protected]bccc4472013-04-18 16:37:192857 // -the OS already has a gesture to do this through pinch-zoom
2858 // -if a user starts an inertial scroll, let's go, and presses control
2859 // (i.e. control+tab) then the OS's buffered scroll events will come in
2860 // with control key set which isn't what the user wants
Blink Reformat1c4d759e2017-04-09 16:34:542861 if (delegate_ && event.wheel_ticks_y &&
Ehsan Karamad0f83cb112018-09-06 22:07:362862 event.event_action == blink::WebMouseWheelEvent::EventAction::kPageZoom) {
w.shackleton49bcd392016-01-06 17:38:222863 // Count only integer cumulative scrolls as zoom events; this handles
2864 // smooth scroll and regular scroll device behavior.
Blink Reformat1c4d759e2017-04-09 16:34:542865 zoom_scroll_remainder_ += event.wheel_ticks_y;
w.shackleton49bcd392016-01-06 17:38:222866 int whole_zoom_scroll_remainder_ = std::lround(zoom_scroll_remainder_);
2867 zoom_scroll_remainder_ -= whole_zoom_scroll_remainder_;
2868 if (whole_zoom_scroll_remainder_ != 0) {
2869 delegate_->ContentsZoomChange(whole_zoom_scroll_remainder_ > 0);
2870 }
[email protected]fb3f066e2013-02-12 19:12:522871 return true;
2872 }
[email protected]bccc4472013-04-18 16:37:192873#endif
[email protected]fb3f066e2013-02-12 19:12:522874 return false;
2875}
2876
[email protected]04bce562014-01-30 05:34:542877bool WebContentsImpl::PreHandleGestureEvent(
2878 const blink::WebGestureEvent& event) {
[email protected]28042d32014-02-03 14:10:032879 return delegate_ && delegate_->PreHandleGestureEvent(this, event);
[email protected]04bce562014-01-30 05:34:542880}
2881
kenrb2a565f82015-09-02 20:24:592882RenderWidgetHostInputEventRouter* WebContentsImpl::GetInputEventRouter() {
wjmacleane31234f2015-12-14 17:20:452883 if (!is_being_destroyed_ && GetOuterWebContents())
2884 return GetOuterWebContents()->GetInputEventRouter();
2885
2886 if (!rwh_input_event_router_.get() && !is_being_destroyed_)
kenrb2a565f82015-09-02 20:24:592887 rwh_input_event_router_.reset(new RenderWidgetHostInputEventRouter);
2888 return rwh_input_event_router_.get();
2889}
2890
alexmos3fcd0ca2015-10-23 18:18:332891void WebContentsImpl::ReplicatePageFocus(bool is_focused) {
2892 // Focus loss may occur while this WebContents is being destroyed. Don't
2893 // send the message in this case, as the main frame's RenderFrameHost and
2894 // other state has already been cleared.
2895 if (is_being_destroyed_)
2896 return;
2897
2898 frame_tree_.ReplicatePageFocus(is_focused);
2899}
2900
alexmosc4cbacb2015-11-21 01:29:222901RenderWidgetHostImpl* WebContentsImpl::GetFocusedRenderWidgetHost(
2902 RenderWidgetHostImpl* receiving_widget) {
alexmosc4cbacb2015-11-21 01:29:222903 // Events for widgets other than the main frame (e.g., popup menus) should be
2904 // forwarded directly to the widget they arrived on.
2905 if (receiving_widget != GetMainFrame()->GetRenderWidgetHost())
2906 return receiving_widget;
alexmosc4d183e2015-11-06 00:46:522907
paulmeyerfeafc2d2017-04-25 21:46:402908 // If the focused WebContents is a guest WebContents, then get the focused
2909 // frame in the embedder WebContents instead.
W. James MacLean13d834d2019-12-04 16:06:452910 FrameTreeNode* focused_frame =
2911 GetFocusedWebContents()->frame_tree_.GetFocusedFrame();
lfg1453e412017-04-11 00:48:502912
alexmosc4d183e2015-11-06 00:46:522913 if (!focused_frame)
alexmosc4cbacb2015-11-21 01:29:222914 return receiving_widget;
alexmosc4d183e2015-11-06 00:46:522915
alexmos732ca3a2015-12-08 02:01:022916 // The view may be null if a subframe's renderer process has crashed while
2917 // the subframe has focus. Drop the event in that case. Do not give
2918 // it to the main frame, so that the user doesn't unexpectedly type into the
2919 // wrong frame if a focused subframe renderer crashes while they type.
2920 RenderWidgetHostView* view = focused_frame->current_frame_host()->GetView();
2921 if (!view)
2922 return nullptr;
2923
2924 return RenderWidgetHostImpl::From(view->GetRenderWidgetHost());
alexmosc4d183e2015-11-06 00:46:522925}
2926
avallee9993fca2016-11-17 06:16:502927RenderWidgetHostImpl* WebContentsImpl::GetRenderWidgetHostWithPageFocus() {
lfg1453e412017-04-11 00:48:502928 WebContentsImpl* focused_web_contents = GetFocusedWebContents();
2929
lfg1453e412017-04-11 00:48:502930 return focused_web_contents->GetMainFrame()->GetRenderWidgetHost();
avallee9993fca2016-11-17 06:16:502931}
2932
Avi Drissmand1d25652020-03-06 21:28:582933bool WebContentsImpl::CanEnterFullscreenMode() {
Avi Drissman33972942020-06-19 14:16:012934 // It's possible that this WebContents was spawned while blocking UI was on
2935 // the screen, or that it was downstream from a WebContents when UI was
2936 // blocked. Therefore, disqualify it from fullscreen if it or any upstream
2937 // WebContents has an active blocker.
2938 auto openers = GetAllOpeningWebContents(this);
2939 return std::all_of(openers.begin(), openers.end(), [](auto* opener) {
2940 return opener->fullscreen_blocker_count_ == 0;
2941 });
Avi Drissmand1d25652020-03-06 21:28:582942}
2943
Dave Tapuska3ed44192018-05-01 18:53:302944void WebContentsImpl::EnterFullscreenMode(
Mike Wasserman4ca09792020-05-29 17:44:432945 RenderFrameHost* requesting_frame,
Dave Tapuskaa4189512019-10-15 20:27:342946 const blink::mojom::FullscreenOptions& options) {
Avi Drissmand1d25652020-03-06 21:28:582947 DCHECK(CanEnterFullscreenMode());
2948
mlamouri7a78d6fd2015-01-17 13:23:532949 // This method is being called to enter renderer-initiated fullscreen mode.
2950 // Make sure any existing fullscreen widget is shut down first.
[email protected]4aebbca2013-09-17 22:26:492951 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
avi85a4cef2015-12-18 20:13:372952 if (widget_view) {
2953 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())
2954 ->ShutdownAndDestroyWidget(true);
2955 }
[email protected]4aebbca2013-09-17 22:26:492956
Joe Downing13dd76b2018-04-09 18:32:152957 if (delegate_) {
Mike Wasserman4ca09792020-05-29 17:44:432958 delegate_->EnterFullscreenModeForTab(requesting_frame, options);
mlamouri7a78d6fd2015-01-17 13:23:532959
Joe Downing13dd76b2018-04-09 18:32:152960 if (keyboard_lock_widget_)
2961 delegate_->RequestKeyboardLock(this, esc_key_locked_);
2962 }
2963
Alexander Timin90c20c32020-08-12 15:28:322964 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2965 observer->DidToggleFullscreenModeForTab(IsFullscreen(), false);
2966 });
Avi Drissman33972942020-06-19 14:16:012967 FullscreenContentsSet(GetBrowserContext())->insert(this);
mlamouri7a78d6fd2015-01-17 13:23:532968}
2969
bokanece34a82016-01-28 19:49:462970void WebContentsImpl::ExitFullscreenMode(bool will_cause_resize) {
mlamouri7a78d6fd2015-01-17 13:23:532971 // This method is being called to leave renderer-initiated fullscreen mode.
2972 // Make sure any existing fullscreen widget is shut down first.
2973 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
avi85a4cef2015-12-18 20:13:372974 if (widget_view) {
2975 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())
2976 ->ShutdownAndDestroyWidget(true);
2977 }
mlamouri7a78d6fd2015-01-17 13:23:532978
Joe Downing13dd76b2018-04-09 18:32:152979 if (delegate_) {
mlamouri7a78d6fd2015-01-17 13:23:532980 delegate_->ExitFullscreenModeForTab(this);
[email protected]657c8e02014-03-19 19:18:372981
Joe Downing13dd76b2018-04-09 18:32:152982 if (keyboard_lock_widget_)
2983 delegate_->CancelKeyboardLockRequest(this);
2984 }
2985
bokanece34a82016-01-28 19:49:462986 // The fullscreen state is communicated to the renderer through a resize
2987 // message. If the change in fullscreen state doesn't cause a view resize
2988 // then we must ensure web contents exit the fullscreen state by explicitly
2989 // sending a resize message. This is required for the situation of the browser
2990 // moving the view into a "browser fullscreen" state and then the contents
2991 // entering "tab fullscreen". Exiting the contents "tab fullscreen" then won't
2992 // have the side effect of the view resizing, hence the explicit call here is
2993 // required.
2994 if (!will_cause_resize) {
2995 if (RenderWidgetHostView* rwhv = GetRenderWidgetHostView()) {
2996 if (RenderWidgetHost* render_widget_host = rwhv->GetRenderWidgetHost())
Fady Samuel0b911822018-04-25 13:22:162997 render_widget_host->SynchronizeVisualProperties();
bokanece34a82016-01-28 19:49:462998 }
scheib3dcb6c932015-02-23 10:55:582999 }
3000
Arthur Sonzogni929d29f2018-09-17 14:19:443001 current_fullscreen_frame_ = nullptr;
Becca Hughese9e27952018-06-25 17:08:273002
Alexander Timin90c20c32020-08-12 15:28:323003 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3004 observer->DidToggleFullscreenModeForTab(IsFullscreen(), will_cause_resize);
3005 });
Becca Hughesd11d6502018-07-31 17:01:283006
3007 if (display_cutout_host_impl_)
3008 display_cutout_host_impl_->DidExitFullscreen();
Avi Drissman33972942020-06-19 14:16:013009
3010 FullscreenContentsSet(GetBrowserContext())->erase(this);
[email protected]8a5e0ca2011-08-25 06:30:473011}
3012
Becca Hughesfd5d8f892018-06-14 18:23:363013void WebContentsImpl::FullscreenStateChanged(RenderFrameHost* rfh,
3014 bool is_fullscreen) {
Arthur Sonzogni929d29f2018-09-17 14:19:443015 RenderFrameHostImpl* frame = static_cast<RenderFrameHostImpl*>(rfh);
Becca Hughesfd5d8f892018-06-14 18:23:363016
3017 if (is_fullscreen) {
Jan Wilken Dörrie531be7ca2019-06-07 10:05:573018 if (!base::Contains(fullscreen_frames_, frame)) {
Arthur Sonzogni929d29f2018-09-17 14:19:443019 fullscreen_frames_.insert(frame);
3020 FullscreenFrameSetUpdated();
Becca Hughesfd5d8f892018-06-14 18:23:363021 }
Arthur Sonzogni929d29f2018-09-17 14:19:443022 return;
3023 }
Becca Hughesfd5d8f892018-06-14 18:23:363024
Arthur Sonzogni929d29f2018-09-17 14:19:443025 // If |frame| is no longer in fullscreen, remove it and any descendants.
3026 // See https://fullscreen.spec.whatwg.org.
Arthur Sonzogni969a794e2018-10-11 08:56:093027 size_t size_before_deletion = fullscreen_frames_.size();
3028 base::EraseIf(fullscreen_frames_, [&](RenderFrameHostImpl* current) {
3029 return (current == frame || current->IsDescendantOf(frame));
Arthur Sonzogni929d29f2018-09-17 14:19:443030 });
3031
Arthur Sonzogni969a794e2018-10-11 08:56:093032 if (size_before_deletion != fullscreen_frames_.size())
Arthur Sonzogni929d29f2018-09-17 14:19:443033 FullscreenFrameSetUpdated();
3034}
3035
3036void WebContentsImpl::FullscreenFrameSetUpdated() {
3037 if (fullscreen_frames_.empty()) {
3038 current_fullscreen_frame_ = nullptr;
3039 return;
Becca Hughesfd5d8f892018-06-14 18:23:363040 }
3041
Arthur Sonzogni929d29f2018-09-17 14:19:443042 // Find the current fullscreen frame and call the observers.
3043 // If frame A is fullscreen, then frame B goes into inner fullscreen, then B
3044 // exits fullscreen - that will result in A being fullscreen.
3045 RenderFrameHostImpl* new_fullscreen_frame = *std::max_element(
3046 fullscreen_frames_.begin(), fullscreen_frames_.end(), FrameCompareDepth);
Becca Hughesfd5d8f892018-06-14 18:23:363047
Arthur Sonzogni929d29f2018-09-17 14:19:443048 // If we have already notified observers about this frame then we should not
3049 // fire the observers again.
3050 if (new_fullscreen_frame == current_fullscreen_frame_)
3051 return;
3052 current_fullscreen_frame_ = new_fullscreen_frame;
Becca Hughesfd5d8f892018-06-14 18:23:363053
Alexander Timin90c20c32020-08-12 15:28:323054 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3055 observer->DidAcquireFullscreen(new_fullscreen_frame);
3056 });
Arthur Sonzogni929d29f2018-09-17 14:19:443057 if (display_cutout_host_impl_)
3058 display_cutout_host_impl_->DidAcquireFullscreen(new_fullscreen_frame);
Becca Hughesfd5d8f892018-06-14 18:23:363059}
3060
Collin Baker989e0882019-11-01 01:27:173061void WebContentsImpl::UpdateVisibilityAndNotifyPageAndView(
3062 Visibility new_visibility) {
Collin Baker989e0882019-11-01 01:27:173063 // Only hide the page if there are no entities capturing screenshots
Collin Bakerc5259962019-11-14 17:51:583064 // or video (e.g. mirroring). If there are, apply the correct state of
3065 // kHidden or kHiddenButPainting.
3066 PageVisibilityState page_visibility;
3067 if (new_visibility == Visibility::VISIBLE || visible_capturer_count_ > 0)
3068 page_visibility = PageVisibilityState::kVisible;
3069 else if (hidden_capturer_count_ > 0)
3070 page_visibility = PageVisibilityState::kHiddenButPainting;
3071 else
3072 page_visibility = PageVisibilityState::kHidden;
Collin Baker989e0882019-11-01 01:27:173073 // If there are entities in Picture-in-Picture mode, don't activate
3074 // the "disable rendering" optimization.
Collin Bakerc5259962019-11-14 17:51:583075 const bool view_is_visible =
3076 page_visibility != PageVisibilityState::kHidden ||
3077 HasPictureInPictureVideo();
Collin Baker989e0882019-11-01 01:27:173078
Collin Bakerc5259962019-11-14 17:51:583079 if (page_visibility != PageVisibilityState::kHidden) {
Dana Friedcf3bc8e2019-11-13 20:00:243080 // We cannot show a page or capture video unless there is a valid renderer
3081 // associated with this web contents. The navigation controller for this
3082 // page must be set to active (allowing navigation to complete, a renderer
3083 // and its associated views to be created, etc.) if any of these conditions
3084 // holds.
3085 //
3086 // Previously, it was possible for browser-side code to try to capture video
3087 // from a restored tab (for a variety of reasons, including the browser
3088 // creating preview thumbnails) and the tab would never actually load. By
Collin Bakerc5259962019-11-14 17:51:583089 // keying this behavior off of |page_visibility| instead of just
Dana Friedcf3bc8e2019-11-13 20:00:243090 // |new_visibility| we avoid this case. See crbug.com/1020782 for more
3091 // context.
3092 controller_.SetActive(true);
3093
3094 // This shows the Page before showing the individual RenderWidgets, as
3095 // RenderWidgets will work to produce compositor frames and handle input
3096 // as soon as they are shown. But the Page and other classes do not expect
3097 // to be producing frames when the Page is hidden. So we make sure the Page
3098 // is shown first.
Yuzu Saijo232076f2020-05-29 07:14:023099 for (auto* rvh : GetRenderViewHostsIncludingBackForwardCached()) {
3100 rvh->SetVisibility(page_visibility);
Yuzu Saijobe024af02020-05-11 07:35:563101 }
Collin Baker98457b52019-11-06 21:34:293102 }
Collin Baker989e0882019-11-01 01:27:173103
3104 // |GetRenderWidgetHostView()| can be null if the user middle clicks a link to
3105 // open a tab in the background, then closes the tab before selecting it.
3106 // This is because closing the tab calls WebContentsImpl::Destroy(), which
3107 // removes the |GetRenderViewHost()|; then when we actually destroy the
3108 // window, OnWindowPosChanged() notices and calls WasHidden() (which
3109 // calls us).
3110 if (auto* view = GetRenderWidgetHostView()) {
3111 if (view_is_visible) {
3112 view->Show();
Collin Baker989e0882019-11-01 01:27:173113 } else if (new_visibility == Visibility::HIDDEN) {
3114 view->Hide();
3115 } else {
3116 view->WasOccluded();
3117 }
3118 }
3119
Carlos IL07f282f2020-05-15 22:58:293120 SetVisibilityForChildViews(view_is_visible);
Collin Baker989e0882019-11-01 01:27:173121
3122 // Make sure to call SetVisibilityAndNotifyObservers(VISIBLE) before notifying
3123 // the CrossProcessFrameConnector.
3124 if (new_visibility == Visibility::VISIBLE) {
3125 last_active_time_ = base::TimeTicks::Now();
3126 SetVisibilityAndNotifyObservers(new_visibility);
3127 }
3128
Collin Bakerc5259962019-11-14 17:51:583129 if (page_visibility == PageVisibilityState::kHidden) {
Collin Baker989e0882019-11-01 01:27:173130 // Similar to when showing the page, we only hide the page after
3131 // hiding the individual RenderWidgets.
Yuzu Saijo232076f2020-05-29 07:14:023132 for (auto* rvh : GetRenderViewHostsIncludingBackForwardCached()) {
3133 rvh->SetVisibility(page_visibility);
Yuzu Saijobe024af02020-05-11 07:35:563134 }
3135
Collin Baker989e0882019-11-01 01:27:173136 } else {
3137 for (FrameTreeNode* node : frame_tree_.Nodes()) {
3138 RenderFrameProxyHost* parent = node->render_manager()->GetProxyToParent();
3139 if (!parent)
3140 continue;
3141
3142 parent->cross_process_frame_connector()->DelegateWasShown();
3143 }
3144 }
3145
3146 if (new_visibility != Visibility::VISIBLE)
3147 SetVisibilityAndNotifyObservers(new_visibility);
3148}
3149
Clark DuValla0e42992018-09-17 17:00:113150#if defined(OS_ANDROID)
3151void WebContentsImpl::UpdateUserGestureCarryoverInfo() {
3152 if (delegate_)
3153 delegate_->UpdateUserGestureCarryoverInfo(this);
3154}
3155#endif
3156
Avi Drissman97aef042020-06-30 21:04:483157bool WebContentsImpl::IsFullscreen() {
[email protected]199bba6e2012-04-04 16:19:383158 return delegate_ ? delegate_->IsFullscreenForTabOrPending(this) : false;
[email protected]5d5f7af2011-10-01 01:38:123159}
3160
Malay Keshav87c42c02019-01-15 08:37:473161bool WebContentsImpl::ShouldShowStaleContentOnEviction() {
3162 return GetDelegate() && GetDelegate()->ShouldShowStaleContentOnEviction(this);
3163}
3164
danakj45d42452020-04-08 17:24:183165blink::mojom::DisplayMode WebContentsImpl::GetDisplayMode() const {
mikhail.pozdnyakovc0e251b2015-04-15 06:51:123166 return delegate_ ? delegate_->GetDisplayMode(this)
Eric Willigers052f0432019-10-04 04:06:573167 : blink::mojom::DisplayMode::kBrowser;
mikhail.pozdnyakovc0e251b2015-04-15 06:51:123168}
3169
avic3aa8422015-11-09 20:57:223170void WebContentsImpl::RequestToLockMouse(
3171 RenderWidgetHostImpl* render_widget_host,
3172 bool user_gesture,
lfgad8244352016-07-13 16:55:513173 bool last_unlocked_by_target,
3174 bool privileged) {
lfgf0cd46e2017-01-04 00:05:233175 for (WebContentsImpl* current = this; current;
3176 current = current->GetOuterWebContents()) {
3177 if (current->mouse_lock_widget_) {
James Hollyerd5c9de462020-03-10 19:02:453178 render_widget_host->GotResponseToLockMouseRequest(
3179 blink::mojom::PointerLockResult::kAlreadyLocked);
lfgf0cd46e2017-01-04 00:05:233180 return;
3181 }
[email protected]e9621112011-10-17 05:38:373182 }
avic3aa8422015-11-09 20:57:223183
lfgad8244352016-07-13 16:55:513184 if (privileged) {
lfgf0cd46e2017-01-04 00:05:233185 DCHECK(!GetOuterWebContents());
lfgad8244352016-07-13 16:55:513186 mouse_lock_widget_ = render_widget_host;
James Hollyerd5c9de462020-03-10 19:02:453187 render_widget_host->GotResponseToLockMouseRequest(
3188 blink::mojom::PointerLockResult::kSuccess);
lfgad8244352016-07-13 16:55:513189 return;
3190 }
3191
lfgbee1e0a2016-06-08 21:24:213192 bool widget_in_frame_tree = false;
3193 for (FrameTreeNode* node : frame_tree_.Nodes()) {
3194 if (node->current_frame_host()->GetRenderWidgetHost() ==
3195 render_widget_host) {
3196 widget_in_frame_tree = true;
3197 break;
3198 }
3199 }
3200
3201 if (widget_in_frame_tree && delegate_) {
lfgf0cd46e2017-01-04 00:05:233202 for (WebContentsImpl* current = this; current;
3203 current = current->GetOuterWebContents()) {
3204 current->mouse_lock_widget_ = render_widget_host;
3205 }
3206
avic3aa8422015-11-09 20:57:223207 delegate_->RequestToLockMouse(this, user_gesture, last_unlocked_by_target);
lfgbee1e0a2016-06-08 21:24:213208 } else {
James Hollyerd5c9de462020-03-10 19:02:453209 render_widget_host->GotResponseToLockMouseRequest(
3210 blink::mojom::PointerLockResult::kWrongDocument);
lfgbee1e0a2016-06-08 21:24:213211 }
[email protected]e9621112011-10-17 05:38:373212}
3213
avi3e4b8512015-11-11 01:55:493214void WebContentsImpl::LostMouseLock(RenderWidgetHostImpl* render_widget_host) {
lfgbee1e0a2016-06-08 21:24:213215 CHECK(mouse_lock_widget_);
lfgf0cd46e2017-01-04 00:05:233216
3217 if (mouse_lock_widget_->delegate()->GetAsWebContents() != this)
3218 return mouse_lock_widget_->delegate()->LostMouseLock(render_widget_host);
3219
lfgbee1e0a2016-06-08 21:24:213220 mouse_lock_widget_->SendMouseLockLost();
lfgf0cd46e2017-01-04 00:05:233221 for (WebContentsImpl* current = this; current;
3222 current = current->GetOuterWebContents()) {
3223 current->mouse_lock_widget_ = nullptr;
3224 }
avi3e4b8512015-11-11 01:55:493225
[email protected]e9621112011-10-17 05:38:373226 if (delegate_)
3227 delegate_->LostMouseLock();
3228}
3229
lfgad8244352016-07-13 16:55:513230bool WebContentsImpl::HasMouseLock(RenderWidgetHostImpl* render_widget_host) {
3231 // To verify if the mouse is locked, the mouse_lock_widget_ needs to be
3232 // assigned to the widget that requested the mouse lock, and the top-level
3233 // platform RenderWidgetHostView needs to hold the mouse lock from the OS.
Lucas Gadania0ea0172018-09-20 18:31:373234 auto* widget_host = GetTopLevelRenderWidgetHostView();
3235 return mouse_lock_widget_ == render_widget_host && widget_host &&
3236 widget_host->IsMouseLocked();
lfgad8244352016-07-13 16:55:513237}
3238
lfg84763c92017-02-16 18:55:153239RenderWidgetHostImpl* WebContentsImpl::GetMouseLockWidget() {
Lucas Gadania0ea0172018-09-20 18:31:373240 auto* widget_host = GetTopLevelRenderWidgetHostView();
3241 if ((widget_host && widget_host->IsMouseLocked()) ||
lfge2176fb2017-03-26 00:45:473242 (GetFullscreenRenderWidgetHostView() &&
Lucas Gadania0ea0172018-09-20 18:31:373243 GetFullscreenRenderWidgetHostView()->IsMouseLocked())) {
lfg84763c92017-02-16 18:55:153244 return mouse_lock_widget_;
Lucas Gadania0ea0172018-09-20 18:31:373245 }
lfg84763c92017-02-16 18:55:153246
3247 return nullptr;
3248}
3249
Joe Downing192998b22018-03-22 15:51:363250bool WebContentsImpl::RequestKeyboardLock(
Joe Downing13dd76b2018-04-09 18:32:153251 RenderWidgetHostImpl* render_widget_host,
3252 bool esc_key_locked) {
Joe Downing192998b22018-03-22 15:51:363253 DCHECK(render_widget_host);
Joe Downing192998b22018-03-22 15:51:363254 if (render_widget_host->delegate()->GetAsWebContents() != this) {
3255 NOTREACHED();
3256 return false;
3257 }
3258
3259 // KeyboardLock is only supported when called by the top-level browsing
3260 // context and is not supported in embedded content scenarios.
3261 if (GetOuterWebContents())
3262 return false;
3263
Joe Downing13dd76b2018-04-09 18:32:153264 esc_key_locked_ = esc_key_locked;
Joe Downing192998b22018-03-22 15:51:363265 keyboard_lock_widget_ = render_widget_host;
3266
Joe Downing13dd76b2018-04-09 18:32:153267 if (delegate_)
3268 delegate_->RequestKeyboardLock(this, esc_key_locked_);
Joe Downing192998b22018-03-22 15:51:363269 return true;
3270}
3271
3272void WebContentsImpl::CancelKeyboardLock(
3273 RenderWidgetHostImpl* render_widget_host) {
3274 if (!keyboard_lock_widget_ || render_widget_host != keyboard_lock_widget_)
3275 return;
3276
3277 RenderWidgetHostImpl* old_keyboard_lock_widget = keyboard_lock_widget_;
3278 keyboard_lock_widget_ = nullptr;
3279
Joe Downing13dd76b2018-04-09 18:32:153280 if (delegate_)
3281 delegate_->CancelKeyboardLockRequest(this);
3282
Joe Downing192998b22018-03-22 15:51:363283 old_keyboard_lock_widget->CancelKeyboardLock();
3284}
3285
3286RenderWidgetHostImpl* WebContentsImpl::GetKeyboardLockWidget() {
3287 return keyboard_lock_widget_;
3288}
3289
Dave Tapuskac3344362019-02-20 17:54:283290void WebContentsImpl::OnRenderFrameProxyVisibilityChanged(
3291 blink::mojom::FrameVisibility visibility) {
3292 switch (visibility) {
3293 case blink::mojom::FrameVisibility::kRenderedInViewport:
3294 WasShown();
3295 break;
3296 case blink::mojom::FrameVisibility::kNotRendered:
3297 WasHidden();
3298 break;
3299 case blink::mojom::FrameVisibility::kRenderedOutOfViewport:
3300 WasOccluded();
3301 break;
3302 }
ekaramada4f42692016-02-11 19:48:373303}
3304
Albert J. Wong65fe64d2019-09-20 02:48:143305RenderFrameHostDelegate* WebContentsImpl::CreateNewWindow(
csharrison95f01e922017-04-24 18:52:353306 RenderFrameHost* opener,
rockot5c478a72016-09-28 23:14:183307 const mojom::CreateNewWindowParams& params,
Albert J. Wong65fe64d2019-09-20 02:48:143308 bool is_new_browsing_instance,
Sergey Kuznetsov32257a22019-02-11 20:26:503309 bool has_user_gesture,
[email protected]97714c82012-06-06 10:15:133310 SessionStorageNamespace* session_storage_namespace) {
csharrison95f01e922017-04-24 18:52:353311 DCHECK(opener);
nick5ae4d2d2017-01-06 01:18:353312
csharrison95f01e922017-04-24 18:52:353313 int render_process_id = opener->GetProcess()->GetID();
csharrison95f01e922017-04-24 18:52:353314
Albert J. Wong65fe64d2019-09-20 02:48:143315 SiteInstance* source_site_instance = opener->GetSiteInstance();
nick5ae4d2d2017-01-06 01:18:353316
Aaron Colwelleb219982020-01-16 02:17:273317 const GURL source_site_url = source_site_instance->GetSiteURL();
[email protected]fdac6ade2013-07-20 01:06:303318 const std::string& partition_id =
Aaron Colwelleb219982020-01-16 02:17:273319 GetContentClient()->browser()->GetStoragePartitionIdForSite(
3320 GetBrowserContext(), source_site_url);
3321 {
3322 StoragePartition* partition = BrowserContext::GetStoragePartitionForSite(
3323 GetBrowserContext(), source_site_url);
3324 DOMStorageContextWrapper* dom_storage_context =
3325 static_cast<DOMStorageContextWrapper*>(
3326 partition->GetDOMStorageContext());
3327 SessionStorageNamespaceImpl* session_storage_namespace_impl =
3328 static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace);
3329 CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context));
3330 }
[email protected]dd6730412013-08-14 15:03:373331
Albert J. Wong1ceccef92019-10-08 08:25:203332 if (delegate_ && delegate_->IsWebContentsCreationOverridden(
3333 source_site_instance, params.window_container_type,
3334 opener->GetLastCommittedURL(), params.frame_name,
3335 params.target_url)) {
3336 return static_cast<WebContentsImpl*>(delegate_->CreateCustomWebContents(
3337 opener, source_site_instance, is_new_browsing_instance,
3338 opener->GetLastCommittedURL(), params.frame_name, params.target_url,
3339 partition_id, session_storage_namespace));
[email protected]dd6730412013-08-14 15:03:373340 }
3341
danakj22b4e8b2019-08-01 23:14:393342 bool renderer_started_hidden =
3343 params.disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB;
3344
Aaron Colwelleb219982020-01-16 02:17:273345 // We usually create the new window in the same BrowsingInstance (group of
3346 // script-related windows), by passing in the current SiteInstance. However,
3347 // if the opener is being suppressed (in a non-guest), we do not provide
3348 // a SiteInstance which causes a new one to get created in its own
3349 // BrowsingInstance.
3350 bool is_guest = BrowserPluginGuest::IsGuest(this);
3351 scoped_refptr<SiteInstance> site_instance =
3352 params.opener_suppressed && !is_guest ? nullptr : source_site_instance;
3353
[email protected]dd6730412013-08-14 15:03:373354 // Create the new web contents. This will automatically create the new
3355 // WebContentsView. In the future, we may want to create the view separately.
[email protected]fc72bb12013-06-02 21:13:463356 CreateParams create_params(GetBrowserContext(), site_instance.get());
nasko48321ca32015-07-02 20:44:123357 create_params.main_frame_name = params.frame_name;
alexmos4cf2aa32015-07-15 23:40:433358 create_params.opener_render_process_id = render_process_id;
csharrison95f01e922017-04-24 18:52:353359 create_params.opener_render_frame_id = opener->GetRoutingID();
[email protected]50d326e2014-05-20 17:59:063360 create_params.opener_suppressed = params.opener_suppressed;
danakj22b4e8b2019-08-01 23:14:393361 create_params.initially_hidden = renderer_started_hidden;
[email protected]50d326e2014-05-20 17:59:063362
Albert J. Wong65fe64d2019-09-20 02:48:143363 // Even though all codepaths leading here are in response to a renderer
3364 // tryng to open a new window, if the new window ends up in a different
3365 // browsing instance, then the RenderViewHost, RenderWidgetHost,
3366 // RenderFrameHost constellation is effectively browser initiated
3367 // the opener's process will not given the routing IDs for the new
3368 // objects.
3369 create_params.renderer_initiated_creation = !is_new_browsing_instance;
Albert J. Wong1ceccef92019-10-08 08:25:203370
Albert J. Wong65fe64d2019-09-20 02:48:143371 std::unique_ptr<WebContentsImpl> new_contents;
[email protected]c4538072013-03-18 02:17:553372 if (!is_guest) {
3373 create_params.context = view_->GetNativeView();
Albert J. Wong65fe64d2019-09-20 02:48:143374 new_contents = WebContentsImpl::Create(create_params);
3375 } else {
3376 new_contents = base::WrapUnique(static_cast<WebContentsImpl*>(
3377 GetBrowserPluginGuest()->CreateNewGuestWindow(create_params)));
[email protected]c4538072013-03-18 02:17:553378 }
Albert J. Wong65fe64d2019-09-20 02:48:143379 auto* new_contents_impl = new_contents.get();
danakje6c01622018-10-05 19:39:263380
3381 new_contents_impl->GetController().SetSessionStorageNamespace(
erikchenbee5c9622018-04-27 19:30:253382 partition_id, session_storage_namespace);
[email protected]d1198fd2012-08-13 22:50:193383
alexmos646fec02015-07-25 00:11:493384 // If the new frame has a name, make sure any SiteInstances that can find
3385 // this named frame have proxies for it. Must be called after
3386 // SetSessionStorageNamespace, since this calls CreateRenderView, which uses
3387 // GetSessionStorageNamespace.
3388 if (!params.frame_name.empty())
danakje6c01622018-10-05 19:39:263389 new_contents_impl->GetRenderManager()->CreateProxiesForNewNamedFrame();
alexmos646fec02015-07-25 00:11:493390
[email protected]c4538072013-03-18 02:17:553391 // Save the window for later if we're not suppressing the opener (since it
[email protected]d70bea92013-04-05 04:23:343392 // will be shown immediately).
3393 if (!params.opener_suppressed) {
3394 if (!is_guest) {
danakje6c01622018-10-05 19:39:263395 WebContentsView* new_view = new_contents_impl->view_.get();
[email protected]bafe6cd2012-05-23 23:09:503396
[email protected]d70bea92013-04-05 04:23:343397 // TODO(brettw): It seems bogus that we have to call this function on the
3398 // newly created object and give it one of its own member variables.
danakj22b4e8b2019-08-01 23:14:393399 RenderWidgetHostView* widget_view = new_view->CreateViewForWidget(
W. James MacLean13d834d2019-12-04 16:06:453400 new_contents_impl->GetRenderViewHost()->GetWidget());
danakj22b4e8b2019-08-01 23:14:393401 if (!renderer_started_hidden) {
3402 // RenderWidgets for frames always initialize as hidden. If the renderer
3403 // created this window as visible, then we show it here.
3404 widget_view->Show();
3405 }
[email protected]d70bea92013-04-05 04:23:343406 }
[email protected]bafe6cd2012-05-23 23:09:503407 // Save the created window associated with the route so we can show it
3408 // later.
Albert J. Wongcb004632018-07-10 22:58:253409 //
3410 // TODO(ajwong): This should be keyed off the RenderFrame routing id or the
3411 // FrameTreeNode id instead of the routing id of the Widget for the main
3412 // frame. https://crbug.com/545684
Fergal Daly052873a82020-03-11 14:45:493413 int32_t main_frame_routing_id = new_contents_impl->GetMainFrame()
3414 ->GetRenderWidgetHost()
3415 ->GetRoutingID();
3416 GlobalRoutingID id(render_process_id, main_frame_routing_id);
Joel Hockey8c2011b22020-04-30 05:07:193417 pending_contents_[id] =
3418 CreatedWindow(std::move(new_contents), params.target_url);
danakje6c01622018-10-05 19:39:263419 AddDestructionObserver(new_contents_impl);
[email protected]bafe6cd2012-05-23 23:09:503420 }
3421
3422 if (delegate_) {
Bryan McQuaded2b93c02017-07-14 22:26:313423 delegate_->WebContentsCreated(this, render_process_id,
3424 opener->GetRoutingID(), params.frame_name,
danakje6c01622018-10-05 19:39:263425 params.target_url, new_contents_impl);
[email protected]bafe6cd2012-05-23 23:09:503426 }
3427
Alexander Timin90c20c32020-08-12 15:28:323428 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3429 observer->DidOpenRequestedURL(new_contents_impl, opener, params.target_url,
3430 params.referrer.To<Referrer>(),
3431 params.disposition, ui::PAGE_TRANSITION_LINK,
3432 false, // started_from_context_menu
3433 true); // renderer_initiated
3434 });
pnolandaae574e2017-03-06 21:04:213435
Avi Drissmanba3b1b342017-08-29 18:16:133436 // Any new WebContents opened while this WebContents is in fullscreen can be
3437 // used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:453438 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
3439 // The new contents will be independent of this contents, so release the
3440 // fullscreen block.
3441 fullscreen_block.RunAndReset();
Avi Drissmanba3b1b342017-08-29 18:16:133442
[email protected]bafe6cd2012-05-23 23:09:503443 if (params.opener_suppressed) {
3444 // When the opener is suppressed, the original renderer cannot access the
3445 // new window. As a result, we need to show and navigate the window here.
[email protected]eda238a12012-09-07 23:44:003446 bool was_blocked = false;
erikchenbee5c9622018-04-27 19:30:253447
[email protected]eda238a12012-09-07 23:44:003448 if (delegate_) {
danakje6c01622018-10-05 19:39:263449 base::WeakPtr<WebContentsImpl> weak_new_contents =
3450 new_contents_impl->weak_factory_.GetWeakPtr();
nick0d558482017-02-13 22:27:223451
danakje6c01622018-10-05 19:39:263452 gfx::Rect initial_rect; // Report an empty initial rect.
Albert J. Wong65fe64d2019-09-20 02:48:143453 delegate_->AddNewContents(this, std::move(new_contents),
Joel Hockey891e88062020-04-30 05:38:443454 params.target_url, params.disposition,
3455 initial_rect, has_user_gesture, &was_blocked);
danakje6c01622018-10-05 19:39:263456 // The delegate may delete |new_contents_impl| during AddNewContents().
nick0d558482017-02-13 22:27:223457 if (!weak_new_contents)
Albert J. Wong65fe64d2019-09-20 02:48:143458 return nullptr;
[email protected]eda238a12012-09-07 23:44:003459 }
erikchenbee5c9622018-04-27 19:30:253460
[email protected]eda238a12012-09-07 23:44:003461 if (!was_blocked) {
Nasko Oskov83a8cf92018-10-19 14:58:563462 std::unique_ptr<NavigationController::LoadURLParams> load_params =
3463 std::make_unique<NavigationController::LoadURLParams>(
3464 params.target_url);
Nasko Oskov93e7c55c2018-12-19 01:59:293465 load_params->initiator_origin = opener->GetLastCommittedOrigin();
Lukasz Anforowiczd2629b42020-08-11 16:07:313466 // Avoiding setting |load_params->source_site_instance| when
3467 // |opener_suppressed| is true, because in that case we do not want to use
3468 // the old SiteInstance and/or BrowsingInstance. See also the test here:
3469 // NewPopupCOOP_SameOriginPolicyAndCrossOriginIframeSetsNoopener.
Leon Han963dc182018-11-06 05:41:483470 load_params->referrer = params.referrer.To<Referrer>();
Nasko Oskov83a8cf92018-10-19 14:58:563471 load_params->transition_type = ui::PAGE_TRANSITION_LINK;
3472 load_params->is_renderer_initiated = true;
Sergey Kuznetsov32257a22019-02-11 20:26:503473 load_params->has_user_gesture = has_user_gesture;
mariakhomenkoa4971c12015-07-21 19:04:373474
3475 if (delegate_ && !is_guest &&
3476 !delegate_->ShouldResumeRequestsForCreatedWindow()) {
Nasko Oskov83a8cf92018-10-19 14:58:563477 // We are in asynchronous add new contents path, delay navigation.
3478 DCHECK(!new_contents_impl->delayed_open_url_params_);
3479 new_contents_impl->delayed_load_url_params_ = std::move(load_params);
mariakhomenkoa4971c12015-07-21 19:04:373480 } else {
Nasko Oskov83a8cf92018-10-19 14:58:563481 new_contents_impl->controller_.LoadURLWithParams(*load_params.get());
Nasko Oskov28ebd5b2018-12-07 22:29:333482 if (!is_guest)
3483 new_contents_impl->Focus();
mariakhomenkoa4971c12015-07-21 19:04:373484 }
[email protected]eda238a12012-09-07 23:44:003485 }
[email protected]bafe6cd2012-05-23 23:09:503486 }
Albert J. Wong65fe64d2019-09-20 02:48:143487 return new_contents_impl;
[email protected]bafe6cd2012-05-23 23:09:503488}
3489
Dave Tapuskad9835622020-03-10 17:32:313490void WebContentsImpl::CreateNewWidget(
3491 int32_t render_process_id,
3492 int32_t widget_route_id,
Dave Tapuska8499eec2020-03-16 17:54:303493 mojo::PendingAssociatedReceiver<blink::mojom::WidgetHost> blink_widget_host,
3494 mojo::PendingAssociatedRemote<blink::mojom::Widget> blink_widget) {
Albert J. Wongf6e13ed2018-09-18 15:25:473495 CreateNewWidget(render_process_id, widget_route_id, /*is_fullscreen=*/false,
Dave Tapuskab686c1b2020-06-09 00:40:233496 std::move(blink_widget_host), std::move(blink_widget));
[email protected]bafe6cd2012-05-23 23:09:503497}
3498
Julie Jeongeun Kimcaacf9102019-09-12 02:13:053499void WebContentsImpl::CreateNewFullscreenWidget(
3500 int32_t render_process_id,
3501 int32_t widget_route_id,
Dave Tapuska8499eec2020-03-16 17:54:303502 mojo::PendingAssociatedReceiver<blink::mojom::WidgetHost> blink_widget_host,
3503 mojo::PendingAssociatedRemote<blink::mojom::Widget> blink_widget) {
Albert J. Wongf6e13ed2018-09-18 15:25:473504 CreateNewWidget(render_process_id, widget_route_id, /*is_fullscreen=*/true,
Dave Tapuskab686c1b2020-06-09 00:40:233505 std::move(blink_widget_host), std::move(blink_widget));
[email protected]bafe6cd2012-05-23 23:09:503506}
3507
Dave Tapuskad9835622020-03-10 17:32:313508void WebContentsImpl::CreateNewWidget(
3509 int32_t render_process_id,
3510 int32_t route_id,
3511 bool is_fullscreen,
Dave Tapuska8499eec2020-03-16 17:54:303512 mojo::PendingAssociatedReceiver<blink::mojom::WidgetHost> blink_widget_host,
3513 mojo::PendingAssociatedRemote<blink::mojom::Widget> blink_widget) {
kenrba26d15092016-02-10 22:00:253514 RenderProcessHost* process = RenderProcessHost::FromID(render_process_id);
kenrbb46f86a2015-12-07 07:53:233515 // A message to create a new widget can only come from an active process for
[email protected]a8504022013-12-04 20:23:513516 // this WebContentsImpl instance. If any other process sends the request,
3517 // it is invalid and the process must be terminated.
dcheng57e39e22016-01-21 00:25:383518 if (!HasMatchingProcess(&frame_tree_, render_process_id)) {
Lukasz Anforowicz6f746282018-01-04 23:24:513519 ReceivedBadMessage(process, bad_message::WCI_NEW_WIDGET_PROCESS_MISMATCH);
[email protected]a8504022013-12-04 20:23:513520 return;
3521 }
3522
Dave Tapuskab686c1b2020-06-09 00:40:233523 RenderWidgetHostImpl* widget_host =
3524 new RenderWidgetHostImpl(this, process, route_id, IsHidden(),
3525 std::make_unique<FrameTokenMessageQueue>());
Dave Tapuska8499eec2020-03-16 17:54:303526
3527 widget_host->BindWidgetInterfaces(std::move(blink_widget_host),
3528 std::move(blink_widget));
[email protected]cfd80b02014-05-01 17:46:483529 RenderWidgetHostViewBase* widget_view =
3530 static_cast<RenderWidgetHostViewBase*>(
danakj0b246942018-09-17 21:30:273531 view_->CreateViewForChildWidget(widget_host));
[email protected]83918ec2013-01-10 15:37:193532 if (!widget_view)
3533 return;
danakj0b246942018-09-17 21:30:273534 // Fullscreen child widgets are frames, other child widgets are popups, and
3535 // popups should not get activated.
3536 if (!is_fullscreen)
3537 widget_view->SetWidgetType(WidgetType::kPopup);
[email protected]bafe6cd2012-05-23 23:09:503538 // Save the created widget associated with the route so we can show it later.
Lukasz Anforowicz09060bdf72018-08-23 15:53:173539 pending_widget_views_[GlobalRoutingID(render_process_id, route_id)] =
alexmosc2a8cec2016-05-23 22:19:533540 widget_view;
[email protected]bafe6cd2012-05-23 23:09:503541}
3542
Mike Wassermandabad612020-08-13 04:26:273543void WebContentsImpl::ShowCreatedWindow(RenderFrameHost* opener,
nick5ae4d2d2017-01-06 01:18:353544 int main_frame_widget_route_id,
[email protected]bafe6cd2012-05-23 23:09:503545 WindowOpenDisposition disposition,
bokan107a47f2015-02-03 23:23:393546 const gfx::Rect& initial_rect,
[email protected]bafe6cd2012-05-23 23:09:503547 bool user_gesture) {
danakje6c01622018-10-05 19:39:263548 // This method is the renderer requesting an existing top level window to
3549 // show a new top level window that the renderer created. Each top level
3550 // window is associated with a WebContents. In this case it was created
3551 // earlier but showing it was deferred until the renderer requested for it
3552 // to be shown. We find that previously created WebContents here.
3553 // TODO(danakj): Why do we defer this show step until the renderer asks for it
3554 // when it will always do so. What needs to happen in the renderer before we
3555 // reach here?
Mike Wassermandabad612020-08-13 04:26:273556 base::Optional<CreatedWindow> owned_created = GetCreatedWindow(
3557 opener->GetProcess()->GetID(), main_frame_widget_route_id);
Joel Hockey8c2011b22020-04-30 05:07:193558
danakje6c01622018-10-05 19:39:263559 // The browser may have rejected the request to make a new window, or the
3560 // renderer could be sending an invalid route id. Ignore the request then.
Joel Hockey8c2011b22020-04-30 05:07:193561 if (!owned_created || !owned_created->contents)
danakje6c01622018-10-05 19:39:263562 return;
mariakhomenko44bdc4732015-04-29 01:55:383563
Joel Hockey8c2011b22020-04-30 05:07:193564 WebContentsImpl* created = owned_created->contents.get();
3565
danakje6c01622018-10-05 19:39:263566 // This uses the delegate for the WebContents where the window was created
3567 // from, to control how to show the newly created window.
3568 WebContentsDelegate* delegate = GetDelegate();
nick5ae4d2d2017-01-06 01:18:353569
danakje6c01622018-10-05 19:39:263570 // The delegate can be null in tests, so we must check for it :(.
3571 if (delegate) {
3572 // Mark the web contents as pending resume, then immediately do
3573 // the resume if the delegate wants it.
3574 created->is_resume_pending_ = true;
3575 if (delegate->ShouldResumeRequestsForCreatedWindow())
3576 created->ResumeLoadingCreatedWebContents();
3577
Mike Wassermandabad612020-08-13 04:26:273578 // Individual members of |initial_rect| may be 0 to indicate that the
3579 // window.open() feature string did not specify a value. This code does not
3580 // have the ability to distinguish between an unspecified value and 0.
3581 // Assume that if any single value is non-zero, all values should be used.
3582 // TODO(crbug.com/897300): Plumb values as specified; set defaults here?
3583 gfx::Rect adjusted_rect = initial_rect;
3584 if (adjusted_rect != gfx::Rect())
3585 adjusted_rect = AdjustRequestedWindowBounds(adjusted_rect, opener);
3586
danakje6c01622018-10-05 19:39:263587 base::WeakPtr<WebContentsImpl> weak_created =
3588 created->weak_factory_.GetWeakPtr();
Joel Hockey8c2011b22020-04-30 05:07:193589 delegate->AddNewContents(this, std::move(owned_created->contents),
Joel Hockey891e88062020-04-30 05:38:443590 std::move(owned_created->target_url), disposition,
Mike Wassermandabad612020-08-13 04:26:273591 adjusted_rect, user_gesture, nullptr);
danakje6c01622018-10-05 19:39:263592 // The delegate may delete |created| during AddNewContents().
3593 if (!weak_created)
3594 return;
[email protected]eda238a12012-09-07 23:44:003595 }
danakje6c01622018-10-05 19:39:263596
3597 RenderWidgetHostImpl* rwh = created->GetMainFrame()->GetRenderWidgetHost();
3598 DCHECK_EQ(main_frame_widget_route_id, rwh->GetRoutingID());
3599 rwh->Send(new WidgetMsg_SetBounds_ACK(rwh->GetRoutingID()));
[email protected]bafe6cd2012-05-23 23:09:503600}
3601
alexmosc2a8cec2016-05-23 22:19:533602void WebContentsImpl::ShowCreatedWidget(int process_id,
Albert J. Wongf6e13ed2018-09-18 15:25:473603 int widget_route_id,
bokan107a47f2015-02-03 23:23:393604 const gfx::Rect& initial_rect) {
Albert J. Wongf6e13ed2018-09-18 15:25:473605 ShowCreatedWidget(process_id, widget_route_id, false, initial_rect);
[email protected]bafe6cd2012-05-23 23:09:503606}
3607
alexmosc2a8cec2016-05-23 22:19:533608void WebContentsImpl::ShowCreatedFullscreenWidget(int process_id,
Albert J. Wongf6e13ed2018-09-18 15:25:473609 int widget_route_id) {
3610 ShowCreatedWidget(process_id, widget_route_id, true, gfx::Rect());
[email protected]bafe6cd2012-05-23 23:09:503611}
3612
alexmosc2a8cec2016-05-23 22:19:533613void WebContentsImpl::ShowCreatedWidget(int process_id,
3614 int route_id,
[email protected]bafe6cd2012-05-23 23:09:503615 bool is_fullscreen,
bokan107a47f2015-02-03 23:23:393616 const gfx::Rect& initial_rect) {
[email protected]cfd80b02014-05-01 17:46:483617 RenderWidgetHostViewBase* widget_host_view =
alexmosc2a8cec2016-05-23 22:19:533618 static_cast<RenderWidgetHostViewBase*>(
3619 GetCreatedWidget(process_id, route_id));
[email protected]bafe6cd2012-05-23 23:09:503620 if (!widget_host_view)
3621 return;
[email protected]cfd80b02014-05-01 17:46:483622
W. James MacLeanec4125c2019-09-27 18:56:003623 // GetOutermostWebContents() returns |this| if there are no outer WebContents.
W. James MacLean3c5f50462019-10-28 16:24:213624 auto* outer_web_contents = GetOuterWebContents();
3625 auto* outermost_web_contents = GetOutermostWebContents();
W. James MacLeanec4125c2019-09-27 18:56:003626 RenderWidgetHostView* view =
W. James MacLean3c5f50462019-10-28 16:24:213627 outermost_web_contents->GetRenderWidgetHostView();
3628 // It's not entirely obvious why we need the transform only in the case where
3629 // the outer webcontents is not the same as the outermost webcontents. It may
3630 // be due to the fact that oopifs that are children of the mainframe get
3631 // correct values for their screenrects, but deeper cross-process frames do
3632 // not. Hopefully this can be resolved with https://crbug.com/928825.
3633 // Handling these cases separately is needed for http://crbug.com/1015298.
3634 bool needs_transform = this != outermost_web_contents &&
3635 outermost_web_contents != outer_web_contents;
W. James MacLeanec4125c2019-09-27 18:56:003636
3637 gfx::Rect transformed_rect(initial_rect);
3638 RenderWidgetHostView* this_view = GetRenderWidgetHostView();
W. James MacLean3c5f50462019-10-28 16:24:213639 if (needs_transform) {
W. James MacLeanec4125c2019-09-27 18:56:003640 // We need to transform the coordinates of initial_rect.
3641 gfx::Point origin =
3642 this_view->TransformPointToRootCoordSpace(initial_rect.origin());
3643 gfx::Point bottom_right =
3644 this_view->TransformPointToRootCoordSpace(initial_rect.bottom_right());
3645 transformed_rect =
3646 gfx::Rect(origin.x(), origin.y(), bottom_right.x() - origin.x(),
3647 bottom_right.y() - origin.y());
[email protected]cfd80b02014-05-01 17:46:483648 }
3649
danakj0b246942018-09-17 21:30:273650 // Fullscreen child widgets are frames, other child widgets are popups.
[email protected]4aebbca2013-09-17 22:26:493651 if (is_fullscreen) {
[email protected]d7f80ba2013-10-12 07:42:313652 DCHECK_EQ(MSG_ROUTING_NONE, fullscreen_widget_routing_id_);
[email protected]0b431992014-06-24 00:08:033653 view_->StoreFocus();
alexmosc9e76ec2016-05-16 22:59:373654 fullscreen_widget_process_id_ =
3655 widget_host_view->GetRenderWidgetHost()->GetProcess()->GetID();
[email protected]d7f80ba2013-10-12 07:42:313656 fullscreen_widget_routing_id_ = route_id;
[email protected]4aebbca2013-09-17 22:26:493657 if (delegate_ && delegate_->EmbedsFullscreenWidget()) {
3658 widget_host_view->InitAsChild(GetRenderWidgetHostView()->GetNativeView());
Mike Wasserman4ca09792020-05-29 17:44:433659 delegate_->EnterFullscreenModeForTab(GetMainFrame(),
Dave Tapuskaa4189512019-10-15 20:27:343660 blink::mojom::FullscreenOptions());
[email protected]4aebbca2013-09-17 22:26:493661 } else {
[email protected]cfd80b02014-05-01 17:46:483662 widget_host_view->InitAsFullscreen(view);
[email protected]4aebbca2013-09-17 22:26:493663 }
Alexander Timin90c20c32020-08-12 15:28:323664 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3665 observer->DidShowFullscreenWidget();
3666 });
[email protected]4aebbca2013-09-17 22:26:493667 if (!widget_host_view->HasFocus())
3668 widget_host_view->Focus();
3669 } else {
W. James MacLeanec4125c2019-09-27 18:56:003670 widget_host_view->InitAsPopup(view, transformed_rect);
[email protected]4aebbca2013-09-17 22:26:493671 }
[email protected]89054502012-06-03 10:29:243672
yiyixcb1fbc4f2018-03-16 19:54:083673 RenderWidgetHostImpl* render_widget_host_impl = widget_host_view->host();
[email protected]89054502012-06-03 10:29:243674 render_widget_host_impl->Init();
[email protected]d7f80ba2013-10-12 07:42:313675 // Only allow privileged mouse lock for fullscreen render widget, which is
3676 // used to implement Pepper Flash fullscreen.
3677 render_widget_host_impl->set_allow_privileged_mouse_lock(is_fullscreen);
[email protected]bafe6cd2012-05-23 23:09:503678}
3679
Joel Hockey8c2011b22020-04-30 05:07:193680base::Optional<CreatedWindow> WebContentsImpl::GetCreatedWindow(
nick5ae4d2d2017-01-06 01:18:353681 int process_id,
3682 int main_frame_widget_route_id) {
Lukasz Anforowicz09060bdf72018-08-23 15:53:173683 auto key = GlobalRoutingID(process_id, main_frame_widget_route_id);
nick5ae4d2d2017-01-06 01:18:353684 auto iter = pending_contents_.find(key);
[email protected]bafe6cd2012-05-23 23:09:503685
3686 // Certain systems can block the creation of new windows. If we didn't succeed
3687 // in creating one, just return NULL.
alexmosc2a8cec2016-05-23 22:19:533688 if (iter == pending_contents_.end())
Joel Hockey8c2011b22020-04-30 05:07:193689 return base::nullopt;
[email protected]bafe6cd2012-05-23 23:09:503690
Joel Hockey8c2011b22020-04-30 05:07:193691 CreatedWindow result = std::move(iter->second);
3692 WebContentsImpl* new_contents = result.contents.get();
nick5ae4d2d2017-01-06 01:18:353693 pending_contents_.erase(key);
Joel Hockey8c2011b22020-04-30 05:07:193694 RemoveDestructionObserver(new_contents);
[email protected]bafe6cd2012-05-23 23:09:503695
[email protected]d70bea92013-04-05 04:23:343696 // Don't initialize the guest WebContents immediately.
Joel Hockey8c2011b22020-04-30 05:07:193697 if (BrowserPluginGuest::IsGuest(new_contents))
3698 return result;
[email protected]d70bea92013-04-05 04:23:343699
Lukasz Anforowicz5510ed652018-06-06 16:16:193700 if (!new_contents->GetMainFrame()->GetProcess()->IsInitializedAndNotDead() ||
nick5ae4d2d2017-01-06 01:18:353701 !new_contents->GetMainFrame()->GetView()) {
Joel Hockey8c2011b22020-04-30 05:07:193702 return base::nullopt;
nick5ae4d2d2017-01-06 01:18:353703 }
[email protected]bafe6cd2012-05-23 23:09:503704
Joel Hockey8c2011b22020-04-30 05:07:193705 return result;
[email protected]bafe6cd2012-05-23 23:09:503706}
3707
alexmosc2a8cec2016-05-23 22:19:533708RenderWidgetHostView* WebContentsImpl::GetCreatedWidget(int process_id,
3709 int route_id) {
Lukasz Anforowicz09060bdf72018-08-23 15:53:173710 auto iter = pending_widget_views_.find(GlobalRoutingID(process_id, route_id));
[email protected]bafe6cd2012-05-23 23:09:503711 if (iter == pending_widget_views_.end()) {
3712 DCHECK(false);
alexmosc2a8cec2016-05-23 22:19:533713 return nullptr;
[email protected]bafe6cd2012-05-23 23:09:503714 }
3715
3716 RenderWidgetHostView* widget_host_view = iter->second;
Lukasz Anforowicz09060bdf72018-08-23 15:53:173717 pending_widget_views_.erase(GlobalRoutingID(process_id, route_id));
[email protected]bafe6cd2012-05-23 23:09:503718
3719 RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
Lukasz Anforowicz5510ed652018-06-06 16:16:193720 if (!widget_host->GetProcess()->IsInitializedAndNotDead()) {
[email protected]bafe6cd2012-05-23 23:09:503721 // The view has gone away or the renderer crashed. Nothing to do.
alexmosc2a8cec2016-05-23 22:19:533722 return nullptr;
[email protected]bafe6cd2012-05-23 23:09:503723 }
3724
3725 return widget_host_view;
3726}
3727
[email protected]f13b4202012-06-12 23:53:233728void WebContentsImpl::RequestMediaAccessPermission(
[email protected]33662e52013-01-07 21:31:093729 const MediaStreamRequest& request,
Mark Pilgrim57499082018-06-12 12:38:303730 MediaResponseCallback callback) {
[email protected]d19b84b2014-03-14 11:52:373731 if (delegate_) {
Mark Pilgrim57499082018-06-12 12:38:303732 delegate_->RequestMediaAccessPermission(this, request, std::move(callback));
[email protected]d19b84b2014-03-14 11:52:373733 } else {
Antonio Gomes0d42960a2019-06-05 12:35:513734 std::move(callback).Run(
3735 blink::MediaStreamDevices(),
3736 blink::mojom::MediaStreamRequestResult::FAILED_DUE_TO_SHUTDOWN,
3737 std::unique_ptr<MediaStreamUI>());
[email protected]d19b84b2014-03-14 11:52:373738 }
[email protected]f13b4202012-06-12 23:53:233739}
3740
Chandan Padhia4b8bcb72017-09-12 16:41:043741bool WebContentsImpl::CheckMediaAccessPermission(
Raymes Khouryad7c24a12018-03-05 23:22:583742 RenderFrameHost* render_frame_host,
Chandan Padhia4b8bcb72017-09-12 16:41:043743 const url::Origin& security_origin,
Antonio Gomesc8b734b2019-06-05 18:22:163744 blink::mojom::MediaStreamType type) {
3745 DCHECK(type == blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE ||
3746 type == blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE);
Chandan Padhia4b8bcb72017-09-12 16:41:043747 return delegate_ && delegate_->CheckMediaAccessPermission(
Raymes Khouryad7c24a12018-03-05 23:22:583748 render_frame_host, security_origin.GetURL(), type);
grunell657d4d82014-09-18 00:09:433749}
3750
Guido Urdaneta73fa6632019-01-14 18:46:263751std::string WebContentsImpl::GetDefaultMediaDeviceID(
Antonio Gomesc8b734b2019-06-05 18:22:163752 blink::mojom::MediaStreamType type) {
guidou8a440b842017-01-30 13:58:433753 if (!delegate_)
3754 return std::string();
3755 return delegate_->GetDefaultMediaDeviceID(this, type);
3756}
3757
[email protected]cc9200432013-07-23 23:02:403758SessionStorageNamespace* WebContentsImpl::GetSessionStorageNamespace(
3759 SiteInstance* instance) {
3760 return controller_.GetSessionStorageNamespace(instance);
3761}
3762
[email protected]6de7fc482014-06-06 10:46:443763SessionStorageNamespaceMap WebContentsImpl::GetSessionStorageNamespaceMap() {
3764 return controller_.GetSessionStorageNamespaceMap();
3765}
3766
[email protected]9b159a52013-10-03 17:24:553767FrameTree* WebContentsImpl::GetFrameTree() {
3768 return &frame_tree_;
3769}
3770
aelias5252baa2016-04-10 01:18:023771bool WebContentsImpl::IsOverridingUserAgent() {
3772 return GetController().GetVisibleEntry() &&
3773 GetController().GetVisibleEntry()->GetIsOverridingUserAgent();
3774}
3775
avi85ee8362016-10-08 02:09:083776bool WebContentsImpl::IsJavaScriptDialogShowing() const {
3777 return is_showing_javascript_dialog_;
3778}
3779
avic031d392017-03-03 03:09:423780bool WebContentsImpl::ShouldIgnoreUnresponsiveRenderer() {
Dominique Fauteux-Chapleau99244382020-07-08 20:37:003781 if (suppress_unresponsive_renderer_count_ > 0)
3782 return true;
3783
avic031d392017-03-03 03:09:423784 // Ignore unresponsive renderers if the debugger is attached to them since the
3785 // unresponsiveness might be a result of the renderer sitting on a breakpoint.
3786 //
David Bienvenu525f8a02019-02-15 02:02:423787#ifdef OS_WIN
3788 // Check if a windows debugger is attached to the renderer process.
3789 base::ProcessHandle process_handle =
3790 GetMainFrame()->GetProcess()->GetProcess().Handle();
3791 BOOL debugger_present = FALSE;
3792 if (CheckRemoteDebuggerPresent(process_handle, &debugger_present) &&
3793 debugger_present)
3794 return true;
3795#endif // OS_WIN
3796
avic031d392017-03-03 03:09:423797 // TODO(pfeldman): Fix this to only return true if the renderer is *actually*
3798 // sitting on a breakpoint. https://crbug.com/684202
3799 return DevToolsAgentHost::IsDebuggerAttached(this);
3800}
3801
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:413802ui::AXMode WebContentsImpl::GetAccessibilityMode() {
[email protected]95640212014-07-26 18:14:303803 return accessibility_mode_;
3804}
3805
Mario Sanchez Prada5d7f1ac2020-07-16 17:18:403806void WebContentsImpl::AXTreeIDForMainFrameHasChanged() {
3807 RenderWidgetHostViewBase* rwhv =
3808 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
3809 if (rwhv)
3810 rwhv->SetMainFrameAXTreeID(GetMainFrame()->GetAXTreeID());
3811
Alexander Timin90c20c32020-08-12 15:28:323812 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3813 observer->AXTreeIDForMainFrameHasChanged();
3814 });
Mario Sanchez Prada5d7f1ac2020-07-16 17:18:403815}
3816
Dominic Mazzonia7b0edb22017-08-09 16:32:513817void WebContentsImpl::AccessibilityEventReceived(
Dominic Mazzoniccbaa9b2018-06-06 07:44:233818 const AXEventNotificationDetails& details) {
Alexander Timin90c20c32020-08-12 15:28:323819 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3820 observer->AccessibilityEventReceived(details);
3821 });
[email protected]31a71eaf2014-03-13 01:47:363822}
3823
dmazzoni2400c462016-08-23 15:07:133824void WebContentsImpl::AccessibilityLocationChangesReceived(
3825 const std::vector<AXLocationChangeNotificationDetails>& details) {
Alexander Timin90c20c32020-08-12 15:28:323826 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3827 observer->AccessibilityLocationChangesReceived(details);
3828 });
dmazzoni2400c462016-08-23 15:07:133829}
3830
Abigail Kleinabb428332019-09-13 18:26:213831base::string16 WebContentsImpl::DumpAccessibilityTree(
3832 bool internal,
3833 std::vector<AccessibilityTreeFormatter::PropertyFilter> property_filters) {
James Wallace-Leeeafc94cb92018-07-23 21:35:093834 auto* ax_mgr = GetOrCreateRootBrowserAccessibilityManager();
3835 DCHECK(ax_mgr);
Lei Zhangc98caa3822019-11-07 19:17:273836 return AccessibilityTreeFormatterBase::DumpAccessibilityTreeFromManager(
Abigail Kleinabb428332019-09-13 18:26:213837 ax_mgr, internal, property_filters);
James Wallace-Leeeafc94cb92018-07-23 21:35:093838}
3839
Abigail Kleinaa898742019-11-01 02:31:253840void WebContentsImpl::RecordAccessibilityEvents(
Abigail Kleinbb8304bd2020-05-18 21:44:183841 bool start_recording,
3842 base::Optional<AccessibilityEventCallback> callback) {
3843 // Only pass a callback to RecordAccessibilityEvents when starting to record.
3844 DCHECK_EQ(start_recording, callback.has_value());
3845 if (start_recording) {
Abigail Kleinaa898742019-11-01 02:31:253846 SetAccessibilityMode(ui::AXMode::kWebContents);
3847 auto* ax_mgr = GetOrCreateRootBrowserAccessibilityManager();
3848 DCHECK(ax_mgr);
3849 base::ProcessId pid = base::Process::Current().Pid();
3850 event_recorder_ = content::AccessibilityEventRecorder::Create(
3851 ax_mgr, pid, base::StringPiece{});
Abigail Kleinbb8304bd2020-05-18 21:44:183852 event_recorder_->ListenToEvents(*callback);
Abigail Kleinaa898742019-11-01 02:31:253853 } else {
Abigail Kleinbb8304bd2020-05-18 21:44:183854 if (event_recorder_) {
3855 event_recorder_->FlushAsyncEvents();
3856 event_recorder_.reset(nullptr);
3857 }
Abigail Kleinaa898742019-11-01 02:31:253858 }
3859}
3860
dmazzonia656928e2014-09-15 20:28:543861RenderFrameHost* WebContentsImpl::GetGuestByInstanceID(
fsamuel833ee7c2015-02-13 23:40:403862 RenderFrameHost* render_frame_host,
dmazzonia656928e2014-09-15 20:28:543863 int browser_plugin_instance_id) {
3864 BrowserPluginGuestManager* guest_manager =
3865 GetBrowserContext()->GetGuestManager();
fsamuel9cbc00a2015-04-17 20:30:203866 if (!guest_manager)
3867 return nullptr;
3868
dmazzonia656928e2014-09-15 20:28:543869 WebContents* guest = guest_manager->GetGuestByInstanceID(
fsamuel2e9413d2015-02-25 01:25:443870 render_frame_host->GetProcess()->GetID(), browser_plugin_instance_id);
dmazzonia656928e2014-09-15 20:28:543871 if (!guest)
fsamuel9cbc00a2015-04-17 20:30:203872 return nullptr;
3873
dmazzonia656928e2014-09-15 20:28:543874 return guest->GetMainFrame();
3875}
3876
Ke He7319dbe2017-11-09 05:54:443877device::mojom::GeolocationContext* WebContentsImpl::GetGeolocationContext() {
Ella Ge3e375b702020-06-05 15:57:163878 if (delegate_) {
3879 auto* installed_webapp_context =
3880 delegate_->GetInstalledWebappGeolocationContext();
3881 if (installed_webapp_context)
3882 return installed_webapp_context;
3883 }
3884
Ken Rockotce010f02019-12-12 23:32:323885 if (!geolocation_context_) {
3886 GetDeviceService().BindGeolocationContext(
3887 geolocation_context_.BindNewPipeAndPassReceiver());
3888 }
Conley Owens6894c4f2017-07-10 19:29:133889 return geolocation_context_.get();
blundellc57b93f2014-10-29 13:19:573890}
3891
ke.he98b761e2017-05-09 05:59:173892device::mojom::WakeLockContext* WebContentsImpl::GetWakeLockContext() {
blundelld8cd72b2017-03-28 07:18:383893 if (!wake_lock_context_host_)
3894 wake_lock_context_host_.reset(new WakeLockContextHost(this));
blundelle75a8f92017-03-27 08:11:173895 return wake_lock_context_host_->GetWakeLockContext();
alogvinovf50445a2015-10-30 13:00:123896}
3897
blundellf5316fc2017-05-15 11:49:033898#if defined(OS_ANDROID)
Miyoung Shin59f39ff2019-09-17 07:23:203899void WebContentsImpl::GetNFC(
Reilly Grantafbe2242020-02-20 21:14:553900 RenderFrameHost* render_frame_host,
Miyoung Shin59f39ff2019-09-17 07:23:203901 mojo::PendingReceiver<device::mojom::NFC> receiver) {
Reilly Grantafbe2242020-02-20 21:14:553902 if (!nfc_host_)
3903 nfc_host_ = std::make_unique<NFCHost>(this);
3904 nfc_host_->GetNFC(render_frame_host, std::move(receiver));
blundellf5316fc2017-05-15 11:49:033905}
3906#endif
3907
Evan Stade5e750ad02017-08-07 21:59:273908void WebContentsImpl::SetNotWaitingForResponse() {
3909 if (waiting_for_response_ == false)
3910 return;
3911
3912 waiting_for_response_ = false;
3913 if (delegate_)
3914 delegate_->LoadingStateChanged(this, is_load_to_different_document_);
Alexander Timin90c20c32020-08-12 15:28:323915 observers_.ForEachObserver(
3916 [&](WebContentsObserver* observer) { observer->DidReceiveResponse(); });
Evan Stade5e750ad02017-08-07 21:59:273917}
3918
lfgbb9c28a2016-03-01 03:19:493919void WebContentsImpl::SendScreenRects() {
kenrbc52e1b4e2016-03-20 01:03:373920 for (FrameTreeNode* node : frame_tree_.Nodes()) {
kenrb0e8dc202016-05-30 19:51:403921 if (node->current_frame_host()->is_local_root())
kenrbc52e1b4e2016-03-20 01:03:373922 node->current_frame_host()->GetRenderWidgetHost()->SendScreenRects();
3923 }
[email protected]32deec62013-05-15 23:55:043924}
3925
ekaramadadd882292016-06-08 15:22:563926TextInputManager* WebContentsImpl::GetTextInputManager() {
3927 if (GetOuterWebContents())
3928 return GetOuterWebContents()->GetTextInputManager();
3929
Ehsan Karamadc179dc02018-12-15 03:09:293930 if (!text_input_manager_ && !browser_plugin_guest_) {
Darren Shenca53d5f2018-05-15 04:56:013931 text_input_manager_.reset(new TextInputManager(
3932 GetBrowserContext() &&
3933 !GetBrowserContext()->IsOffTheRecord()) /* should_do_learning */);
3934 }
ekaramadadd882292016-06-08 15:22:563935
3936 return text_input_manager_.get();
3937}
3938
paulmeyer7f6f1d4f2016-11-15 00:00:273939bool WebContentsImpl::OnUpdateDragCursor() {
Lei Zhang6410ec1a2019-01-31 21:38:583940 return browser_plugin_embedder_ &&
3941 browser_plugin_embedder_->OnUpdateDragCursor();
paulmeyer7f6f1d4f2016-11-15 00:00:273942}
3943
kenrb11f213a2017-03-24 18:12:063944bool WebContentsImpl::IsWidgetForMainFrame(
3945 RenderWidgetHostImpl* render_widget_host) {
3946 return render_widget_host == GetMainFrame()->GetRenderWidgetHost();
3947}
3948
[email protected]95640212014-07-26 18:14:303949BrowserAccessibilityManager*
3950 WebContentsImpl::GetRootBrowserAccessibilityManager() {
Carlos ILd51e7702020-05-07 18:51:393951 RenderFrameHostImpl* rfh = static_cast<RenderFrameHostImpl*>(GetMainFrame());
creisc014b402015-04-23 16:41:453952 return rfh ? rfh->browser_accessibility_manager() : nullptr;
[email protected]95640212014-07-26 18:14:303953}
3954
3955BrowserAccessibilityManager*
3956 WebContentsImpl::GetOrCreateRootBrowserAccessibilityManager() {
Carlos ILd51e7702020-05-07 18:51:393957 RenderFrameHostImpl* rfh = static_cast<RenderFrameHostImpl*>(GetMainFrame());
creisc014b402015-04-23 16:41:453958 return rfh ? rfh->GetOrCreateBrowserAccessibilityManager() : nullptr;
[email protected]95640212014-07-26 18:14:303959}
3960
Dave Tapuskab336b922017-07-06 19:24:053961void WebContentsImpl::ExecuteEditCommand(
3962 const std::string& command,
3963 const base::Optional<base::string16>& value) {
Dave Tapuska58a099e2020-06-08 21:48:403964 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:513965 if (!input_handler)
Dave Tapuskab336b922017-07-06 19:24:053966 return;
3967
Dave Tapuskae782bea2019-07-09 16:21:513968 input_handler->ExecuteEditCommand(command, value);
Dave Tapuskab336b922017-07-06 19:24:053969}
3970
mohsen7ab1ec16ec2015-07-02 18:26:233971void WebContentsImpl::MoveRangeSelectionExtent(const gfx::Point& extent) {
Dave Tapuska58a099e2020-06-08 21:48:403972 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:513973 if (!input_handler)
mohsen7ab1ec16ec2015-07-02 18:26:233974 return;
3975
Dave Tapuskae782bea2019-07-09 16:21:513976 input_handler->MoveRangeSelectionExtent(extent);
mohsen7ab1ec16ec2015-07-02 18:26:233977}
3978
3979void WebContentsImpl::SelectRange(const gfx::Point& base,
3980 const gfx::Point& extent) {
Dave Tapuska58a099e2020-06-08 21:48:403981 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:513982 if (!input_handler)
mohsen7ab1ec16ec2015-07-02 18:26:233983 return;
3984
Dave Tapuskae782bea2019-07-09 16:21:513985 input_handler->SelectRange(base, extent);
mohsen7ab1ec16ec2015-07-02 18:26:233986}
3987
Dave Tapuskab336b922017-07-06 19:24:053988void WebContentsImpl::MoveCaret(const gfx::Point& extent) {
Dave Tapuska58a099e2020-06-08 21:48:403989 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:513990 if (!input_handler)
Dave Tapuskab336b922017-07-06 19:24:053991 return;
3992
Dave Tapuskae782bea2019-07-09 16:21:513993 input_handler->MoveCaret(extent);
Dave Tapuskab336b922017-07-06 19:24:053994}
3995
Shimi Zhang37deeb22017-09-28 00:59:013996void WebContentsImpl::AdjustSelectionByCharacterOffset(
3997 int start_adjust,
3998 int end_adjust,
3999 bool show_selection_menu) {
Dave Tapuska58a099e2020-06-08 21:48:404000 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514001 if (!input_handler)
aurimasab0319022015-07-10 21:57:384002 return;
4003
Shimi Zhang37deeb22017-09-28 00:59:014004 using blink::mojom::SelectionMenuBehavior;
Dave Tapuskae782bea2019-07-09 16:21:514005 input_handler->AdjustSelectionByCharacterOffset(
Shimi Zhang37deeb22017-09-28 00:59:014006 start_adjust, end_adjust,
4007 show_selection_menu ? SelectionMenuBehavior::kShow
4008 : SelectionMenuBehavior::kHide);
aurimasab0319022015-07-10 21:57:384009}
4010
[email protected]b172aee2012-04-10 17:05:264011void WebContentsImpl::UpdatePreferredSize(const gfx::Size& pref_size) {
[email protected]222f5822014-02-05 23:40:494012 const gfx::Size old_size = GetPreferredSize();
[email protected]bcd2815602012-01-14 18:17:234013 preferred_size_ = pref_size;
[email protected]222f5822014-02-05 23:40:494014 OnPreferredSizeChanged(old_size);
[email protected]0548c5352011-09-07 00:33:334015}
4016
avic3aa8422015-11-09 20:57:224017void WebContentsImpl::ResizeDueToAutoResize(
4018 RenderWidgetHostImpl* render_widget_host,
Fady Samuel97947112018-05-05 16:24:544019 const gfx::Size& new_size) {
avic3aa8422015-11-09 20:57:224020 if (render_widget_host != GetRenderViewHost()->GetWidget())
4021 return;
4022
[email protected]61e2b3cc2012-03-02 16:13:344023 if (delegate_)
4024 delegate_->ResizeDueToAutoResize(this, new_size);
4025}
4026
[email protected]b172aee2012-04-10 17:05:264027WebContents* WebContentsImpl::OpenURL(const OpenURLParams& params) {
Aaron Colwell9dab1652019-12-09 18:29:494028#if DCHECK_IS_ON()
4029 DCHECK(params.Valid());
4030#endif
4031
Bo Liu300c6052018-06-12 04:46:074032 if (!delegate_) {
4033 // Embedder can delay setting a delegate on new WebContents with
4034 // WebContentsDelegate::ShouldResumeRequestsForCreatedWindow. In the mean
4035 // time, navigations, including the initial one, that goes through OpenURL
4036 // should be delayed until embedder is ready to resume loading.
4037 delayed_open_url_params_ = std::make_unique<OpenURLParams>(params);
Nasko Oskov83a8cf92018-10-19 14:58:564038
4039 // If there was a navigation deferred when creating the window through
4040 // CreateNewWindow, drop it in favor of this navigation.
4041 delayed_load_url_params_.reset();
4042
Ivan Kotenkov2c0d2bb32017-11-01 15:41:284043 return nullptr;
Bo Liu300c6052018-06-12 04:46:074044 }
[email protected]00c37fc2011-08-02 00:22:504045
[email protected]e5d549d2011-12-28 01:29:204046 WebContents* new_contents = delegate_->OpenURLFromTab(this, params);
pnoland488944652017-02-22 18:58:544047
4048 RenderFrameHost* source_render_frame_host = RenderFrameHost::FromID(
4049 params.source_render_process_id, params.source_render_frame_id);
4050
4051 if (source_render_frame_host && params.source_site_instance) {
4052 CHECK_EQ(source_render_frame_host->GetSiteInstance(),
4053 params.source_site_instance.get());
4054 }
4055
4056 if (new_contents && source_render_frame_host && new_contents != this) {
Alexander Timin90c20c32020-08-12 15:28:324057 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4058 observer->DidOpenRequestedURL(
Lukasz Anforowicz48c9f872018-08-01 00:58:414059 new_contents, source_render_frame_host, params.url, params.referrer,
4060 params.disposition, params.transition,
4061 params.started_from_context_menu, params.is_renderer_initiated);
Alexander Timin90c20c32020-08-12 15:28:324062 });
pnoland488944652017-02-22 18:58:544063 }
4064
[email protected]e5d549d2011-12-28 01:29:204065 return new_contents;
[email protected]d5f942ba2008-09-26 19:30:344066}
4067
avi2b177592014-12-10 02:08:024068void WebContentsImpl::SetHistoryOffsetAndLength(int history_offset,
4069 int history_length) {
alexmos136fd6e62016-08-15 20:58:414070 SendPageMessage(new PageMsg_SetHistoryOffsetAndLength(
4071 MSG_ROUTING_NONE, history_offset, history_length));
avi2b177592014-12-10 02:08:024072}
4073
4074void WebContentsImpl::SetHistoryOffsetAndLengthForView(
4075 RenderViewHost* render_view_host,
4076 int history_offset,
4077 int history_length) {
alexmos136fd6e62016-08-15 20:58:414078 render_view_host->Send(new PageMsg_SetHistoryOffsetAndLength(
avi2b177592014-12-10 02:08:024079 render_view_host->GetRoutingID(), history_offset, history_length));
[email protected]796931a92011-08-10 01:32:144080}
4081
arthursonzogni818c2642019-09-27 12:18:104082void WebContentsImpl::ReloadFocusedFrame() {
[email protected]1f3fc1d2014-04-03 14:50:174083 RenderFrameHost* focused_frame = GetFocusedFrame();
4084 if (!focused_frame)
4085 return;
4086
yilkal921048bd2019-10-09 23:51:044087 focused_frame->Reload();
[email protected]959be4c2014-04-08 15:01:334088}
4089
4090void WebContentsImpl::Undo() {
Dave Tapuska58a099e2020-06-08 21:48:404091 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514092 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334093 return;
4094
Dave Tapuskae782bea2019-07-09 16:21:514095 input_handler->Undo();
[email protected]959be4c2014-04-08 15:01:334096 RecordAction(base::UserMetricsAction("Undo"));
4097}
4098
4099void WebContentsImpl::Redo() {
Dave Tapuska58a099e2020-06-08 21:48:404100 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514101 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334102 return;
Dave Tapuskae782bea2019-07-09 16:21:514103
4104 input_handler->Redo();
[email protected]959be4c2014-04-08 15:01:334105 RecordAction(base::UserMetricsAction("Redo"));
4106}
4107
4108void WebContentsImpl::Cut() {
Dave Tapuska58a099e2020-06-08 21:48:404109 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514110 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334111 return;
4112
Dave Tapuskae782bea2019-07-09 16:21:514113 input_handler->Cut();
[email protected]959be4c2014-04-08 15:01:334114 RecordAction(base::UserMetricsAction("Cut"));
4115}
4116
4117void WebContentsImpl::Copy() {
Dave Tapuska58a099e2020-06-08 21:48:404118 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514119 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334120 return;
4121
Dave Tapuskae782bea2019-07-09 16:21:514122 input_handler->Copy();
[email protected]959be4c2014-04-08 15:01:334123 RecordAction(base::UserMetricsAction("Copy"));
4124}
4125
4126void WebContentsImpl::CopyToFindPboard() {
Avi Drissman7c57be72020-07-29 20:09:464127#if defined(OS_MAC)
Dave Tapuska58a099e2020-06-08 21:48:404128 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514129 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334130 return;
4131
4132 // Windows/Linux don't have the concept of a find pasteboard.
Dave Tapuskae782bea2019-07-09 16:21:514133 input_handler->CopyToFindPboard();
[email protected]959be4c2014-04-08 15:01:334134 RecordAction(base::UserMetricsAction("CopyToFindPboard"));
4135#endif
4136}
4137
4138void WebContentsImpl::Paste() {
Dave Tapuska58a099e2020-06-08 21:48:404139 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514140 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334141 return;
4142
Dave Tapuskae782bea2019-07-09 16:21:514143 input_handler->Paste();
Alexander Timin90c20c32020-08-12 15:28:324144 observers_.ForEachObserver(
4145 [&](WebContentsObserver* observer) { observer->OnPaste(); });
[email protected]959be4c2014-04-08 15:01:334146 RecordAction(base::UserMetricsAction("Paste"));
4147}
4148
4149void WebContentsImpl::PasteAndMatchStyle() {
Dave Tapuska58a099e2020-06-08 21:48:404150 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514151 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334152 return;
4153
Dave Tapuskae782bea2019-07-09 16:21:514154 input_handler->PasteAndMatchStyle();
Alexander Timin90c20c32020-08-12 15:28:324155 observers_.ForEachObserver(
4156 [&](WebContentsObserver* observer) { observer->OnPaste(); });
[email protected]959be4c2014-04-08 15:01:334157 RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
4158}
4159
4160void WebContentsImpl::Delete() {
Dave Tapuska58a099e2020-06-08 21:48:404161 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514162 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334163 return;
4164
Dave Tapuskae782bea2019-07-09 16:21:514165 input_handler->Delete();
[email protected]959be4c2014-04-08 15:01:334166 RecordAction(base::UserMetricsAction("DeleteSelection"));
4167}
4168
4169void WebContentsImpl::SelectAll() {
Dave Tapuska58a099e2020-06-08 21:48:404170 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514171 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334172 return;
4173
Dave Tapuskae782bea2019-07-09 16:21:514174 input_handler->SelectAll();
[email protected]959be4c2014-04-08 15:01:334175 RecordAction(base::UserMetricsAction("SelectAll"));
4176}
4177
yabinh351e7ec2017-03-10 02:43:244178void WebContentsImpl::CollapseSelection() {
Dave Tapuska58a099e2020-06-08 21:48:404179 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514180 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334181 return;
4182
Dave Tapuskae782bea2019-07-09 16:21:514183 input_handler->CollapseSelection();
[email protected]1f3fc1d2014-04-03 14:50:174184}
4185
4186void WebContentsImpl::Replace(const base::string16& word) {
Dave Tapuska58a099e2020-06-08 21:48:404187 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514188 if (!input_handler)
[email protected]1f3fc1d2014-04-03 14:50:174189 return;
4190
Dave Tapuskae782bea2019-07-09 16:21:514191 input_handler->Replace(word);
[email protected]1f3fc1d2014-04-03 14:50:174192}
4193
4194void WebContentsImpl::ReplaceMisspelling(const base::string16& word) {
Dave Tapuska58a099e2020-06-08 21:48:404195 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514196 if (!input_handler)
[email protected]1f3fc1d2014-04-03 14:50:174197 return;
4198
Dave Tapuskae782bea2019-07-09 16:21:514199 input_handler->ReplaceMisspelling(word);
[email protected]959be4c2014-04-08 15:01:334200}
4201
4202void WebContentsImpl::NotifyContextMenuClosed(
4203 const CustomContextMenuContext& context) {
4204 RenderFrameHost* focused_frame = GetFocusedFrame();
4205 if (!focused_frame)
4206 return;
4207
4208 focused_frame->Send(new FrameMsg_ContextMenuClosed(
4209 focused_frame->GetRoutingID(), context));
4210}
4211
4212void WebContentsImpl::ExecuteCustomContextMenuCommand(
4213 int action, const CustomContextMenuContext& context) {
4214 RenderFrameHost* focused_frame = GetFocusedFrame();
4215 if (!focused_frame)
4216 return;
4217
4218 focused_frame->Send(new FrameMsg_CustomContextMenuAction(
4219 focused_frame->GetRoutingID(), context, action));
[email protected]4fed3702014-04-01 09:08:004220}
4221
[email protected]fc2b46b2014-05-03 16:33:454222gfx::NativeView WebContentsImpl::GetNativeView() {
4223 return view_->GetNativeView();
4224}
4225
4226gfx::NativeView WebContentsImpl::GetContentNativeView() {
4227 return view_->GetContentNativeView();
4228}
4229
4230gfx::NativeWindow WebContentsImpl::GetTopLevelNativeWindow() {
4231 return view_->GetTopLevelNativeWindow();
4232}
4233
4234gfx::Rect WebContentsImpl::GetViewBounds() {
4235 return view_->GetViewBounds();
4236}
4237
4238gfx::Rect WebContentsImpl::GetContainerBounds() {
Jeremy Roman352239c2020-05-21 16:31:324239 return view_->GetContainerBounds();
[email protected]fc2b46b2014-05-03 16:33:454240}
4241
4242DropData* WebContentsImpl::GetDropData() {
4243 return view_->GetDropData();
4244}
4245
4246void WebContentsImpl::Focus() {
miu9e14e492014-10-25 02:39:044247 view_->Focus();
[email protected]fc2b46b2014-05-03 16:33:454248}
4249
4250void WebContentsImpl::SetInitialFocus() {
miu9e14e492014-10-25 02:39:044251 view_->SetInitialFocus();
[email protected]fc2b46b2014-05-03 16:33:454252}
4253
4254void WebContentsImpl::StoreFocus() {
miu9e14e492014-10-25 02:39:044255 view_->StoreFocus();
[email protected]fc2b46b2014-05-03 16:33:454256}
4257
4258void WebContentsImpl::RestoreFocus() {
miu9e14e492014-10-25 02:39:044259 view_->RestoreFocus();
[email protected]fc2b46b2014-05-03 16:33:454260}
4261
[email protected]b172aee2012-04-10 17:05:264262void WebContentsImpl::FocusThroughTabTraversal(bool reverse) {
Maxim Podgorodskiya926c4ff2017-11-20 02:06:394263 view_->FocusThroughTabTraversal(reverse);
[email protected]96d185d2009-04-24 03:28:544264}
4265
[email protected]b172aee2012-04-10 17:05:264266bool WebContentsImpl::IsSavable() {
[email protected]a53209b2012-01-20 16:48:164267 // WebKit creates Document object when MIME type is application/xhtml+xml,
4268 // so we also support this MIME type.
Yuzu Saijoc23e9b72020-06-25 07:21:274269 std::string mime_type = GetContentsMimeType();
4270 return mime_type == "text/html" || mime_type == "text/xml" ||
4271 mime_type == "application/xhtml+xml" || mime_type == "text/plain" ||
4272 mime_type == "text/css" ||
4273 blink::IsSupportedJavascriptMimeType(mime_type);
[email protected]a53209b2012-01-20 16:48:164274}
4275
[email protected]b172aee2012-04-10 17:05:264276void WebContentsImpl::OnSavePage() {
[email protected]c7dd2f62011-07-18 15:57:594277 // If we can not save the page, try to download it.
[email protected]a53209b2012-01-20 16:48:164278 if (!IsSavable()) {
Min Qinda0ed2062018-02-23 22:00:534279 download::RecordSavePackageEvent(
4280 download::SAVE_PACKAGE_DOWNLOAD_ON_NON_HTML);
nasko89ad7742015-03-05 22:14:194281 SaveFrame(GetLastCommittedURL(), Referrer());
[email protected]27678b2a2012-02-04 22:09:144282 return;
[email protected]c7dd2f62011-07-18 15:57:594283 }
4284
4285 Stop();
4286
4287 // Create the save package and possibly prompt the user for the name to save
4288 // the page as. The user prompt is an asynchronous operation that runs on
4289 // another thread.
4290 save_package_ = new SavePackage(this);
4291 save_package_->GetSaveInfo();
4292}
4293
4294// Used in automated testing to bypass prompting the user for file names.
4295// Instead, the names and paths are hard coded rather than running them through
4296// file name sanitation and extension / mime checking.
[email protected]2dec8ec2013-02-07 19:20:344297bool WebContentsImpl::SavePage(const base::FilePath& main_file,
4298 const base::FilePath& dir_path,
[email protected]8ff00d72012-10-23 19:12:214299 SavePageType save_type) {
[email protected]c7dd2f62011-07-18 15:57:594300 // Stop the page from navigating.
4301 Stop();
4302
4303 save_package_ = new SavePackage(this, save_type, main_file, dir_path);
[email protected]8ff00d72012-10-23 19:12:214304 return save_package_->Init(SavePackageDownloadCreatedCallback());
[email protected]c7dd2f62011-07-18 15:57:594305}
4306
[email protected]3c71576ce2013-07-23 02:00:014307void WebContentsImpl::SaveFrame(const GURL& url,
4308 const Referrer& referrer) {
Xing Liu10329bf2018-03-20 19:22:144309 SaveFrameWithHeaders(url, referrer, std::string(), base::string16());
kundaji6c7f9692015-03-09 18:00:374310}
4311
Xing Liu10329bf2018-03-20 19:22:144312void WebContentsImpl::SaveFrameWithHeaders(
4313 const GURL& url,
4314 const Referrer& referrer,
4315 const std::string& headers,
4316 const base::string16& suggested_filename) {
Lei Zhang13a42e42019-02-19 23:28:114317 // Check and see if the guest can handle this.
4318 if (delegate_) {
4319 WebContents* guest_web_contents = nullptr;
4320 if (browser_plugin_embedder_) {
4321 BrowserPluginGuest* guest = browser_plugin_embedder_->GetFullPageGuest();
4322 if (guest)
4323 guest_web_contents = guest->GetWebContents();
4324 } else if (browser_plugin_guest_) {
4325 guest_web_contents = this;
4326 }
4327
4328 if (guest_web_contents && delegate_->GuestSaveFrame(guest_web_contents))
4329 return;
4330 }
4331
nasko89ad7742015-03-05 22:14:194332 if (!GetLastCommittedURL().is_valid())
[email protected]3c71576ce2013-07-23 02:00:014333 return;
sammc92af61552014-11-19 23:27:404334 if (delegate_ && delegate_->SaveFrame(url, referrer))
4335 return;
4336
nasko89ad7742015-03-05 22:14:194337 // TODO(nasko): This check for main frame is incorrect and should be fixed
brettw760f7442016-05-23 21:19:224338 // by explicitly passing in which frame this method should target. This would
4339 // indicate whether it's the main frame, and also tell us the frame pointer
4340 // to use for routing.
nasko89ad7742015-03-05 22:14:194341 bool is_main_frame = (url == GetLastCommittedURL());
brettw760f7442016-05-23 21:19:224342 RenderFrameHost* frame_host = GetMainFrame();
[email protected]3c71576ce2013-07-23 02:00:014343
avib7348942015-12-25 20:57:104344 int64_t post_id = -1;
[email protected]3c71576ce2013-07-23 02:00:014345 if (is_main_frame) {
Lucas Furukawa Gadani5553a152019-01-08 18:55:574346 NavigationEntry* entry = controller_.GetLastCommittedEntry();
[email protected]3c71576ce2013-07-23 02:00:014347 if (entry)
4348 post_id = entry->GetPostID();
4349 }
Ramin Halavati24e21012017-07-10 12:56:064350 net::NetworkTrafficAnnotationTag traffic_annotation =
4351 net::DefineNetworkTrafficAnnotation("download_web_contents_frame", R"(
4352 semantics {
4353 sender: "Save Page Action"
4354 description:
4355 "Saves the given frame's URL to the local file system."
4356 trigger:
4357 "The user has triggered a save operation on the frame through a "
4358 "context menu or other mechanism."
4359 data: "None."
4360 destination: WEBSITE
4361 }
4362 policy {
Ramin Halavati3b979782017-07-21 11:40:264363 cookies_allowed: YES
Ramin Halavati24e21012017-07-10 12:56:064364 cookies_store: "user"
4365 setting:
4366 "This feature cannot be disabled by settings, but it's is only "
4367 "triggered by user request."
4368 policy_exception_justification: "Not implemented."
4369 })");
Min Qina904f3302018-02-13 23:33:344370 auto params = std::make_unique<download::DownloadUrlParameters>(
brettw760f7442016-05-23 21:19:224371 url, frame_host->GetProcess()->GetID(),
4372 frame_host->GetRenderViewHost()->GetRoutingID(),
Matt Menke0dcaebc32020-03-06 17:00:104373 frame_host->GetRoutingID(), traffic_annotation);
Min Qina904f3302018-02-13 23:33:344374 params->set_referrer(referrer.url);
4375 params->set_referrer_policy(
4376 Referrer::ReferrerPolicyForUrlRequest(referrer.policy));
[email protected]3c71576ce2013-07-23 02:00:014377 params->set_post_id(post_id);
[email protected]3c71576ce2013-07-23 02:00:014378 if (post_id >= 0)
4379 params->set_method("POST");
4380 params->set_prompt(true);
kundaji6c7f9692015-03-09 18:00:374381
4382 if (headers.empty()) {
4383 params->set_prefer_cache(true);
4384 } else {
Min Qina904f3302018-02-13 23:33:344385 for (download::DownloadUrlParameters::RequestHeadersNameValuePair
4386 key_value : ParseDownloadHeaders(headers)) {
Megan Jablonski2f6a4c52017-07-10 23:01:254387 params->add_request_header(key_value.first, key_value.second);
kundaji6c7f9692015-03-09 18:00:374388 }
4389 }
Xing Liu10329bf2018-03-20 19:22:144390 params->set_suggested_name(suggested_filename);
Min Qin0ca8e1ee2018-01-31 00:49:354391 params->set_download_source(download::DownloadSource::WEB_CONTENTS_API);
thestig859c78892017-05-15 21:17:064392 BrowserContext::GetDownloadManager(GetBrowserContext())
Ramin Halavati03efa732017-06-12 09:28:204393 ->DownloadUrl(std::move(params));
[email protected]3c71576ce2013-07-23 02:00:014394}
4395
[email protected]b172aee2012-04-10 17:05:264396void WebContentsImpl::GenerateMHTML(
dewittj6dc5747a2016-05-17 01:48:474397 const MHTMLGenerationParams& params,
Avi Drissman149b7832018-03-23 14:31:494398 base::OnceCallback<void(int64_t)> callback) {
Angel Alvarez902496682019-08-27 22:58:424399 base::OnceCallback<void(const MHTMLGenerationResult&)> wrapper_callback =
4400 base::BindOnce(
4401 [](base::OnceCallback<void(int64_t)> size_callback,
4402 const MHTMLGenerationResult& result) {
4403 std::move(size_callback).Run(result.file_size);
4404 },
4405 std::move(callback));
4406 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, params,
4407 std::move(wrapper_callback));
4408}
4409
4410void WebContentsImpl::GenerateMHTMLWithResult(
4411 const MHTMLGenerationParams& params,
4412 MHTMLGenerationResult::GenerateMHTMLCallback callback) {
Avi Drissman149b7832018-03-23 14:31:494413 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, params,
4414 std::move(callback));
[email protected]aa4f3972012-03-01 18:12:124415}
4416
Tsuyoshi Horob0d8d902020-03-12 00:09:394417void WebContentsImpl::GenerateWebBundle(
4418 const base::FilePath& file_path,
4419 base::OnceCallback<void(uint64_t /* file_size */,
4420 data_decoder::mojom::WebBundlerError)> callback) {
4421 SaveAsWebBundleJob::Start(this, file_path, std::move(callback));
4422}
4423
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414424const std::string& WebContentsImpl::GetContentsMimeType() {
Yuzu Saijoc23e9b72020-06-25 07:21:274425 return GetRenderViewHost()->contents_mime_type();
[email protected]0bfbf882011-12-22 18:19:274426}
4427
Leon Hanc819dc62019-01-28 04:30:194428blink::mojom::RendererPreferences* WebContentsImpl::GetMutableRendererPrefs() {
[email protected]0bfbf882011-12-22 18:19:274429 return &renderer_preferences_;
4430}
4431
[email protected]e35ccd52012-05-23 16:22:474432void WebContentsImpl::Close() {
4433 Close(GetRenderViewHost());
4434}
4435
Ella Ge80a52dce2017-11-15 18:01:524436void WebContentsImpl::DragSourceEndedAt(float client_x,
4437 float client_y,
4438 float screen_x,
4439 float screen_y,
Paul Meyer0c58c3712016-11-17 22:59:514440 blink::WebDragOperation operation,
4441 RenderWidgetHost* source_rwh) {
Lei Zhang6410ec1a2019-01-31 21:38:584442 if (browser_plugin_embedder_) {
W. James MacLean9437b5bf2019-12-06 17:33:444443 browser_plugin_embedder_->DragSourceEndedAt(client_x, client_y, screen_x,
4444 screen_y, operation);
Lei Zhang6410ec1a2019-01-31 21:38:584445 }
Paul Meyer0c58c3712016-11-17 22:59:514446 if (source_rwh) {
Ella Ge80a52dce2017-11-15 18:01:524447 source_rwh->DragSourceEndedAt(gfx::PointF(client_x, client_y),
4448 gfx::PointF(screen_x, screen_y), operation);
Paul Meyer0c58c3712016-11-17 22:59:514449 }
[email protected]cf200a562013-05-03 16:24:294450}
4451
jam73f892642016-09-11 06:04:064452void WebContentsImpl::LoadStateChanged(
Charles Harrison911fa062018-03-06 21:01:464453 const std::string& host,
jam73f892642016-09-11 06:04:064454 const net::LoadStateWithParam& load_state,
4455 uint64_t upload_position,
4456 uint64_t upload_size) {
Charles Harrison911fa062018-03-06 21:01:464457 base::string16 host16 = url_formatter::IDNToUnicode(host);
Elly Fong-Jonescad9c3d12018-01-31 17:26:104458 // Drop no-op updates.
4459 if (load_state_.state == load_state.state &&
4460 load_state_.param == load_state.param &&
4461 upload_position_ == upload_position && upload_size_ == upload_size &&
Charles Harrison911fa062018-03-06 21:01:464462 load_state_host_ == host16) {
Elly Fong-Jonescad9c3d12018-01-31 17:26:104463 return;
4464 }
jam73f892642016-09-11 06:04:064465 load_state_ = load_state;
4466 upload_position_ = upload_position;
4467 upload_size_ = upload_size;
Charles Harrison911fa062018-03-06 21:01:464468 load_state_host_ = host16;
jam73f892642016-09-11 06:04:064469 if (load_state_.state == net::LOAD_STATE_READING_RESPONSE)
4470 SetNotWaitingForResponse();
4471 if (IsLoading()) {
4472 NotifyNavigationStateChanged(static_cast<InvalidateTypes>(
4473 INVALIDATE_TYPE_LOAD | INVALIDATE_TYPE_TAB));
4474 }
4475}
4476
Collin Baker989e0882019-11-01 01:27:174477void WebContentsImpl::SetVisibilityAndNotifyObservers(Visibility visibility) {
Francois Doraye6161152018-03-27 22:05:374478 const Visibility previous_visibility = visibility_;
4479 visibility_ = visibility;
4480
Francois Dorayfe4a1772018-02-17 04:17:094481 // Notify observers if the visibility changed or if WasShown() is being called
4482 // for the first time.
Francois Dorayfe4a1772018-02-17 04:17:094483 if (visibility != previous_visibility ||
4484 (visibility == Visibility::VISIBLE && !did_first_set_visible_)) {
Alexander Timin90c20c32020-08-12 15:28:324485 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4486 observer->OnVisibilityChanged(visibility);
4487 });
Francois Dorayfe4a1772018-02-17 04:17:094488 }
4489}
4490
Michael Thiessen896405db2017-07-20 17:52:324491void WebContentsImpl::NotifyWebContentsFocused(
4492 RenderWidgetHost* render_widget_host) {
Alexander Timin90c20c32020-08-12 15:28:324493 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4494 observer->OnWebContentsFocused(render_widget_host);
4495 });
calamity7fe55ce2015-04-10 03:59:374496}
4497
Michael Thiessen896405db2017-07-20 17:52:324498void WebContentsImpl::NotifyWebContentsLostFocus(
4499 RenderWidgetHost* render_widget_host) {
Alexander Timin90c20c32020-08-12 15:28:324500 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4501 observer->OnWebContentsLostFocus(render_widget_host);
4502 });
zijiehe3bee08e22017-05-17 04:14:464503}
4504
Paul Meyer0c58c3712016-11-17 22:59:514505void WebContentsImpl::SystemDragEnded(RenderWidgetHost* source_rwh) {
4506 if (source_rwh)
4507 source_rwh->DragSourceSystemDragEnded();
Lei Zhang6410ec1a2019-01-31 21:38:584508 if (browser_plugin_embedder_)
[email protected]cf200a562013-05-03 16:24:294509 browser_plugin_embedder_->SystemDragEnded();
[email protected]7813bd72011-02-05 02:19:344510}
4511
[email protected]b172aee2012-04-10 17:05:264512void WebContentsImpl::SetClosedByUserGesture(bool value) {
[email protected]0bfbf882011-12-22 18:19:274513 closed_by_user_gesture_ = value;
4514}
4515
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414516bool WebContentsImpl::GetClosedByUserGesture() {
[email protected]0bfbf882011-12-22 18:19:274517 return closed_by_user_gesture_;
4518}
4519
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414520int WebContentsImpl::GetMinimumZoomPercent() {
[email protected]0bfbf882011-12-22 18:19:274521 return minimum_zoom_percent_;
4522}
4523
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414524int WebContentsImpl::GetMaximumZoomPercent() {
[email protected]0bfbf882011-12-22 18:19:274525 return maximum_zoom_percent_;
4526}
4527
Dave Tapuska8f7c3872020-02-07 01:16:384528void WebContentsImpl::SetPageScale(float scale_factor) {
4529 GetMainFrame()->GetAssociatedLocalMainFrame()->SetScaleFactor(scale_factor);
ccameronb7c1d6c2015-03-09 17:08:244530}
4531
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414532gfx::Size WebContentsImpl::GetPreferredSize() {
Francois Doray24fc62c2017-12-11 17:27:334533 return IsBeingCaptured() ? preferred_size_for_capture_ : preferred_size_;
[email protected]bcd2815602012-01-14 18:17:234534}
4535
James Hollyerd5c9de462020-03-10 19:02:454536bool WebContentsImpl::GotResponseToLockMouseRequest(
4537 blink::mojom::PointerLockResult result) {
lfgf0cd46e2017-01-04 00:05:234538 if (mouse_lock_widget_) {
4539 if (mouse_lock_widget_->delegate()->GetAsWebContents() != this) {
4540 return mouse_lock_widget_->delegate()
4541 ->GetAsWebContents()
James Hollyerd5c9de462020-03-10 19:02:454542 ->GotResponseToLockMouseRequest(result);
lfgf0cd46e2017-01-04 00:05:234543 }
lfgad8244352016-07-13 16:55:514544
James Hollyerd5c9de462020-03-10 19:02:454545 if (mouse_lock_widget_->GotResponseToLockMouseRequest(result))
lfgf0cd46e2017-01-04 00:05:234546 return true;
4547 }
4548
4549 for (WebContentsImpl* current = this; current;
4550 current = current->GetOuterWebContents()) {
4551 current->mouse_lock_widget_ = nullptr;
4552 }
4553
lfgbee1e0a2016-06-08 21:24:214554 return false;
[email protected]0bfbf882011-12-22 18:19:274555}
4556
James Hollyerd5c9de462020-03-10 19:02:454557void WebContentsImpl::GotLockMousePermissionResponse(bool allowed) {
4558 GotResponseToLockMouseRequest(
4559 allowed ? blink::mojom::PointerLockResult::kSuccess
4560 : blink::mojom::PointerLockResult::kPermissionDenied);
4561}
4562
Joe Downing13dd76b2018-04-09 18:32:154563bool WebContentsImpl::GotResponseToKeyboardLockRequest(bool allowed) {
4564 if (!keyboard_lock_widget_)
4565 return false;
4566
4567 if (keyboard_lock_widget_->delegate()->GetAsWebContents() != this) {
4568 NOTREACHED();
4569 return false;
4570 }
4571
4572 // KeyboardLock is only supported when called by the top-level browsing
4573 // context and is not supported in embedded content scenarios.
4574 if (GetOuterWebContents())
4575 return false;
4576
4577 keyboard_lock_widget_->GotResponseToKeyboardLockRequest(allowed);
4578 return true;
4579}
4580
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414581bool WebContentsImpl::HasOpener() {
Ivan Kotenkov2c0d2bb32017-11-01 15:41:284582 return GetOpener() != nullptr;
[email protected]a0358d72012-03-09 14:06:504583}
4584
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414585RenderFrameHostImpl* WebContentsImpl::GetOpener() {
alexmose201c7cd2015-06-10 17:14:214586 FrameTreeNode* opener_ftn = frame_tree_.root()->opener();
lukasza6f8ac622017-06-06 03:10:204587 return opener_ftn ? opener_ftn->current_frame_host() : nullptr;
jochen55ff3502014-12-18 20:52:574588}
4589
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414590bool WebContentsImpl::HasOriginalOpener() {
Ivan Kotenkov2c0d2bb32017-11-01 15:41:284591 return GetOriginalOpener() != nullptr;
jochen6004a362017-02-04 00:11:404592}
4593
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414594RenderFrameHostImpl* WebContentsImpl::GetOriginalOpener() {
jochen6004a362017-02-04 00:11:404595 FrameTreeNode* opener_ftn = frame_tree_.root()->original_opener();
lukasza6f8ac622017-06-06 03:10:204596 return opener_ftn ? opener_ftn->current_frame_host() : nullptr;
jochen6004a362017-02-04 00:11:404597}
4598
[email protected]cb805452013-05-22 15:16:214599void WebContentsImpl::DidChooseColorInColorChooser(SkColor color) {
Joel Hockey85b379d2017-12-11 10:42:134600 color_chooser_->DidChooseColorInColorChooser(color);
[email protected]da8543762012-03-20 08:52:204601}
4602
[email protected]cb805452013-05-22 15:16:214603void WebContentsImpl::DidEndColorChooser() {
Joel Hockey85b379d2017-12-11 10:42:134604 color_chooser_.reset();
[email protected]da8543762012-03-20 08:52:204605}
4606
halton.huoca2eabd2015-07-06 08:17:404607int WebContentsImpl::DownloadImage(
4608 const GURL& url,
4609 bool is_favicon,
Fredrik Söderquistb2b39eb92019-11-18 16:16:504610 uint32_t preferred_size,
halton.huoca2eabd2015-07-06 08:17:404611 uint32_t max_bitmap_size,
4612 bool bypass_cache,
Avi Drissmana5a52dd2018-03-27 03:39:024613 WebContents::ImageDownloadCallback callback) {
Danyao Wanga78f3dd22020-03-05 05:31:274614 return DownloadImageInFrame(GlobalFrameRoutingId(), url, is_favicon,
4615 preferred_size, max_bitmap_size, bypass_cache,
4616 std::move(callback));
4617}
4618
4619int WebContentsImpl::DownloadImageInFrame(
4620 const GlobalFrameRoutingId& initiator_frame_routing_id,
4621 const GURL& url,
4622 bool is_favicon,
4623 uint32_t preferred_size,
4624 uint32_t max_bitmap_size,
4625 bool bypass_cache,
4626 WebContents::ImageDownloadCallback callback) {
amistry9f01b772015-07-29 01:54:554627 DCHECK_CURRENTLY_ON(BrowserThread::UI);
halton.huoca2eabd2015-07-06 08:17:404628 static int next_image_download_id = 0;
Danyao Wanga78f3dd22020-03-05 05:31:274629
4630 RenderFrameHostImpl* initiator_frame =
4631 initiator_frame_routing_id.child_id
4632 ? RenderFrameHostImpl::FromID(initiator_frame_routing_id)
4633 : GetMainFrame();
Julie Jeongeun Kimb1473572019-08-15 05:59:134634 const mojo::Remote<blink::mojom::ImageDownloader>& mojo_image_downloader =
Danyao Wanga78f3dd22020-03-05 05:31:274635 initiator_frame->GetMojoImageDownloader();
amistry9f01b772015-07-29 01:54:554636 const int download_id = ++next_image_download_id;
4637 if (!mojo_image_downloader) {
4638 // If the renderer process is dead (i.e. crash, or memory pressure on
4639 // Android), the downloader service will be invalid. Pre-Mojo, this would
Avi Drissmana5a52dd2018-03-27 03:39:024640 // hang the callback indefinitely since the IPC would be dropped. Now,
amistry9f01b772015-07-29 01:54:554641 // respond with a 400 HTTP error code to indicate that something went wrong.
Gabriel Charettee7cdc5cd2020-05-27 23:35:054642 GetUIThreadTaskRunner({})->PostTask(
4643 FROM_HERE,
tzike2aca992017-09-05 08:50:544644 base::BindOnce(&WebContentsImpl::OnDidDownloadImage,
Avi Drissmana5a52dd2018-03-27 03:39:024645 weak_factory_.GetWeakPtr(), std::move(callback),
4646 download_id, url, 400, std::vector<SkBitmap>(),
4647 std::vector<gfx::Size>()));
amistry9f01b772015-07-29 01:54:554648 return download_id;
4649 }
4650
halton.huoca2eabd2015-07-06 08:17:404651 mojo_image_downloader->DownloadImage(
Fredrik Söderquistb2b39eb92019-11-18 16:16:504652 url, is_favicon, preferred_size, max_bitmap_size, bypass_cache,
tzike2aca992017-09-05 08:50:544653 base::BindOnce(&WebContentsImpl::OnDidDownloadImage,
Avi Drissmana5a52dd2018-03-27 03:39:024654 weak_factory_.GetWeakPtr(), std::move(callback),
4655 download_id, url));
amistry9f01b772015-07-29 01:54:554656 return download_id;
[email protected]795c28972012-12-06 06:13:394657}
4658
[email protected]36ec24f2014-01-09 00:32:084659void WebContentsImpl::Find(int request_id,
4660 const base::string16& search_text,
Rakina Zata Amni3f77dff2018-09-08 16:19:434661 blink::mojom::FindOptionsPtr options) {
thestig6057a6b22015-11-12 23:01:334662 // Cowardly refuse to search for no text.
4663 if (search_text.empty()) {
4664 NOTREACHED();
4665 return;
4666 }
4667
Rakina Zata Amni3f77dff2018-09-08 16:19:434668 GetOrCreateFindRequestManager()->Find(request_id, search_text,
4669 std::move(options));
[email protected]36ec24f2014-01-09 00:32:084670}
4671
4672void WebContentsImpl::StopFinding(StopFindAction action) {
paulmeyerfeafc2d2017-04-25 21:46:404673 if (FindRequestManager* manager = GetFindRequestManager())
4674 manager->StopFinding(action);
[email protected]36ec24f2014-01-09 00:32:084675}
4676
Tommy Steimel18360512017-11-01 00:38:194677bool WebContentsImpl::WasEverAudible() {
4678 return was_ever_audible_;
4679}
4680
Avi Drissmana5a52dd2018-03-27 03:39:024681void WebContentsImpl::GetManifest(GetManifestCallback callback) {
Yuzu Saijofce18322020-05-14 05:02:094682 // TODO(yuzus, 1061899): Move this function to RenderFrameHostImpl.
4683 ManifestManagerHost* manifest_manager_host =
4684 ManifestManagerHost::GetOrCreateForCurrentDocument(GetMainFrame());
4685 manifest_manager_host->GetManifest(std::move(callback));
mlamouriefdca9d2014-09-16 16:55:404686}
4687
bokanece34a82016-01-28 19:49:464688void WebContentsImpl::ExitFullscreen(bool will_cause_resize) {
mlamouri7a78d6fd2015-01-17 13:23:534689 // Clean up related state and initiate the fullscreen exit.
James Hollyerd5c9de462020-03-10 19:02:454690 GetRenderViewHost()->GetWidget()->RejectMouseLockOrUnlockIfNecessary(
4691 blink::mojom::PointerLockResult::kUserRejected);
bokanece34a82016-01-28 19:49:464692 ExitFullscreenMode(will_cause_resize);
mlamouri7a78d6fd2015-01-17 13:23:534693}
4694
Avi Drissman1a55a9d62020-03-10 18:56:454695base::ScopedClosureRunner WebContentsImpl::ForSecurityDropFullscreen() {
Avi Drissman33972942020-06-19 14:16:014696 // Kick WebContentses that are "related" to this WebContents out of
4697 // fullscreen. This needs to be done with two passes, because it is simple to
4698 // walk _up_ the chain of openers and outer contents, but it not simple to
4699 // walk _down_ the chain.
4700
4701 // First, determine if any WebContents that is in fullscreen has this
4702 // WebContents as an upstream contents. Drop that WebContents out of
4703 // fullscreen if it does. This is theoretically quadratic-ish (fullscreen
4704 // contentses x each one's opener length) but neither of those is expected to
4705 // ever be a large number.
4706
4707 auto fullscreen_set_copy = *FullscreenContentsSet(GetBrowserContext());
4708 for (auto* fullscreen_contents : fullscreen_set_copy) {
Avi Drissman97aef042020-06-30 21:04:484709 // Checking IsFullscreen() for tabs in the fullscreen set may seem
4710 // redundant, but teeeeechnically fullscreen is run by the delegate, and
4711 // it's possible that the delegate's notion of fullscreen may have changed
4712 // outside of WebContents's notice.
4713 if (fullscreen_contents->IsFullscreen()) {
Avi Drissman33972942020-06-19 14:16:014714 auto opener_contentses = GetAllOpeningWebContents(fullscreen_contents);
4715 if (opener_contentses.count(this))
4716 fullscreen_contents->ExitFullscreen(true);
4717 }
4718 }
4719
4720 // Second, walk upstream from this WebContents, and drop the fullscreen of
4721 // all WebContentses that are in fullscreen. Block all the WebContentses in
4722 // the chain from entering fullscreen while the returned closure runner is
4723 // alive. It's OK that this set doesn't contain downstream WebContentses, as
4724 // any request to enter fullscreen will have the upstream of the WebContents
4725 // checked. (See CanEnterFullscreenMode().)
Avi Drissmanced52b62019-08-14 21:25:464726
Avi Drissman1a55a9d62020-03-10 18:56:454727 std::vector<base::WeakPtr<WebContentsImpl>> blocked_contentses;
4728
Avi Drissman33972942020-06-19 14:16:014729 for (auto* opener : GetAllOpeningWebContents(this)) {
Avi Drissman1a55a9d62020-03-10 18:56:454730 // Drop fullscreen if the WebContents is in it, and...
Avi Drissman97aef042020-06-30 21:04:484731 if (opener->IsFullscreen())
Avi Drissman33972942020-06-19 14:16:014732 opener->ExitFullscreen(true);
Avi Drissmanced52b62019-08-14 21:25:464733
Avi Drissman1a55a9d62020-03-10 18:56:454734 // ...block the WebContents from entering fullscreen until further notice.
Avi Drissman33972942020-06-19 14:16:014735 ++opener->fullscreen_blocker_count_;
4736 blocked_contentses.push_back(opener->weak_factory_.GetWeakPtr());
Avi Drissmanced52b62019-08-14 21:25:464737 }
Avi Drissman1a55a9d62020-03-10 18:56:454738
4739 return base::ScopedClosureRunner(base::BindOnce(
4740 [](std::vector<base::WeakPtr<WebContentsImpl>> blocked_contentses) {
4741 for (base::WeakPtr<WebContentsImpl>& web_contents :
4742 blocked_contentses) {
4743 if (web_contents) {
4744 DCHECK_GT(web_contents->fullscreen_blocker_count_, 0);
4745 --web_contents->fullscreen_blocker_count_;
4746 }
4747 }
4748 },
4749 std::move(blocked_contentses)));
Avi Drissmanced52b62019-08-14 21:25:464750}
4751
mariakhomenko44bdc4732015-04-29 01:55:384752void WebContentsImpl::ResumeLoadingCreatedWebContents() {
Nasko Oskov83a8cf92018-10-19 14:58:564753 if (delayed_load_url_params_.get()) {
4754 DCHECK(!delayed_open_url_params_);
4755 controller_.LoadURLWithParams(*delayed_load_url_params_.get());
4756 delayed_load_url_params_.reset(nullptr);
4757 return;
4758 }
4759
mariakhomenkoa4971c12015-07-21 19:04:374760 if (delayed_open_url_params_.get()) {
4761 OpenURL(*delayed_open_url_params_.get());
4762 delayed_open_url_params_.reset(nullptr);
4763 return;
4764 }
4765
mariakhomenko44bdc4732015-04-29 01:55:384766 // Resume blocked requests for both the RenderViewHost and RenderFrameHost.
4767 // TODO(brettw): It seems bogus to reach into here and initialize the host.
dfalcantarae6b7b46752015-07-10 18:14:164768 if (is_resume_pending_) {
4769 is_resume_pending_ = false;
avi0f1bbc9712015-11-17 02:58:134770 GetRenderViewHost()->GetWidget()->Init();
dfalcantarae6b7b46752015-07-10 18:14:164771 GetMainFrame()->Init();
4772 }
mariakhomenko44bdc4732015-04-29 01:55:384773}
4774
[email protected]b172aee2012-04-10 17:05:264775bool WebContentsImpl::FocusLocationBarByDefault() {
Xiyuan Xia2a66b112018-12-06 15:52:164776 if (should_focus_location_bar_by_default_)
[email protected]0c9406632013-02-08 01:13:334777 return true;
Xiyuan Xia2a66b112018-12-06 15:52:164778
[email protected]0c9406632013-02-08 01:13:334779 return delegate_ && delegate_->ShouldFocusLocationBarByDefault(this);
[email protected]0bfbf882011-12-22 18:19:274780}
4781
Tommy C. Li8bb5bf42019-01-18 18:45:514782void WebContentsImpl::SetFocusToLocationBar() {
[email protected]0bfbf882011-12-22 18:19:274783 if (delegate_)
Tommy C. Li8bb5bf42019-01-18 18:45:514784 delegate_->SetFocusToLocationBar();
[email protected]c40d6232011-03-25 00:16:214785}
4786
clamy0e119882015-07-31 16:12:334787void WebContentsImpl::DidStartNavigation(NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:484788 TRACE_EVENT1("navigation", "WebContentsImpl::DidStartNavigation",
4789 "navigation_handle", navigation_handle);
Alan Cutterab48fc02020-02-24 12:26:424790 if (navigation_handle->IsInMainFrame())
4791 favicon_urls_.clear();
Mounir Lamouri7b4a1f232019-12-23 16:32:104792
Alexander Timin90c20c32020-08-12 15:28:324793 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4794 observer->DidStartNavigation(navigation_handle);
4795 });
Xiyuan Xia2a66b112018-12-06 15:52:164796 if (navigation_handle->IsInMainFrame()) {
4797 // When the browser is started with about:blank as the startup URL, focus
4798 // the location bar (which will also select its contents) so people can
4799 // simply begin typing to navigate elsewhere.
4800 //
4801 // We need to be careful not to trigger this for anything other than the
4802 // startup navigation. In particular, if we allow an attacker to open a
4803 // popup to about:blank, then navigate, focusing the Omnibox will cause the
4804 // end of the new URL to be scrolled into view instead of the start,
4805 // allowing the attacker to spoof other URLs. The conditions checked here
4806 // are all aimed at ensuring no such attacker-controlled navigation can
4807 // trigger this.
4808 should_focus_location_bar_by_default_ =
4809 controller_.IsInitialNavigation() &&
4810 !navigation_handle->IsRendererInitiated() &&
4811 navigation_handle->GetURL() == url::kAboutBlankURL;
4812 }
clamy0e119882015-07-31 16:12:334813}
4814
4815void WebContentsImpl::DidRedirectNavigation(
4816 NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:484817 TRACE_EVENT1("navigation", "WebContentsImpl::DidRedirectNavigation",
4818 "navigation_handle", navigation_handle);
Alexander Timin90c20c32020-08-12 15:28:324819 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4820 observer->DidRedirectNavigation(navigation_handle);
4821 });
jam5f358e52017-02-13 16:37:034822 // Notify accessibility if this is a reload. This has to called on the
4823 // BrowserAccessibilityManager associated with the old RFHI.
4824 if (navigation_handle->GetReloadType() != ReloadType::NONE) {
Mohamed Abdelhalim95794962019-09-20 11:16:494825 NavigationRequest* request = NavigationRequest::From(navigation_handle);
jam5f358e52017-02-13 16:37:034826 BrowserAccessibilityManager* manager =
Mohamed Abdelhalim95794962019-09-20 11:16:494827 request->frame_tree_node()
jam5f358e52017-02-13 16:37:034828 ->current_frame_host()
4829 ->browser_accessibility_manager();
4830 if (manager)
4831 manager->UserIsReloading();
4832 }
clamy0e119882015-07-31 16:12:334833}
4834
clamyefca29e2015-09-17 00:22:114835void WebContentsImpl::ReadyToCommitNavigation(
4836 NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:484837 TRACE_EVENT1("navigation", "WebContentsImpl::ReadyToCommitNavigation",
4838 "navigation_handle", navigation_handle);
Alexander Timin90c20c32020-08-12 15:28:324839 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4840 observer->ReadyToCommitNavigation(navigation_handle);
4841 });
Kenneth Russell954ed9ce2018-04-12 23:07:014842 // If any domains are blocked from accessing 3D APIs because they may
4843 // have caused the GPU to reset recently, unblock them here if the user
4844 // initiated this navigation. This implies that the user was involved in
4845 // the decision to navigate, so there's no concern about
4846 // denial-of-service issues. Want to do this as early as
4847 // possible to avoid race conditions with pages attempting to access
4848 // WebGL early on.
4849 //
4850 // TODO(crbug.com/617904): currently navigations initiated by the browser
4851 // (reload button, reload menu option, pressing return in the Omnibox)
4852 // return false from HasUserGesture(). If or when that is addressed,
4853 // remove the check for IsRendererInitiated() below.
4854 //
4855 // TODO(crbug.com/832180): HasUserGesture comes from the renderer
4856 // process and isn't validated. Until it is, don't trust it.
4857 if (!navigation_handle->IsRendererInitiated()) {
4858 GpuDataManagerImpl::GetInstance()->UnblockDomainFrom3DAPIs(
4859 navigation_handle->GetURL());
4860 }
4861
John Abd-El-Malekfde08e6da2017-12-05 04:06:244862 if (navigation_handle->IsSameDocument())
4863 return;
4864
Livvie Lin139bf442018-08-10 00:18:544865 // SSLInfo is not needed on subframe navigations since the main-frame
4866 // certificate is the only one that can be inspected (using the info
4867 // bubble) without refreshing the page with DevTools open.
Carlos ILaed1e7b2019-03-12 19:27:214868 // We don't call DidStartResourceResponse on net errors, since that results on
4869 // existing cert exceptions being revoked, which leads to weird behavior with
4870 // committed interstitials or while offline. We only need the error check for
4871 // the main frame case because unlike this method, SubresourceResponseStarted
4872 // does not get called on network errors.
4873 if (navigation_handle->IsInMainFrame() &&
4874 navigation_handle->GetNetErrorCode() == net::OK) {
Livvie Lin139bf442018-08-10 00:18:544875 controller_.ssl_manager()->DidStartResourceResponse(
Lukasz Anforowiczd334bba2020-02-10 23:32:554876 navigation_handle->GetURL(),
Camille Lamy62b826012019-02-26 09:15:474877 navigation_handle->GetSSLInfo().has_value()
4878 ? net::IsCertStatusError(
4879 navigation_handle->GetSSLInfo()->cert_status)
4880 : false);
4881 }
John Abd-El-Malekfde08e6da2017-12-05 04:06:244882
4883 SetNotWaitingForResponse();
clamyefca29e2015-09-17 00:22:114884}
4885
clamy0e119882015-07-31 16:12:334886void WebContentsImpl::DidFinishNavigation(NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:484887 TRACE_EVENT1("navigation", "WebContentsImpl::DidFinishNavigation",
4888 "navigation_handle", navigation_handle);
Steven Holte38041342018-06-22 22:00:574889
Alexander Timin90c20c32020-08-12 15:28:324890 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4891 observer->DidFinishNavigation(navigation_handle);
4892 });
Becca Hughesd11d6502018-07-31 17:01:284893 if (display_cutout_host_impl_)
4894 display_cutout_host_impl_->DidFinishNavigation(navigation_handle);
4895
jam5f358e52017-02-13 16:37:034896 if (navigation_handle->HasCommitted()) {
Ian Prestcdd843d2020-01-28 18:59:584897 // TODO(domfarolino, dmazzoni): Do this using WebContentsObserver. See
4898 // https://crbug.com/981271.
4899 BrowserAccessibilityManager* manager =
4900 static_cast<RenderFrameHostImpl*>(
4901 navigation_handle->GetRenderFrameHost())
4902 ->browser_accessibility_manager();
4903 if (manager) {
4904 if (navigation_handle->IsErrorPage()) {
4905 manager->NavigationFailed();
4906 } else {
4907 manager->NavigationSucceeded();
4908 }
4909 }
4910
Yue Ru Sun979c4b162019-11-06 16:11:044911 if (navigation_handle->IsInMainFrame()) {
4912 last_committed_source_id_including_same_document_ =
Steven Holte38041342018-06-22 22:00:574913 ukm::ConvertToSourceId(navigation_handle->GetNavigationId(),
4914 ukm::SourceIdType::NAVIGATION_ID);
Yue Ru Sun979c4b162019-11-06 16:11:044915
4916 if (!navigation_handle->IsSameDocument()) {
4917 was_ever_audible_ = false;
Yue Ru Sun979c4b162019-11-06 16:11:044918 }
Tommy Steimel18360512017-11-01 00:38:194919 }
Lan Weif81c6e7c2020-02-12 16:46:094920
4921 if (!navigation_handle->IsSameDocument())
4922 last_screen_orientation_change_time_ = base::TimeTicks();
dmazzonibf8cec42015-02-08 08:28:084923 }
Xiyuan Xia2a66b112018-12-06 15:52:164924
4925 // If we didn't end up on about:blank after setting this in DidStartNavigation
4926 // then don't focus the location bar.
4927 if (should_focus_location_bar_by_default_ &&
4928 navigation_handle->GetURL() != url::kAboutBlankURL) {
4929 should_focus_location_bar_by_default_ = false;
4930 }
yilkal796e89e2019-10-02 23:58:284931
yilkal172da772019-11-06 22:49:074932 if (navigation_handle->IsInMainFrame() && first_navigation_completed_)
4933 RecordMaxFrameCountUMA(max_loaded_frame_count_);
yilkal796e89e2019-10-02 23:58:284934
yilkal172da772019-11-06 22:49:074935 // If navigation has successfully finished in the main frame, set
4936 // |first_navigation_completed_| to true so that we will record
4937 // |max_loaded_frame_count_| above when future main frame navigations finish.
4938 if (navigation_handle->IsInMainFrame() && !navigation_handle->IsErrorPage()) {
4939 first_navigation_completed_ = true;
4940
4941 // Navigation has completed in main frame. Reset |max_loaded_frame_count_|.
4942 // |max_loaded_frame_count_| is not necessarily 1 if the navigation was
4943 // served from BackForwardCache.
4944 max_loaded_frame_count_ =
4945 GetMainFrame()->frame_tree_node()->GetFrameTreeSize();
yilkal796e89e2019-10-02 23:58:284946 }
Rakina Zata Amni347b70902020-07-22 10:49:044947
4948 if (web_preferences_) {
4949 // Update the WebPreferences for this WebContents that depends on changes
4950 // that might occur during navigation. This will only update the preferences
4951 // that needs to be updated (and won't cause an update/overwrite preferences
4952 // that needs to stay the same after navigations).
4953 bool value_changed_due_to_override =
4954 GetContentClient()->browser()->OverrideWebPreferencesAfterNavigation(
4955 this, web_preferences_.get());
4956 // We need to update the WebPreferences value on the renderer if the value
4957 // is changed due to the override above, or if the navigation is served from
4958 // the back-forward cache, because the WebPreferences value stored in the
4959 // renderer might be stale (because we don't send WebPreferences updates to
4960 // bfcached renderers).
4961 // TODO(rakina): Maybe handle the back-forward cache case in
4962 // ReadyToCommitNavigation instead?
4963 if (value_changed_due_to_override ||
4964 NavigationRequest::From(navigation_handle)
4965 ->IsServedFromBackForwardCache()) {
4966 SetWebPreferences(*web_preferences_.get());
4967 }
4968 }
[email protected]400992b2012-06-14 00:03:544969}
4970
[email protected]b80624c2014-02-09 02:46:554971void WebContentsImpl::DidFailLoadWithError(
4972 RenderFrameHostImpl* render_frame_host,
[email protected]b80624c2014-02-09 02:46:554973 const GURL& url,
Dave Tapuska924ef3c2020-01-22 18:20:594974 int error_code) {
Alexander Timin90c20c32020-08-12 15:28:324975 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4976 observer->DidFailLoad(render_frame_host, url, error_code);
4977 });
[email protected]b80624c2014-02-09 02:46:554978}
4979
[email protected]52913802013-12-10 05:52:184980void WebContentsImpl::NotifyChangedNavigationState(
4981 InvalidateTypes changed_flags) {
4982 NotifyNavigationStateChanged(changed_flags);
4983}
4984
lukasza1d025732016-09-28 21:36:084985bool WebContentsImpl::ShouldTransferNavigation(bool is_main_frame_navigation) {
creis29460272015-12-16 04:38:224986 if (!delegate_)
4987 return true;
lukasza1d025732016-09-28 21:36:084988 return delegate_->ShouldTransferNavigation(is_main_frame_navigation);
creis29460272015-12-16 04:38:224989}
4990
[email protected]aa62afd2014-04-22 19:22:464991bool WebContentsImpl::ShouldPreserveAbortedURLs() {
4992 if (!delegate_)
4993 return false;
4994 return delegate_->ShouldPreserveAbortedURLs(this);
4995}
4996
[email protected]0d0f4c492014-04-02 06:42:574997void WebContentsImpl::DidNavigateMainFramePreCommit(
[email protected]5cfbddc2014-06-23 23:52:234998 bool navigation_is_within_page) {
[email protected]0d0f4c492014-04-02 06:42:574999 // Ensure fullscreen mode is exited before committing the navigation to a
5000 // different page. The next page will not start out assuming it is in
5001 // fullscreen mode.
[email protected]5cfbddc2014-06-23 23:52:235002 if (navigation_is_within_page) {
[email protected]dfc39cb2014-04-09 22:58:195003 // No page change? Then, the renderer and browser can remain in fullscreen.
[email protected]0d0f4c492014-04-02 06:42:575004 return;
5005 }
Avi Drissman97aef042020-06-30 21:04:485006 if (IsFullscreen())
bokanece34a82016-01-28 19:49:465007 ExitFullscreen(false);
Avi Drissman97aef042020-06-30 21:04:485008 DCHECK(!IsFullscreen());
Joe Downingc1a57efe2018-05-09 18:23:545009
5010 // Clean up keyboard lock state when navigating.
5011 CancelKeyboardLock(keyboard_lock_widget_);
[email protected]0d0f4c492014-04-02 06:42:575012}
5013
[email protected]37567b432014-02-12 01:12:225014void WebContentsImpl::DidNavigateMainFramePostCommit(
sky8b00392d2015-01-10 00:30:285015 RenderFrameHostImpl* render_frame_host,
[email protected]37567b432014-02-12 01:12:225016 const LoadCommittedDetails& details,
5017 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
5018 if (details.is_navigation_to_different_page()) {
5019 // Clear the status bubble. This is a workaround for a bug where WebKit
5020 // doesn't let us know that the cursor left an element during a
5021 // transition (this is also why the mouse cursor remains as a hand after
5022 // clicking on a link); see bugs 1184641 and 980803. We don't want to
5023 // clear the bubble when a user navigates to a named anchor in the same
5024 // page.
Lukasz Anforowiczfd707142018-02-07 19:46:135025 ClearTargetURL();
lanwei9d343ad22015-02-11 01:46:005026
5027 RenderWidgetHostViewBase* rwhvb =
5028 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
5029 if (rwhvb)
5030 rwhvb->OnDidNavigateMainFrameToNewPage();
[email protected]37567b432014-02-12 01:12:225031 }
5032
[email protected]e85165c642014-06-10 14:34:315033 if (delegate_)
[email protected]37567b432014-02-12 01:12:225034 delegate_->DidNavigateMainFramePostCommit(this);
[email protected]e85165c642014-06-10 14:34:315035 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
Shivani Sharma985474f2019-05-23 21:36:475036
Carlos Caballero91fffb22019-10-29 15:24:305037 if (details.is_navigation_to_different_page() &&
5038 GetRenderViewHost()->did_first_visually_non_empty_paint()) {
5039 // This event will not fire again if the page is restored from the
5040 // BackForwardCache. So fire it ourselves if needed.
5041 DidFirstVisuallyNonEmptyPaint(GetRenderViewHost());
5042 }
Carlos Caballero1215f882019-10-29 15:58:435043
5044 if (GetRenderViewHost()->theme_color() != last_sent_theme_color_) {
5045 // This event will not fire again if the page is restored from the
5046 // BackForwardCache. So fire it ourselves if needed.
5047 OnThemeColorChanged(GetRenderViewHost());
5048 }
[email protected]37567b432014-02-12 01:12:225049}
5050
5051void WebContentsImpl::DidNavigateAnyFramePostCommit(
5052 RenderFrameHostImpl* render_frame_host,
5053 const LoadCommittedDetails& details,
5054 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
[email protected]b4c84012014-04-28 19:51:105055 // Now that something has committed, we don't need to track whether the
5056 // initial page has been accessed.
5057 has_accessed_initial_document_ = false;
5058
[email protected]37567b432014-02-12 01:12:225059 // If we navigate off the page, close all JavaScript dialogs.
eugenebutee08663a2017-04-27 17:43:125060 if (!details.is_same_document)
creis89a0f782015-05-27 16:13:175061 CancelActiveAndPendingDialogs();
[email protected]37567b432014-02-12 01:12:225062
avid53461d2016-02-25 17:15:045063 // If this is a user-initiated navigation, start allowing JavaScript dialogs
5064 // again.
avi5d3b8692016-10-12 22:00:465065 if (params.gesture == NavigationGestureUser && dialog_manager_) {
avi6879fcf2017-01-21 05:27:535066 dialog_manager_->CancelDialogs(this, /*reset_state=*/true);
avi5d3b8692016-10-12 22:00:465067 }
[email protected]37567b432014-02-12 01:12:225068}
5069
[email protected]277857a2014-06-03 10:38:015070bool WebContentsImpl::CanOverscrollContent() const {
[email protected]e85165c642014-06-10 14:34:315071 // Disable overscroll when touch emulation is on. See crbug.com/369938.
[email protected]34ff1cfc2014-08-20 06:16:055072 if (force_disable_overscroll_content_)
[email protected]e85165c642014-06-10 14:34:315073 return false;
5074
[email protected]37567b432014-02-12 01:12:225075 if (delegate_)
5076 return delegate_->CanOverscrollContent();
5077
5078 return false;
5079}
5080
Carlos Caballero1215f882019-10-29 15:58:435081void WebContentsImpl::OnThemeColorChanged(RenderViewHostImpl* source) {
5082 if (source->did_first_visually_non_empty_paint() &&
5083 last_sent_theme_color_ != source->theme_color()) {
Alexander Timin90c20c32020-08-12 15:28:325084 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5085 observer->DidChangeThemeColor();
5086 });
peter90afaba2015-06-01 12:05:295087 }
[email protected]e7104762014-06-20 19:17:255088}
5089
Gyuyoung Kim1905f7c2020-05-02 00:00:245090void WebContentsImpl::DidLoadResourceFromMemoryCache(
nicka0ac8382016-12-15 23:59:235091 RenderFrameHostImpl* source,
[email protected]724159a2010-12-30 01:11:185092 const GURL& url,
[email protected]70435962011-08-02 20:13:285093 const std::string& http_method,
[email protected]6d6cfb3a2012-05-23 22:53:185094 const std::string& mime_type,
Kinuko Yasuda433f710a2020-02-14 02:11:585095 network::mojom::RequestDestination request_destination) {
Alexander Timin90c20c32020-08-12 15:28:325096 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5097 observer->DidLoadResourceFromMemoryCache(url, mime_type,
5098 request_destination);
5099 });
[email protected]b0f724c2013-09-05 04:21:135100
Steven Bingler674fb0822018-12-12 18:04:525101 if (url.is_valid() && url.SchemeIsHTTPOrHTTPS()) {
nicka0ac8382016-12-15 23:59:235102 StoragePartition* partition = source->GetProcess()->GetStoragePartition();
John Abd-El-Malekf4fe9d82019-07-31 04:05:595103 partition->GetNetworkContext()->NotifyExternalCacheHit(
Matt Menke2a33dee2019-12-02 17:01:545104 url, http_method, source->GetNetworkIsolationKey());
[email protected]8bfc8272013-09-09 20:10:535105 }
[email protected]724159a2010-12-30 01:11:185106}
5107
carloskd9d97942017-02-16 08:58:095108void WebContentsImpl::DidDisplayInsecureContent() {
estarkc2273502016-10-12 22:03:025109 controller_.ssl_manager()->DidDisplayMixedContent();
[email protected]724159a2010-12-30 01:11:185110}
5111
Dave Tapuskaa657d872019-10-21 20:23:215112void WebContentsImpl::DidContainInsecureFormAction() {
elawrenceb2ac2a232017-03-27 21:46:255113 controller_.ssl_manager()->DidContainInsecureFormAction();
5114}
5115
Julie Jeongeun Kim0b103492020-01-29 05:30:515116void WebContentsImpl::DocumentAvailableInMainFrame() {
Alexander Timin90c20c32020-08-12 15:28:325117 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5118 observer->DocumentAvailableInMainFrame();
5119 });
Julie Jeongeun Kim0b103492020-01-29 05:30:515120}
5121
nicka0ac8382016-12-15 23:59:235122void WebContentsImpl::OnDidRunInsecureContent(RenderFrameHostImpl* source,
5123 const GURL& security_origin,
estark910b4572015-12-09 20:55:415124 const GURL& target_url) {
nicka0ac8382016-12-15 23:59:235125 // TODO(nick, estark): Should we call FilterURL using |source|'s process on
5126 // these parameters? |target_url| seems unused, except for a log message. And
5127 // |security_origin| might be replaceable with the origin of the main frame.
carloskd9d97942017-02-16 08:58:095128 DidRunInsecureContent(security_origin, target_url);
5129}
5130
5131void WebContentsImpl::DidRunInsecureContent(const GURL& security_origin,
5132 const GURL& target_url) {
[email protected]9450c462013-11-23 01:22:585133 LOG(WARNING) << security_origin << " ran insecure content from "
5134 << target_url.possibly_invalid_spec();
[email protected]e6e30ac2014-01-13 21:24:395135 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
estark910b4572015-12-09 20:55:415136 if (base::EndsWith(security_origin.spec(), kDotGoogleDotCom,
brettwa7ff1b292015-07-16 17:49:295137 base::CompareCase::INSENSITIVE_ASCII))
[email protected]e6e30ac2014-01-13 21:24:395138 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
estarkc2273502016-10-12 22:03:025139 controller_.ssl_manager()->DidRunMixedContent(security_origin);
[email protected]724159a2010-12-30 01:11:185140}
5141
carloskd9d97942017-02-16 08:58:095142void WebContentsImpl::PassiveInsecureContentFound(const GURL& resource_url) {
Sergey Kuznetsov3ebc01b2018-02-01 04:57:365143 if (delegate_) {
5144 delegate_->PassiveInsecureContentFound(resource_url);
5145 }
carloskd9d97942017-02-16 08:58:095146}
5147
5148bool WebContentsImpl::ShouldAllowRunningInsecureContent(
carloskd9d97942017-02-16 08:58:095149 bool allowed_per_prefs,
5150 const url::Origin& origin,
5151 const GURL& resource_url) {
Sergey Kuznetsov3ebc01b2018-02-01 04:57:365152 if (delegate_) {
Carlos IL29294a62020-05-15 00:21:165153 return delegate_->ShouldAllowRunningInsecureContent(this, allowed_per_prefs,
5154 origin, resource_url);
Sergey Kuznetsov3ebc01b2018-02-01 04:57:365155 }
5156
5157 return allowed_per_prefs;
carloskd9d97942017-02-16 08:58:095158}
5159
Lukasz Anforowicze1b954d92017-10-30 21:28:065160void WebContentsImpl::ViewSource(RenderFrameHostImpl* frame) {
5161 DCHECK_EQ(this, WebContents::FromRenderFrameHost(frame));
5162
5163 // Don't do anything if there is no |delegate_| that could accept and show the
5164 // new WebContents containing the view-source.
5165 if (!delegate_)
5166 return;
5167
5168 // Use the last committed entry, since the pending entry hasn't loaded yet and
5169 // won't be copied into the cloned tab.
5170 NavigationEntryImpl* last_committed_entry =
Fergal Daly09d6c762020-05-29 02:05:185171 GetController().GetLastCommittedEntry();
Lukasz Anforowicze1b954d92017-10-30 21:28:065172 if (!last_committed_entry)
5173 return;
5174
5175 FrameNavigationEntry* frame_entry =
5176 last_committed_entry->GetFrameEntry(frame->frame_tree_node());
5177 if (!frame_entry)
5178 return;
5179
5180 // Any new WebContents opened while this WebContents is in fullscreen can be
5181 // used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:455182 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
5183 // The new view source contents will be independent of this contents, so
5184 // release the fullscreen block.
5185 fullscreen_block.RunAndReset();
Lukasz Anforowicze1b954d92017-10-30 21:28:065186
5187 // We intentionally don't share the SiteInstance with the original frame so
5188 // that view source has a consistent process model and always ends up in a new
5189 // process (https://crbug.com/699493).
5190 scoped_refptr<SiteInstanceImpl> site_instance_for_view_source = nullptr;
Lukasz Anforowicz435bcb582019-07-12 20:50:065191 // Referrer and initiator are not important, because view-source should not
5192 // hit the network, but should be served from the cache instead.
Lukasz Anforowicze1b954d92017-10-30 21:28:065193 Referrer referrer_for_view_source;
Lukasz Anforowicz435bcb582019-07-12 20:50:065194 base::Optional<url::Origin> initiator_for_view_source = base::nullopt;
Lukasz Anforowicze1b954d92017-10-30 21:28:065195 // Do not restore title, derive it from the url.
5196 base::string16 title_for_view_source;
5197 auto navigation_entry = std::make_unique<NavigationEntryImpl>(
5198 site_instance_for_view_source, frame_entry->url(),
Lukasz Anforowicz435bcb582019-07-12 20:50:065199 referrer_for_view_source, initiator_for_view_source,
5200 title_for_view_source, ui::PAGE_TRANSITION_LINK,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:095201 /* is_renderer_initiated = */ false,
5202 /* blob_url_loader_factory = */ nullptr);
Joel Hockey891e88062020-04-30 05:38:445203 const GURL url(content::kViewSourceScheme + std::string(":") +
5204 frame_entry->url().spec());
5205 navigation_entry->SetVirtualURL(url);
Matt Menkea56c5992020-04-10 20:53:565206 navigation_entry->set_isolation_info(
5207 frame->GetIsolationInfoForSubresources());
Yao Xiaof68f57d2019-10-03 04:20:055208
Lukasz Anforowicze1b954d92017-10-30 21:28:065209 // Do not restore scroller position.
5210 // TODO(creis, lukasza, arthursonzogni): Do not reuse the original PageState,
5211 // but start from a new one and only copy the needed data.
5212 const PageState& new_page_state =
5213 frame_entry->page_state().RemoveScrollOffset();
5214
5215 scoped_refptr<FrameNavigationEntry> new_frame_entry =
5216 navigation_entry->root_node()->frame_entry;
5217 new_frame_entry->set_method(frame_entry->method());
5218 new_frame_entry->SetPageState(new_page_state);
5219
5220 // Create a new WebContents, which is used to display the source code.
erikchenbee5c9622018-04-27 19:30:255221 std::unique_ptr<WebContents> view_source_contents =
Erik Chenbb8e738e2018-04-28 14:10:435222 Create(CreateParams(GetBrowserContext()));
Lukasz Anforowicze1b954d92017-10-30 21:28:065223
5224 // Restore the previously created NavigationEntry.
5225 std::vector<std::unique_ptr<NavigationEntry>> navigation_entries;
5226 navigation_entries.push_back(std::move(navigation_entry));
5227 view_source_contents->GetController().Restore(0, RestoreType::CURRENT_SESSION,
5228 &navigation_entries);
5229
5230 // Add |view_source_contents| as a new tab.
5231 gfx::Rect initial_rect;
5232 constexpr bool kUserGesture = true;
5233 bool ignored_was_blocked;
Joel Hockey891e88062020-04-30 05:38:445234 delegate_->AddNewContents(this, std::move(view_source_contents), url,
Lukasz Anforowicze1b954d92017-10-30 21:28:065235 WindowOpenDisposition::NEW_FOREGROUND_TAB,
5236 initial_rect, kUserGesture, &ignored_was_blocked);
5237 // Note that the |delegate_| could have deleted |view_source_contents| during
5238 // AddNewContents method call.
5239}
5240
Lukasz Anforowiczd334bba2020-02-10 23:32:555241void WebContentsImpl::SubresourceResponseStarted(const GURL& url,
5242 net::CertStatus cert_status) {
5243 controller_.ssl_manager()->DidStartResourceResponse(url, cert_status);
Jay Civellid5904f02018-03-23 19:43:575244 SetNotWaitingForResponse();
5245}
5246
Jay Civelli116683f2018-03-27 19:56:235247void WebContentsImpl::ResourceLoadComplete(
Jay Civelli52a63302018-04-30 22:39:555248 RenderFrameHost* render_frame_host,
Clark DuVall36164bd2018-08-09 22:49:085249 const GlobalRequestID& request_id,
Minggang Wangee5af392020-02-05 02:55:285250 blink::mojom::ResourceLoadInfoPtr resource_load_info) {
Alexander Timin90c20c32020-08-12 15:28:325251 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5252 observer->ResourceLoadComplete(render_frame_host, request_id,
5253 *resource_load_info);
5254 });
John Abd-El-Malekd4882642017-12-04 21:45:195255}
5256
Rakina Zata Amni347b70902020-07-22 10:49:045257const WebPreferences& WebContentsImpl::GetOrCreateWebPreferences() {
5258 // Compute WebPreferences based on the current state if it's null.
5259 if (!web_preferences_)
Rakina Zata Amni4029b6d2020-07-28 02:36:205260 OnWebPreferencesChanged();
Rakina Zata Amni347b70902020-07-22 10:49:045261 return *web_preferences_.get();
5262}
5263
5264bool WebContentsImpl::IsWebPreferencesSet() const {
5265 return web_preferences_.get();
5266}
5267
5268void WebContentsImpl::SetWebPreferences(const WebPreferences& prefs) {
5269 web_preferences_ = std::make_unique<WebPreferences>(prefs);
5270 // Get all the RenderViewHosts (except the ones for currently back-forward
5271 // cached pages), and make them send the current WebPreferences
5272 // to the renderer. WebPreferences updates for back-forward cached pages will
5273 // be sent when we restore those pages from the back-forward cache.
5274 for (auto& rvh : frame_tree_.render_view_hosts()) {
5275 rvh.second->SendWebPreferencesToRenderer();
5276 }
5277}
5278
5279void WebContentsImpl::RecomputeWebPreferencesSlow() {
Rakina Zata Amni4029b6d2020-07-28 02:36:205280 // OnWebPreferencesChanged is a no-op when this is true.
5281 if (updating_web_preferences_)
5282 return;
Rakina Zata Amni347b70902020-07-22 10:49:045283 // Resets |web_preferences_| so that we won't have any cached value for slow
5284 // attributes (which won't get recomputed if we have pre-existing values for
5285 // them).
5286 web_preferences_.reset();
Rakina Zata Amni4029b6d2020-07-28 02:36:205287 OnWebPreferencesChanged();
Rakina Zata Amni347b70902020-07-22 10:49:045288}
5289
Wei Li5bb659742018-02-14 03:07:585290void WebContentsImpl::PrintCrossProcessSubframe(
5291 const gfx::Rect& rect,
5292 int document_cookie,
5293 RenderFrameHost* subframe_host) {
Wei Li5c0b4d12018-03-22 15:05:225294 auto* outer_contents = GetOuterWebContents();
5295 if (outer_contents) {
5296 // When an extension or app page is printed, the content should be
5297 // composited with outer content, so the outer contents should handle the
5298 // print request.
5299 outer_contents->PrintCrossProcessSubframe(rect, document_cookie,
5300 subframe_host);
5301 return;
5302 }
5303
Wei Li5bb659742018-02-14 03:07:585304 // If there is no delegate such as in tests or during deletion, do nothing.
5305 if (!delegate_)
5306 return;
5307
5308 delegate_->PrintCrossProcessSubframe(this, rect, document_cookie,
5309 subframe_host);
5310}
5311
ckitagawa8695799b2020-02-05 16:08:495312void WebContentsImpl::CapturePaintPreviewOfCrossProcessSubframe(
5313 const gfx::Rect& rect,
5314 const base::UnguessableToken& guid,
5315 RenderFrameHost* render_frame_host) {
5316 if (!delegate_)
5317 return;
ckitagawac43ac982020-07-07 17:41:175318 delegate_->CapturePaintPreviewOfSubframe(this, rect, guid, render_frame_host);
ckitagawa8695799b2020-02-05 16:08:495319}
5320
rob.buis300b0872017-03-10 20:43:585321#if defined(OS_ANDROID)
5322base::android::ScopedJavaLocalRef<jobject>
5323WebContentsImpl::GetJavaRenderFrameHostDelegate() {
5324 return GetJavaWebContents();
5325}
5326#endif
5327
Hiroki Nakagawa39d1bbe2020-07-14 16:15:525328void WebContentsImpl::OnDidDisplayContentWithCertificateErrors() {
estarkc2273502016-10-12 22:03:025329 controller_.ssl_manager()->DidDisplayContentWithCertErrors();
estark910b4572015-12-09 20:55:415330}
5331
5332void WebContentsImpl::OnDidRunContentWithCertificateErrors(
Zhuoyu Qian4353f7f2018-01-08 05:33:005333 RenderFrameHostImpl* source) {
Emily Starkabbdd662020-06-05 02:40:135334 // For RenderFrameHosts that are inactive and going to be discarded, we can
5335 // disregard this message; there's no need to update the UI if the UI will
5336 // never be shown again.
5337 //
5338 // We still process this message for speculative RenderFrameHosts. This can
5339 // happen when a subframe's main resource has a certificate error. The
5340 // currently committed navigation entry will get marked as having run insecure
5341 // content and that will carry over to the navigation entry for the
5342 // speculative RFH when it commits.
5343 if (source->lifecycle_state() !=
5344 RenderFrameHostImpl::LifecycleState::kSpeculative &&
5345 source->IsInactiveAndDisallowReactivation()) {
estarkaeda1422016-05-10 02:31:125346 return;
Emily Starkabbdd662020-06-05 02:40:135347 }
estarkcd2e30c2016-08-12 06:51:155348 controller_.ssl_manager()->DidRunContentWithCertErrors(
Emily Starkabbdd662020-06-05 02:40:135349 source->GetMainFrame()->GetLastCommittedOrigin().GetURL());
estark910b4572015-12-09 20:55:415350}
5351
Kouhei Ueno97e0990d2019-09-25 02:57:275352void WebContentsImpl::DOMContentLoaded(RenderFrameHost* render_frame_host) {
Alexander Timin90c20c32020-08-12 15:28:325353 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5354 observer->DOMContentLoaded(render_frame_host);
5355 });
[email protected]724159a2010-12-30 01:11:185356}
5357
Gyuyoung Kim525e0c5d2020-03-09 15:04:195358void WebContentsImpl::OnDidFinishLoad(RenderFrameHost* render_frame_host,
nicka0ac8382016-12-15 23:59:235359 const GURL& url) {
[email protected]8b3af1e2014-01-24 13:29:125360 GURL validated_url(url);
Gyuyoung Kim525e0c5d2020-03-09 15:04:195361 render_frame_host->GetProcess()->FilterURL(false, &validated_url);
[email protected]028053d42014-03-05 22:20:375362
Alexander Timin90c20c32020-08-12 15:28:325363 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5364 observer->DidFinishLoad(render_frame_host, validated_url);
5365 });
yilkal172da772019-11-06 22:49:075366 size_t tree_size = frame_tree_.root()->GetFrameTreeSize();
5367 if (max_loaded_frame_count_ < tree_size)
5368 max_loaded_frame_count_ = tree_size;
5369
Gyuyoung Kim525e0c5d2020-03-09 15:04:195370 if (!render_frame_host->GetParent())
yilkal172da772019-11-06 22:49:075371 UMA_HISTOGRAM_COUNTS_1000("Navigation.MainFrame.FrameCount", tree_size);
[email protected]1a55c5be2011-11-29 11:36:315372}
5373
Dave Tapuska549baab2019-03-19 15:52:405374void WebContentsImpl::OnGoToEntryAtOffset(RenderFrameHostImpl* source,
Julie Jeongeun Kim144f8192020-01-18 06:59:035375 int32_t offset,
Dave Tapuska043b94a2019-09-10 14:14:355376 bool has_user_gesture) {
Arthur Sonzognia7d715a2018-09-20 16:11:135377 // Non-user initiated navigations coming from the renderer should be ignored
5378 // if there is an ongoing browser-initiated navigation.
5379 // See https://crbug.com/879965.
5380 // TODO(arthursonzogni): See if this should check for ongoing navigations in
5381 // the frame(s) affected by the session history navigation, rather than just
5382 // the main frame.
Kevin McNee96851e12020-07-16 03:43:225383 if (Navigator::ShouldIgnoreIncomingRendererRequest(
5384 frame_tree_.root()->navigation_request(), has_user_gesture))
5385 return;
Arthur Sonzognia7d715a2018-09-20 16:11:135386
nicka0ac8382016-12-15 23:59:235387 // All frames are allowed to navigate the global history.
Dave Tapuska8bfd84c2019-03-26 20:47:165388 if (!delegate_ || delegate_->OnGoToEntryOffset(offset)) {
arthursonzognib93a4472020-04-10 07:38:005389 if (source->IsSandboxed(network::mojom::WebSandboxFlags::kTopNavigation)) {
Dave Tapuska8bfd84c2019-03-26 20:47:165390 // Keep track of whether this is a session history from a sandboxed iframe
5391 // with top level navigation disallowed.
5392 controller_.GoToOffsetInSandboxedFrame(offset,
5393 source->GetFrameTreeNodeId());
5394 } else {
5395 controller_.GoToOffset(offset);
5396 }
5397 }
[email protected]216813952011-05-19 22:21:265398}
5399
Dave Tapuska4c02911b2020-02-14 22:52:075400void WebContentsImpl::OnPageScaleFactorChanged(RenderFrameHostImpl* source,
nicka0ac8382016-12-15 23:59:235401 float page_scale_factor) {
mcnee336ea2c2017-05-23 22:50:595402#if !defined(OS_ANDROID)
5403 // While page scale factor is used on mobile, this PageScaleFactorIsOne logic
5404 // is only needed on desktop.
mcnee432e47d2015-11-09 19:37:465405 bool is_one = page_scale_factor == 1.f;
5406 if (is_one != page_scale_factor_is_one_) {
5407 page_scale_factor_is_one_ = is_one;
5408
5409 HostZoomMapImpl* host_zoom_map =
5410 static_cast<HostZoomMapImpl*>(HostZoomMap::GetForWebContents(this));
5411
nicka0ac8382016-12-15 23:59:235412 if (host_zoom_map) {
mcnee432e47d2015-11-09 19:37:465413 host_zoom_map->SetPageScaleFactorIsOneForView(
Dave Tapuska4c02911b2020-02-14 22:52:075414 source->GetProcess()->GetID(),
5415 source->GetRenderViewHost()->GetRoutingID(),
mcnee432e47d2015-11-09 19:37:465416 page_scale_factor_is_one_);
5417 }
5418 }
mcnee336ea2c2017-05-23 22:50:595419#endif // !defined(OS_ANDROID)
mcnee432e47d2015-11-09 19:37:465420
Alexander Timin90c20c32020-08-12 15:28:325421 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5422 observer->OnPageScaleFactorChanged(page_scale_factor);
5423 });
mcnee432e47d2015-11-09 19:37:465424}
5425
W. James MacLean62198672019-06-04 16:46:105426void WebContentsImpl::OnTextAutosizerPageInfoChanged(
Henrique Ferreiroba535472020-04-21 11:38:365427 RenderFrameHostImpl* source,
5428 blink::mojom::TextAutosizerPageInfoPtr page_info) {
W. James MacLean62198672019-06-04 16:46:105429 // Keep a copy of |page_info| in case we create a new RenderView before
5430 // the next update.
Henrique Ferreiroba535472020-04-21 11:38:365431 text_autosizer_page_info_.main_frame_width = page_info->main_frame_width;
5432 text_autosizer_page_info_.main_frame_layout_width =
5433 page_info->main_frame_layout_width;
5434 text_autosizer_page_info_.device_scale_adjustment =
5435 page_info->device_scale_adjustment;
Antonio Gomesda7e03d2020-08-05 15:03:085436
5437 auto remote_frames_broadcast_callback = base::BindRepeating(
5438 [](const blink::mojom::TextAutosizerPageInfo& page_info,
5439 RenderFrameProxyHost* proxy_host) {
5440 DCHECK(proxy_host);
5441 proxy_host->GetAssociatedRemoteMainFrame()->UpdateTextAutosizerPageInfo(
5442 page_info.Clone());
5443 },
5444 text_autosizer_page_info_);
5445
5446 frame_tree_.root()->render_manager()->ExecuteRemoteFramesBroadcastMethod(
5447 std::move(remote_frames_broadcast_callback), source->GetSiteInstance());
W. James MacLean62198672019-06-04 16:46:105448}
5449
Kent Tamura8c9e0562018-11-06 07:02:195450void WebContentsImpl::EnumerateDirectory(
5451 RenderFrameHost* render_frame_host,
Kent Tamura3abb32d2020-07-02 00:23:015452 scoped_refptr<FileChooserImpl::FileSelectListenerImpl> listener,
Kent Tamura8c9e0562018-11-06 07:02:195453 const base::FilePath& directory_path) {
Avi Drissman1a55a9d62020-03-10 18:56:455454 // Any explicit focusing of another window while this WebContents is in
5455 // fullscreen can be used to confuse the user, so drop fullscreen.
5456 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
5457 listener->SetFullscreenBlock(std::move(fullscreen_block));
5458
Kent Tamura8c9e0562018-11-06 07:02:195459 if (delegate_)
5460 delegate_->EnumerateDirectory(this, std::move(listener), directory_path);
5461 else
5462 listener->FileSelectionCanceled();
[email protected]3a29a6e2011-08-24 18:26:215463}
5464
Dave Tapuskaf9fc3122019-10-18 19:42:555465void WebContentsImpl::RegisterProtocolHandler(RenderFrameHostImpl* source,
5466 const std::string& protocol,
5467 const GURL& url,
5468 const base::string16& title,
5469 bool user_gesture) {
nicka0ac8382016-12-15 23:59:235470 // TODO(nick): Do we need to apply FilterURL to |url|?
[email protected]e5f2de02012-07-20 22:15:435471 if (!delegate_)
5472 return;
5473
Raymes Khoury58373df2019-08-06 06:29:205474 if (!AreValidRegisterProtocolHandlerArguments(
5475 protocol, url, source->GetLastCommittedOrigin())) {
5476 ReceivedBadMessage(source->GetProcess(),
5477 bad_message::REGISTER_PROTOCOL_HANDLER_INVALID_URL);
[email protected]b9535422012-02-09 01:47:595478 return;
Raymes Khoury58373df2019-08-06 06:29:205479 }
[email protected]8f810632013-06-06 22:33:325480
Carlos Caballero8a6c6b72020-07-20 16:56:225481 delegate_->RegisterProtocolHandler(source, protocol, url, user_gesture);
[email protected]7d189022011-08-25 22:54:205482}
5483
Dave Tapuskaf9fc3122019-10-18 19:42:555484void WebContentsImpl::UnregisterProtocolHandler(RenderFrameHostImpl* source,
5485 const std::string& protocol,
5486 const GURL& url,
5487 bool user_gesture) {
nicka0ac8382016-12-15 23:59:235488 // TODO(nick): Do we need to apply FilterURL to |url|?
[email protected]f5273e52014-07-14 16:30:205489 if (!delegate_)
5490 return;
5491
Raymes Khoury58373df2019-08-06 06:29:205492 if (!AreValidRegisterProtocolHandlerArguments(
5493 protocol, url, source->GetLastCommittedOrigin())) {
5494 ReceivedBadMessage(source->GetProcess(),
5495 bad_message::REGISTER_PROTOCOL_HANDLER_INVALID_URL);
[email protected]f5273e52014-07-14 16:30:205496 return;
Raymes Khoury58373df2019-08-06 06:29:205497 }
[email protected]f5273e52014-07-14 16:30:205498
Carlos Caballero8a6c6b72020-07-20 16:56:225499 delegate_->UnregisterProtocolHandler(source, protocol, url, user_gesture);
[email protected]f5273e52014-07-14 16:30:205500}
5501
Marijn Kruisselbrink7f519672019-02-05 19:12:505502void WebContentsImpl::OnAppCacheAccessed(const GURL& manifest_url,
[email protected]b172aee2012-04-10 17:05:265503 bool blocked_by_policy) {
nicka0ac8382016-12-15 23:59:235504 // TODO(nick): Should we consider |source| here? Should we call FilterURL on
5505 // |manifest_url|?
5506
[email protected]7fc4bbb2011-09-08 21:23:105507 // Notify observers about navigation.
Alexander Timin90c20c32020-08-12 15:28:325508 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5509 observer->AppCacheAccessed(manifest_url, blocked_by_policy);
5510 });
[email protected]7fc4bbb2011-09-08 21:23:105511}
5512
Gyuyoung Kimc5f4ac12020-05-08 10:59:395513void WebContentsImpl::DomOperationResponse(const std::string& json_string) {
5514 // TODO(lukasza): The notification below should probably indicate which
5515 // RenderFrameHostImpl the message is coming from. This can enable tests to
5516 // talk to 2 frames at the same time, without being confused which frame a
5517 // given response comes from. See also a corresponding TODO in the
5518 // ExecuteScriptHelper in //content/public/test/browser_test_utils.cc
5519 NotificationService::current()->Notify(
5520 NOTIFICATION_DOM_OPERATION_RESPONSE, Source<WebContents>(this),
5521 Details<const std::string>(&json_string));
5522}
5523
Gyuyoung Kim4c50517842020-06-04 17:50:445524void WebContentsImpl::SavableResourceLinksResponse(
5525 RenderFrameHostImpl* source,
5526 const std::vector<GURL>& resources_list,
5527 blink::mojom::ReferrerPtr referrer,
5528 const std::vector<blink::mojom::SavableSubframePtr>& subframes) {
5529 save_package_->SavableResourceLinksResponse(source, resources_list,
5530 std::move(referrer), subframes);
5531}
5532
5533void WebContentsImpl::SavableResourceLinksError(RenderFrameHostImpl* source) {
5534 save_package_->SavableResourceLinksError(source);
5535}
5536
Alexander Timin17edc742020-04-23 18:22:185537void WebContentsImpl::OnServiceWorkerAccessed(
5538 RenderFrameHost* render_frame_host,
5539 const GURL& scope,
5540 AllowServiceWorkerResult allowed) {
Alexander Timin90c20c32020-08-12 15:28:325541 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5542 observer->OnServiceWorkerAccessed(render_frame_host, scope, allowed);
5543 });
Alexander Timin17edc742020-04-23 18:22:185544}
5545
5546void WebContentsImpl::OnServiceWorkerAccessed(
5547 NavigationHandle* navigation,
5548 const GURL& scope,
5549 AllowServiceWorkerResult allowed) {
Alexander Timin90c20c32020-08-12 15:28:325550 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5551 observer->OnServiceWorkerAccessed(navigation, scope, allowed);
5552 });
Alexander Timin17edc742020-04-23 18:22:185553}
5554
Miyoung Shincb6475a2019-11-09 10:49:455555void WebContentsImpl::OnColorChooserFactoryReceiver(
Julie Jeongeun Kim8e2879e2019-08-06 23:55:205556 mojo::PendingReceiver<blink::mojom::ColorChooserFactory> receiver) {
5557 color_chooser_factory_receivers_.Add(this, std::move(receiver));
Joel Hockey85b379d2017-12-11 10:42:135558}
5559
5560void WebContentsImpl::OpenColorChooser(
Julie Jeongeun Kim8e2879e2019-08-06 23:55:205561 mojo::PendingReceiver<blink::mojom::ColorChooser> chooser_receiver,
5562 mojo::PendingRemote<blink::mojom::ColorChooserClient> client,
[email protected]8ed16472014-04-11 19:02:485563 SkColor color,
Joel Hockey163835a2017-12-20 11:51:575564 std::vector<blink::mojom::ColorSuggestionPtr> suggestions) {
Joel Hockey85b379d2017-12-11 10:42:135565 content::ColorChooser* new_color_chooser =
Ivan Kotenkov2c0d2bb32017-11-01 15:41:285566 delegate_ ? delegate_->OpenColorChooser(this, color, suggestions)
5567 : nullptr;
[email protected]820957a2014-01-14 14:56:305568 if (!new_color_chooser)
[email protected]cb805452013-05-22 15:16:215569 return;
[email protected]8ed16472014-04-11 19:02:485570
Joel Hockey85b379d2017-12-11 10:42:135571 color_chooser_.reset();
5572 color_chooser_ = std::make_unique<ColorChooser>(
Julie Jeongeun Kim8e2879e2019-08-06 23:55:205573 new_color_chooser, std::move(chooser_receiver), std::move(client));
[email protected]da8543762012-03-20 08:52:205574}
5575
brettw4b461082016-11-19 18:55:165576#if BUILDFLAG(ENABLE_PLUGINS)
nicka0ac8382016-12-15 23:59:235577void WebContentsImpl::OnPepperInstanceCreated(RenderFrameHostImpl* source,
5578 int32_t pp_instance) {
Alexander Timin90c20c32020-08-12 15:28:325579 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5580 observer->PepperInstanceCreated();
5581 });
nicka0ac8382016-12-15 23:59:235582 pepper_playback_observer_->PepperInstanceCreated(source, pp_instance);
emaxxe70f5e12015-05-29 11:26:005583}
5584
nicka0ac8382016-12-15 23:59:235585void WebContentsImpl::OnPepperInstanceDeleted(RenderFrameHostImpl* source,
5586 int32_t pp_instance) {
Alexander Timin90c20c32020-08-12 15:28:325587 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5588 observer->PepperInstanceDeleted();
5589 });
nicka0ac8382016-12-15 23:59:235590 pepper_playback_observer_->PepperInstanceDeleted(source, pp_instance);
emaxxe70f5e12015-05-29 11:26:005591}
5592
nicka0ac8382016-12-15 23:59:235593void WebContentsImpl::OnPepperPluginHung(RenderFrameHostImpl* source,
5594 int plugin_child_id,
tommyclie6633ca72014-10-31 00:40:425595 const base::FilePath& path,
5596 bool is_hung) {
Steven Holte95922222018-09-14 20:06:235597 UMA_HISTOGRAM_COUNTS_1M("Pepper.PluginHung", 1);
tommyclie6633ca72014-10-31 00:40:425598
Alexander Timin90c20c32020-08-12 15:28:325599 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5600 observer->PluginHungStatusChanged(plugin_child_id, path, is_hung);
5601 });
tommyclie6633ca72014-10-31 00:40:425602}
5603
nicka0ac8382016-12-15 23:59:235604void WebContentsImpl::OnPepperStartsPlayback(RenderFrameHostImpl* source,
5605 int32_t pp_instance) {
5606 pepper_playback_observer_->PepperStartsPlayback(source, pp_instance);
zqzhang181047e62016-07-01 13:37:175607}
5608
nicka0ac8382016-12-15 23:59:235609void WebContentsImpl::OnPepperStopsPlayback(RenderFrameHostImpl* source,
5610 int32_t pp_instance) {
5611 pepper_playback_observer_->PepperStopsPlayback(source, pp_instance);
zqzhang181047e62016-07-01 13:37:175612}
5613
nicka0ac8382016-12-15 23:59:235614void WebContentsImpl::OnPluginCrashed(RenderFrameHostImpl* source,
5615 const base::FilePath& plugin_path,
tommyclie6633ca72014-10-31 00:40:425616 base::ProcessId plugin_pid) {
nicka0ac8382016-12-15 23:59:235617 // TODO(nick): Eliminate the |plugin_pid| parameter, which can't be trusted,
Gyuyoung Kim26c7bc92020-04-29 00:53:005618 // and is only used by WebTestControlHost.
Alexander Timin90c20c32020-08-12 15:28:325619 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5620 observer->PluginCrashed(plugin_path, plugin_pid);
5621 });
tommyclie6633ca72014-10-31 00:40:425622}
5623
[email protected]d8415ad92012-08-23 14:40:505624void WebContentsImpl::OnRequestPpapiBrokerPermission(
nicka0ac8382016-12-15 23:59:235625 RenderViewHostImpl* source,
5626 int ppb_broker_route_id,
[email protected]d8415ad92012-08-23 14:40:505627 const GURL& url,
[email protected]2dec8ec2013-02-07 19:20:345628 const base::FilePath& plugin_path) {
Avi Drissman0a2a967d2019-04-01 19:33:525629 base::OnceCallback<void(bool)> permission_result_callback = base::BindOnce(
nicka0ac8382016-12-15 23:59:235630 &WebContentsImpl::SendPpapiBrokerPermissionResult, base::Unretained(this),
5631 source->GetProcess()->GetID(), ppb_broker_route_id);
[email protected]8c8fc292012-11-23 18:57:165632 if (!delegate_) {
Tommy Nyquist4b749d02018-03-20 21:46:295633 std::move(permission_result_callback).Run(false);
[email protected]8c8fc292012-11-23 18:57:165634 return;
[email protected]d8415ad92012-08-23 14:40:505635 }
5636
Avi Drissman0a2a967d2019-04-01 19:33:525637 delegate_->RequestPpapiBrokerPermission(
5638 this, url, plugin_path, std::move(permission_result_callback));
[email protected]d8415ad92012-08-23 14:40:505639}
5640
nicka0ac8382016-12-15 23:59:235641void WebContentsImpl::SendPpapiBrokerPermissionResult(int process_id,
5642 int ppb_broker_route_id,
5643 bool result) {
5644 RenderProcessHost* rph = RenderProcessHost::FromID(process_id);
5645 if (rph) {
5646 // TODO(nick): Convert this from ViewMsg_ to a Ppapi msg, since it
5647 // is not routed to a RenderView.
5648 rph->Send(
5649 new ViewMsg_PpapiBrokerPermissionResult(ppb_broker_route_id, result));
5650 }
[email protected]d8415ad92012-08-23 14:40:505651}
brettw4b461082016-11-19 18:55:165652#endif // BUILDFLAG(ENABLE_PLUGINS)
[email protected]19be7a62012-10-01 23:03:375653
Miyoung Shin5709ab02020-02-19 06:50:415654void WebContentsImpl::UpdateFaviconURL(
5655 RenderFrameHost* source,
5656 std::vector<blink::mojom::FaviconURLPtr> candidates) {
lukasza178ff092017-06-07 23:39:505657 // Ignore favicons for non-main frame.
5658 if (source->GetParent()) {
5659 NOTREACHED();
5660 return;
5661 }
5662
pkotwiczf9bc20592015-04-21 18:57:065663 // We get updated favicon URLs after the page stops loading. If a cross-site
5664 // navigation occurs while a page is still loading, the initial page
5665 // may stop loading and send us updated favicon URLs after the navigation
5666 // for the new page has committed.
lukasza178ff092017-06-07 23:39:505667 if (!source->IsCurrent())
pkotwiczf9bc20592015-04-21 18:57:065668 return;
5669
Miyoung Shin5709ab02020-02-19 06:50:415670 favicon_urls_ = std::move(candidates);
Mounir Lamouri7b4a1f232019-12-23 16:32:105671
Alexander Timin90c20c32020-08-12 15:28:325672 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5673 observer->DidUpdateFaviconURL(source, favicon_urls_);
5674 });
[email protected]795c28972012-12-06 06:13:395675}
5676
qinmin72e8bd02016-10-21 19:35:375677void WebContentsImpl::SetIsOverlayContent(bool is_overlay_content) {
5678 is_overlay_content_ = is_overlay_content;
5679}
5680
Albert J. Wongfb64e142018-10-16 01:10:455681void WebContentsImpl::DidFirstVisuallyNonEmptyPaint(
5682 RenderViewHostImpl* source) {
nicka0ac8382016-12-15 23:59:235683 // TODO(nick): When this is ported to FrameHostMsg_, we should only listen if
5684 // |source| is the main frame.
Alexander Timin90c20c32020-08-12 15:28:325685 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5686 observer->DidFirstVisuallyNonEmptyPaint();
5687 });
Carlos Caballero1215f882019-10-29 15:58:435688 if (source->theme_color() != last_sent_theme_color_) {
yusufod41c5f92015-03-06 00:14:285689 // Theme color should have updated by now if there was one.
Alexander Timin90c20c32020-08-12 15:28:325690 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5691 observer->DidChangeThemeColor();
5692 });
Carlos Caballero1215f882019-10-29 15:58:435693 last_sent_theme_color_ = source->theme_color();
yusufod41c5f92015-03-06 00:14:285694 }
[email protected]9f268072013-11-07 00:02:155695}
[email protected]d9030b82013-07-19 08:26:065696
Kevin McNee068c3eb2020-04-03 18:24:195697bool WebContentsImpl::IsPortal() {
Adithya Srinivasan46b8a792019-02-01 14:47:235698 return portal();
5699}
5700
Kevin McNee94ea52f52020-06-23 17:42:065701WebContentsImpl* WebContentsImpl::GetPortalHostWebContents() {
5702 return portal() ? portal()->GetPortalHostContents() : nullptr;
5703}
5704
[email protected]17e286e2013-03-01 23:29:395705void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
Alexander Timin90c20c32020-08-12 15:28:325706 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5707 observer->BeforeFormRepostWarningShow();
5708 });
[email protected]17e286e2013-03-01 23:29:395709}
5710
[email protected]ec6c05f2013-10-23 18:41:575711void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
5712 Activate();
5713 if (delegate_)
5714 delegate_->ShowRepostFormWarningDialog(this);
5715}
5716
[email protected]b4c84012014-04-28 19:51:105717bool WebContentsImpl::HasAccessedInitialDocument() {
5718 return has_accessed_initial_document_;
5719}
5720
afakhry6f0c1ec22016-07-14 13:55:135721void WebContentsImpl::UpdateTitleForEntry(NavigationEntry* entry,
[email protected]fcf75d42013-12-03 20:11:265722 const base::string16& title) {
[email protected]fcf75d42013-12-03 20:11:265723 base::string16 final_title;
Avi Drissman93002212017-09-27 03:20:525724 base::TrimWhitespace(title, base::TRIM_ALL, &final_title);
[email protected]420ae012009-04-24 05:16:325725
[email protected]987fc3a2011-05-26 14:18:095726 // If a page is created via window.open and never navigated,
5727 // there will be no navigation entry. In this situation,
[email protected]73eb2602012-02-09 19:50:555728 // |page_title_when_no_navigation_entry_| will be used for page title.
[email protected]987fc3a2011-05-26 14:18:095729 if (entry) {
[email protected]36fc0392011-12-25 03:59:515730 if (final_title == entry->GetTitle())
afakhry6f0c1ec22016-07-14 13:55:135731 return; // Nothing changed, don't bother.
[email protected]420ae012009-04-24 05:16:325732
[email protected]36fc0392011-12-25 03:59:515733 entry->SetTitle(final_title);
Avi Drissman93002212017-09-27 03:20:525734
5735 // The title for display may differ from the title just set; grab it.
5736 final_title = entry->GetTitleForDisplay();
[email protected]987fc3a2011-05-26 14:18:095737 } else {
5738 if (page_title_when_no_navigation_entry_ == final_title)
afakhry6f0c1ec22016-07-14 13:55:135739 return; // Nothing changed, don't bother.
[email protected]987fc3a2011-05-26 14:18:095740
5741 page_title_when_no_navigation_entry_ = final_title;
5742 }
[email protected]420ae012009-04-24 05:16:325743
[email protected]420ae012009-04-24 05:16:325744 // Lastly, set the title for the view.
[email protected]790e2fd2011-09-21 20:28:235745 view_->SetPageTitle(final_title);
[email protected]420ae012009-04-24 05:16:325746
Alexander Timin90c20c32020-08-12 15:28:325747 observers_.ForEachObserver(
5748 [&](WebContentsObserver* observer) { observer->TitleWasSet(entry); });
afakhry6f0c1ec22016-07-14 13:55:135749 // Broadcast notifications when the UI should be updated.
5750 if (entry == controller_.GetEntryAtOffset(0))
5751 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE);
[email protected]420ae012009-04-24 05:16:325752}
5753
fdegansa696e5112015-04-17 01:57:595754void WebContentsImpl::SendChangeLoadProgress() {
[email protected]960b0372014-05-19 18:01:005755 loading_last_progress_update_ = base::TimeTicks::Now();
Alexander Timin90c20c32020-08-12 15:28:325756 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5757 observer->LoadProgressChanged(frame_tree_.load_progress());
5758 });
[email protected]960b0372014-05-19 18:01:005759}
5760
5761void WebContentsImpl::ResetLoadProgressState() {
fdegans1d16355162015-03-26 11:58:345762 frame_tree_.ResetLoadProgress();
[email protected]960b0372014-05-19 18:01:005763 loading_weak_factory_.InvalidateWeakPtrs();
5764 loading_last_progress_update_ = base::TimeTicks();
5765}
5766
clamy44e84ce2016-02-22 15:38:255767// Notifies the RenderWidgetHost instance about the fact that the page is
5768// loading, or done loading.
5769void WebContentsImpl::LoadingStateChanged(bool to_different_document,
clamy44e84ce2016-02-22 15:38:255770 LoadNotificationDetails* details) {
Nate Chapin22ea6592019-03-05 22:29:025771 if (is_being_destroyed_)
5772 return;
clamy44e84ce2016-02-22 15:38:255773
5774 bool is_loading = IsLoading();
5775
5776 if (!is_loading) {
5777 load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
5778 base::string16());
5779 load_state_host_.clear();
5780 upload_size_ = 0;
5781 upload_position_ = 0;
5782 }
5783
5784 GetRenderManager()->SetIsLoading(is_loading);
5785
5786 waiting_for_response_ = is_loading;
5787 is_load_to_different_document_ = to_different_document;
5788
5789 if (delegate_)
5790 delegate_->LoadingStateChanged(this, to_different_document);
5791 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD);
5792
5793 std::string url = (details ? details->url.possibly_invalid_spec() : "NULL");
5794 if (is_loading) {
5795 TRACE_EVENT_ASYNC_BEGIN2("browser,navigation", "WebContentsImpl Loading",
5796 this, "URL", url, "Main FrameTreeNode id",
5797 GetFrameTree()->root()->frame_tree_node_id());
Alexander Timin90c20c32020-08-12 15:28:325798 observers_.ForEachObserver(
5799 [&](WebContentsObserver* observer) { observer->DidStartLoading(); });
clamy44e84ce2016-02-22 15:38:255800 } else {
5801 TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
5802 this, "URL", url);
Alexander Timin90c20c32020-08-12 15:28:325803 observers_.ForEachObserver(
5804 [&](WebContentsObserver* observer) { observer->DidStopLoading(); });
clamy44e84ce2016-02-22 15:38:255805 }
5806
5807 // TODO(avi): Remove. http://crbug.com/170921
5808 int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP;
5809 NotificationDetails det = NotificationService::NoDetails();
5810 if (details)
5811 det = Details<LoadNotificationDetails>(details);
5812 NotificationService::current()->Notify(
5813 type, Source<NavigationController>(&controller_), det);
5814}
5815
danakja0bce4c952020-05-12 20:40:285816void WebContentsImpl::NotifyViewSwapped(RenderViewHost* old_view,
5817 RenderViewHost* new_view) {
5818 DCHECK_NE(old_view, new_view);
[email protected]420ae012009-04-24 05:16:325819 // After sending out a swap notification, we need to send a disconnect
5820 // notification so that clients that pick up a pointer to |this| can NULL the
5821 // pointer. See Bug 1230284.
5822 notify_disconnection_ = true;
Alexander Timin90c20c32020-08-12 15:28:325823 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5824 observer->RenderViewHostChanged(old_view, new_view);
5825 });
danakja0bce4c952020-05-12 20:40:285826 view_->RenderViewHostChanged(old_view, new_view);
Jinsuk Kimdc5284c22018-07-11 02:22:065827
Lucas Furukawa Gadanif9ea4fc2018-08-03 23:57:135828 // If this is an inner WebContents that has swapped views, we need to reattach
5829 // it to its outer WebContents.
5830 if (node_.outer_web_contents())
5831 ReattachToOuterWebContentsFrame();
5832
[email protected]7a846df2012-09-20 19:17:395833 // Ensure that the associated embedder gets cleared after a RenderViewHost
5834 // gets swapped, so we don't reuse the same embedder next time a
5835 // RenderViewHost is attached to this WebContents.
5836 RemoveBrowserPluginEmbedder();
[email protected]420ae012009-04-24 05:16:325837}
5838
danakja0bce4c952020-05-12 20:40:285839void WebContentsImpl::NotifyFrameSwapped(RenderFrameHost* old_frame,
5840 RenderFrameHost* new_frame,
Jinsuk Kim895b2c52018-07-03 06:49:165841 bool is_main_frame) {
Bo Liu168c8642017-08-28 18:26:025842#if defined(OS_ANDROID)
danakja0bce4c952020-05-12 20:40:285843 // Copy importance from |old_frame| if |new_frame| is a main frame.
5844 if (old_frame && !new_frame->GetParent()) {
5845 RenderWidgetHostImpl* old_widget =
5846 static_cast<RenderFrameHostImpl*>(old_frame)->GetRenderWidgetHost();
5847 RenderWidgetHostImpl* new_widget =
5848 static_cast<RenderFrameHostImpl*>(new_frame)->GetRenderWidgetHost();
5849 new_widget->SetImportance(old_widget->importance());
Bo Liu7c6779e92017-08-16 02:02:285850 }
Bo Liu168c8642017-08-28 18:26:025851#endif
Alexander Timin90c20c32020-08-12 15:28:325852 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5853 observer->RenderFrameHostChanged(old_frame, new_frame);
5854 });
[email protected]02d7b6e2014-06-24 21:01:505855}
5856
[email protected]da7a7182013-09-06 08:11:115857// TODO(avi): Remove this entire function because this notification is already
5858// covered by two observer functions. http://crbug.com/170921
[email protected]b172aee2012-04-10 17:05:265859void WebContentsImpl::NotifyDisconnected() {
[email protected]420ae012009-04-24 05:16:325860 if (!notify_disconnection_)
5861 return;
5862
5863 notify_disconnection_ = false;
[email protected]8ff00d72012-10-23 19:12:215864 NotificationService::current()->Notify(
5865 NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
5866 Source<WebContents>(this),
5867 NotificationService::NoDetails());
[email protected]420ae012009-04-24 05:16:325868}
5869
[email protected]cbb1ef592013-06-05 19:49:465870void WebContentsImpl::NotifyNavigationEntryCommitted(
5871 const LoadCommittedDetails& load_details) {
Alexander Timin90c20c32020-08-12 15:28:325872 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5873 observer->NavigationEntryCommitted(load_details);
5874 });
[email protected]cbb1ef592013-06-05 19:49:465875}
5876
Sam McNally5c087a32017-08-25 01:46:145877void WebContentsImpl::NotifyNavigationEntryChanged(
5878 const EntryChangedDetails& change_details) {
Alexander Timin90c20c32020-08-12 15:28:325879 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5880 observer->NavigationEntryChanged(change_details);
5881 });
Sam McNally5c087a32017-08-25 01:46:145882}
5883
5884void WebContentsImpl::NotifyNavigationListPruned(
5885 const PrunedDetails& pruned_details) {
Alexander Timin90c20c32020-08-12 15:28:325886 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5887 observer->NavigationListPruned(pruned_details);
5888 });
Sam McNally5c087a32017-08-25 01:46:145889}
5890
Christian Dullweber1af31e62018-02-22 11:49:485891void WebContentsImpl::NotifyNavigationEntriesDeleted() {
Alexander Timin90c20c32020-08-12 15:28:325892 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5893 observer->NavigationEntriesDeleted();
5894 });
Christian Dullweber1af31e62018-02-22 11:49:485895}
5896
rockotf62002a2016-09-15 00:08:595897void WebContentsImpl::OnAssociatedInterfaceRequest(
5898 RenderFrameHost* render_frame_host,
5899 const std::string& interface_name,
5900 mojo::ScopedInterfaceEndpointHandle handle) {
Julie Jeongeun Kim7d0986172019-12-04 03:17:255901 auto it = receiver_sets_.find(interface_name);
5902 if (it != receiver_sets_.end())
5903 it->second->OnReceiverForFrame(render_frame_host, std::move(handle));
rockotf62002a2016-09-15 00:08:595904}
5905
Ben Goodger9e24929e2017-07-21 03:13:405906void WebContentsImpl::OnInterfaceRequest(
5907 RenderFrameHost* render_frame_host,
5908 const std::string& interface_name,
5909 mojo::ScopedMessagePipeHandle* interface_pipe) {
Alexander Timin90c20c32020-08-12 15:28:325910 for (auto& observer : observers_.observer_list()) {
Ben Goodger9e24929e2017-07-21 03:13:405911 observer.OnInterfaceRequestFromFrame(render_frame_host, interface_name,
5912 interface_pipe);
5913 if (!interface_pipe->is_valid())
5914 break;
5915 }
5916}
5917
Varun Khaneja5da94302019-06-25 04:48:105918void WebContentsImpl::OnDidBlockNavigation(
5919 const GURL& blocked_url,
5920 const GURL& initiator_url,
Abhijeet Kandalkarde7348e2020-01-13 06:06:545921 blink::mojom::NavigationBlockedReason reason) {
Nicolas Dossou-gbetebcab2472017-09-09 12:28:405922 if (delegate_)
Varun Khaneja5da94302019-06-25 04:48:105923 delegate_->OnDidBlockNavigation(this, blocked_url, initiator_url, reason);
Nicolas Dossou-gbetebcab2472017-09-09 12:28:405924}
5925
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:415926const GURL& WebContentsImpl::GetMainFrameLastCommittedURL() {
[email protected]c31a84802014-04-03 15:55:495927 return GetLastCommittedURL();
5928}
5929
[email protected]b849847b2013-12-10 21:57:585930void WebContentsImpl::RenderFrameCreated(RenderFrameHost* render_frame_host) {
Alexander Timin90c20c32020-08-12 15:28:325931 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5932 observer->RenderFrameCreated(render_frame_host);
5933 });
dmazzonif8a31042016-12-03 00:52:135934 UpdateAccessibilityModeOnFrame(render_frame_host);
clamy91b7abf2016-03-24 15:17:455935
Becca Hughesd11d6502018-07-31 17:01:285936 if (display_cutout_host_impl_)
5937 display_cutout_host_impl_->RenderFrameCreated(render_frame_host);
5938
clamy91b7abf2016-03-24 15:17:455939 if (!render_frame_host->IsRenderFrameLive() || render_frame_host->GetParent())
5940 return;
5941
5942 NavigationEntry* entry = controller_.GetPendingEntry();
5943 if (entry && entry->IsViewSourceMode()) {
5944 // Put the renderer in view source mode.
Dave Tapuska3c05e1c2019-11-27 18:34:185945 static_cast<RenderFrameHostImpl*>(render_frame_host)
5946 ->GetAssociatedLocalFrame()
5947 ->EnableViewSourceMode();
clamy91b7abf2016-03-24 15:17:455948 }
[email protected]b849847b2013-12-10 21:57:585949}
5950
5951void WebContentsImpl::RenderFrameDeleted(RenderFrameHost* render_frame_host) {
yilkal172da772019-11-06 22:49:075952 if (IsBeingDestroyed() && !render_frame_host->GetParent() &&
5953 first_navigation_completed_ &&
Hajime Hoshibbc509c2020-04-06 08:55:085954 !render_frame_host->IsInBackForwardCache()) {
yilkal796e89e2019-10-02 23:58:285955 // Main frame has been deleted because WebContents is being destroyed.
Rakina Zata Amni74627df2019-10-15 02:03:175956 // Note that we aren't recording this here when the main frame is in the
5957 // back-forward cache because that means we've actually already navigated
5958 // away from it (and we got to this point because the WebContents is
yilkal172da772019-11-06 22:49:075959 // deleted), which means |max_loaded_frame_count_| is already overwritten.
5960 // The |max_loaded_frame_count_| value will instead be recorded from within
5961 // |WebContentsImpl::DidFinishNavigation()|.
5962 RecordMaxFrameCountUMA(max_loaded_frame_count_);
yilkal796e89e2019-10-02 23:58:285963 }
5964
Alexander Timin90c20c32020-08-12 15:28:325965 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5966 observer->RenderFrameDeleted(render_frame_host);
5967 });
zqzhang7b6f4f02016-12-07 22:10:225968#if BUILDFLAG(ENABLE_PLUGINS)
5969 pepper_playback_observer_->RenderFrameDeleted(render_frame_host);
5970#endif
Becca Hughesfd5d8f892018-06-14 18:23:365971
Becca Hughesd11d6502018-07-31 17:01:285972 if (display_cutout_host_impl_)
5973 display_cutout_host_impl_->RenderFrameDeleted(render_frame_host);
5974
Becca Hughesfd5d8f892018-06-14 18:23:365975 // Remove any fullscreen state that the frame has stored.
5976 FullscreenStateChanged(render_frame_host, false /* is_fullscreen */);
[email protected]b849847b2013-12-10 21:57:585977}
5978
[email protected]a09d53ce2014-01-31 00:46:425979void WebContentsImpl::ShowContextMenu(RenderFrameHost* render_frame_host,
5980 const ContextMenuParams& params) {
avie9fd8722017-04-10 16:17:585981 // If a renderer fires off a second command to show a context menu before the
5982 // first context menu is closed, just ignore it. https://crbug.com/707534
ekaramadf6750aa2017-06-06 18:29:425983 if (showing_context_menu_)
avie9fd8722017-04-10 16:17:585984 return;
5985
[email protected]077e704b2014-05-23 19:24:105986 ContextMenuParams context_menu_params(params);
[email protected]a09d53ce2014-01-31 00:46:425987 // Allow WebContentsDelegates to handle the context menu operation first.
Joel Klinghed0ea22ea2019-02-20 22:04:225988 if (delegate_ &&
5989 delegate_->HandleContextMenu(render_frame_host, context_menu_params))
[email protected]a09d53ce2014-01-31 00:46:425990 return;
5991
[email protected]077e704b2014-05-23 19:24:105992 render_view_host_delegate_view_->ShowContextMenu(render_frame_host,
5993 context_menu_params);
[email protected]a09d53ce2014-01-31 00:46:425994}
5995
Avi Drissman4891b852018-09-25 18:12:585996namespace {
5997// Normalizes the line endings: \r\n -> \n, lone \r -> \n.
5998base::string16 NormalizeLineBreaks(const base::string16& source) {
5999 static const base::NoDestructor<base::string16> kReturnNewline(
6000 base::ASCIIToUTF16("\r\n"));
6001 static const base::NoDestructor<base::string16> kReturn(
6002 base::ASCIIToUTF16("\r"));
6003 static const base::NoDestructor<base::string16> kNewline(
6004 base::ASCIIToUTF16("\n"));
6005
6006 std::vector<base::StringPiece16> pieces;
6007
6008 for (const auto& rn_line : base::SplitStringPieceUsingSubstr(
6009 source, *kReturnNewline, base::KEEP_WHITESPACE,
6010 base::SPLIT_WANT_ALL)) {
6011 auto r_lines = base::SplitStringPieceUsingSubstr(
6012 rn_line, *kReturn, base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
6013 std::move(std::begin(r_lines), std::end(r_lines),
6014 std::back_inserter(pieces));
6015 }
6016
6017 return base::JoinString(pieces, *kNewline);
6018}
6019} // namespace
6020
Dave Tapuskacdf545cc2020-01-23 18:38:526021void WebContentsImpl::RunJavaScriptDialog(
6022 RenderFrameHost* render_frame_host,
6023 const base::string16& message,
6024 const base::string16& default_prompt,
6025 JavaScriptDialogType dialog_type,
6026 JavaScriptDialogCallback response_callback) {
Avi Drissman2ccbb402018-03-20 21:11:366027 // Ensure that if showing a dialog is the first thing that a page does, that
6028 // the contents of the previous page aren't shown behind it. This is required
6029 // because showing a dialog freezes the renderer, so no frames will be coming
6030 // from it. https://crbug.com/823353
6031 auto* render_widget_host_impl =
6032 static_cast<RenderFrameHostImpl*>(render_frame_host)
6033 ->GetRenderWidgetHost();
6034 if (render_widget_host_impl)
6035 render_widget_host_impl->ForceFirstFrameAfterNavigationTimeout();
6036
avi0720b02e2017-06-13 03:22:136037 // Running a dialog causes an exit to webpage-initiated fullscreen.
6038 // http://crbug.com/728276
Avi Drissman1a55a9d62020-03-10 18:56:456039 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
avi0720b02e2017-06-13 03:22:136040
Avi Drissman1a55a9d62020-03-10 18:56:456041 auto callback =
6042 base::BindOnce(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
6043 render_frame_host->GetProcess()->GetID(),
6044 render_frame_host->GetRoutingID(),
6045 std::move(response_callback), std::move(fullscreen_block));
Pavel Feldman3c1842b2017-08-02 05:00:166046
Pavel Feldman3c1842b2017-08-02 05:00:166047 std::vector<protocol::PageHandler*> page_handlers =
6048 protocol::PageHandler::EnabledForWebContents(this);
6049
Pavel Feldmanfab3cb62017-10-05 01:02:016050 if (delegate_)
6051 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
6052
Charlie Reis96077362019-07-04 00:34:046053 // While a JS message dialog is showing, defer commits in this WebContents.
6054 javascript_dialog_navigation_deferrer_ =
6055 std::make_unique<JavaScriptDialogNavigationDeferrer>();
6056
Carlos IL07f282f2020-05-15 22:58:296057 // Suppress JavaScript dialogs when requested.
6058 bool should_suppress = delegate_ && delegate_->ShouldSuppressDialogs(this);
Pavel Feldman1c587bc52018-04-04 21:16:056059 bool has_non_devtools_handlers = delegate_ && dialog_manager_;
6060 bool has_handlers = page_handlers.size() || has_non_devtools_handlers;
Pavel Feldmanfab3cb62017-10-05 01:02:016061 bool suppress_this_message = should_suppress || !has_handlers;
6062
6063 if (suppress_this_message) {
Avi Drissmane04d3992017-10-05 15:11:366064 std::move(callback).Run(true, false, base::string16());
Pavel Feldman3c1842b2017-08-02 05:00:166065 return;
6066 }
6067
6068 scoped_refptr<CloseDialogCallbackWrapper> wrapper =
Avi Drissmane04d3992017-10-05 15:11:366069 new CloseDialogCallbackWrapper(std::move(callback));
Pavel Feldman3c1842b2017-08-02 05:00:166070
6071 is_showing_javascript_dialog_ = true;
6072
Avi Drissman4891b852018-09-25 18:12:586073 base::string16 normalized_message = NormalizeLineBreaks(message);
6074
Pavel Feldman3c1842b2017-08-02 05:00:166075 for (auto* handler : page_handlers) {
Avi Drissmane04d3992017-10-05 15:11:366076 handler->DidRunJavaScriptDialog(
Avi Drissman4891b852018-09-25 18:12:586077 render_frame_host->GetLastCommittedURL(), normalized_message,
6078 default_prompt, dialog_type, has_non_devtools_handlers,
Avi Drissmane04d3992017-10-05 15:11:366079 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
Pavel Feldman3c1842b2017-08-02 05:00:166080 }
6081
6082 if (dialog_manager_) {
[email protected]87de04b02014-04-08 22:14:496083 dialog_manager_->RunJavaScriptDialog(
Avi Drissman4891b852018-09-25 18:12:586084 this, render_frame_host, dialog_type, normalized_message,
6085 default_prompt,
Avi Drissmane04d3992017-10-05 15:11:366086 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false),
6087 &suppress_this_message);
[email protected]87de04b02014-04-08 22:14:496088 }
6089
6090 if (suppress_this_message) {
6091 // If we are suppressing messages, just reply as if the user immediately
6092 // pressed "Cancel", passing true to |dialog_was_suppressed|.
Avi Drissmane04d3992017-10-05 15:11:366093 wrapper->Run(true, false, base::string16());
[email protected]87de04b02014-04-08 22:14:496094 }
[email protected]87de04b02014-04-08 22:14:496095}
6096
6097void WebContentsImpl::RunBeforeUnloadConfirm(
[email protected]39f2f9252014-05-03 00:54:016098 RenderFrameHost* render_frame_host,
[email protected]87de04b02014-04-08 22:14:496099 bool is_reload,
Dave Tapuskacdf545cc2020-01-23 18:38:526100 JavaScriptDialogCallback response_callback) {
Avi Drissman2ccbb402018-03-20 21:11:366101 // Ensure that if showing a dialog is the first thing that a page does, that
6102 // the contents of the previous page aren't shown behind it. This is required
6103 // because showing a dialog freezes the renderer, so no frames will be coming
6104 // from it. https://crbug.com/823353
6105 auto* render_widget_host_impl =
6106 static_cast<RenderFrameHostImpl*>(render_frame_host)
6107 ->GetRenderWidgetHost();
6108 if (render_widget_host_impl)
6109 render_widget_host_impl->ForceFirstFrameAfterNavigationTimeout();
6110
avi0720b02e2017-06-13 03:22:136111 // Running a dialog causes an exit to webpage-initiated fullscreen.
6112 // http://crbug.com/728276
Avi Drissman1a55a9d62020-03-10 18:56:456113 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
avi0720b02e2017-06-13 03:22:136114
[email protected]39f2f9252014-05-03 00:54:016115 RenderFrameHostImpl* rfhi =
6116 static_cast<RenderFrameHostImpl*>(render_frame_host);
[email protected]87de04b02014-04-08 22:14:496117 if (delegate_)
6118 delegate_->WillRunBeforeUnloadConfirm();
6119
Avi Drissman1a55a9d62020-03-10 18:56:456120 auto callback =
6121 base::BindOnce(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
6122 render_frame_host->GetProcess()->GetID(),
6123 render_frame_host->GetRoutingID(),
6124 std::move(response_callback), std::move(fullscreen_block));
Pavel Feldman3c1842b2017-08-02 05:00:166125
Pavel Feldman3c1842b2017-08-02 05:00:166126 std::vector<protocol::PageHandler*> page_handlers =
6127 protocol::PageHandler::EnabledForWebContents(this);
6128
Pavel Feldmanfab3cb62017-10-05 01:02:016129 if (delegate_)
6130 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
6131
Charlie Reis96077362019-07-04 00:34:046132 // While a JS beforeunload dialog is showing, defer commits in this
6133 // WebContents.
6134 javascript_dialog_navigation_deferrer_ =
6135 std::make_unique<JavaScriptDialogNavigationDeferrer>();
6136
Sreeja Kamishettyf352e302020-06-10 13:21:246137 bool should_suppress = !rfhi->IsCurrent() ||
Tarun Bansalc209b742019-12-24 06:53:256138 (delegate_ && delegate_->ShouldSuppressDialogs(this));
Pavel Feldman1c587bc52018-04-04 21:16:056139 bool has_non_devtools_handlers = delegate_ && dialog_manager_;
6140 bool has_handlers = page_handlers.size() || has_non_devtools_handlers;
Pavel Feldmanfab3cb62017-10-05 01:02:016141 if (should_suppress || !has_handlers) {
Avi Drissmane04d3992017-10-05 15:11:366142 std::move(callback).Run(false, true, base::string16());
[email protected]87de04b02014-04-08 22:14:496143 return;
6144 }
6145
6146 is_showing_before_unload_dialog_ = true;
Pavel Feldman3c1842b2017-08-02 05:00:166147
6148 scoped_refptr<CloseDialogCallbackWrapper> wrapper =
Avi Drissmane04d3992017-10-05 15:11:366149 new CloseDialogCallbackWrapper(std::move(callback));
Pavel Feldman3c1842b2017-08-02 05:00:166150
6151 GURL frame_url = rfhi->GetLastCommittedURL();
6152 for (auto* handler : page_handlers) {
Avi Drissmane04d3992017-10-05 15:11:366153 handler->DidRunBeforeUnloadConfirm(
Pavel Feldman1c587bc52018-04-04 21:16:056154 frame_url, has_non_devtools_handlers,
Avi Drissmane04d3992017-10-05 15:11:366155 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
Pavel Feldman3c1842b2017-08-02 05:00:166156 }
6157
6158 if (dialog_manager_) {
Avi Drissmane04d3992017-10-05 15:11:366159 dialog_manager_->RunBeforeUnloadDialog(
Avi Drissmanff9ed752017-11-28 21:18:126160 this, render_frame_host, is_reload,
Avi Drissmane04d3992017-10-05 15:11:366161 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
Pavel Feldman3c1842b2017-08-02 05:00:166162 }
[email protected]87de04b02014-04-08 22:14:496163}
6164
Kent Tamurac260c9a2018-09-14 09:10:566165void WebContentsImpl::RunFileChooser(
6166 RenderFrameHost* render_frame_host,
Kent Tamura3abb32d2020-07-02 00:23:016167 scoped_refptr<FileChooserImpl::FileSelectListenerImpl> listener,
Kent Tamurac260c9a2018-09-14 09:10:566168 const blink::mojom::FileChooserParams& params) {
Avi Drissman3d41e7712018-08-27 21:18:086169 // Any explicit focusing of another window while this WebContents is in
6170 // fullscreen can be used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:456171 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
6172 listener->SetFullscreenBlock(std::move(fullscreen_block));
Avi Drissman3d41e7712018-08-27 21:18:086173
naskoada75b22016-06-11 16:09:466174 if (delegate_)
Kent Tamura512a27e2018-10-04 00:49:326175 delegate_->RunFileChooser(render_frame_host, std::move(listener), params);
6176 else
6177 listener->FileSelectionCanceled();
naskoada75b22016-06-11 16:09:466178}
6179
[email protected]a86c0e962013-12-17 17:10:396180WebContents* WebContentsImpl::GetAsWebContents() {
6181 return this;
6182}
6183
mcnee336ea2c2017-05-23 22:50:596184#if !defined(OS_ANDROID)
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416185double WebContentsImpl::GetPendingPageZoomLevel() {
wjmaclean64951902016-04-29 20:59:126186 NavigationEntry* pending_entry = GetController().GetPendingEntry();
6187 if (!pending_entry)
6188 return HostZoomMap::GetZoomLevel(this);
6189
6190 GURL url = pending_entry->GetURL();
6191 return HostZoomMap::GetForWebContents(this)->GetZoomLevelForHostAndScheme(
6192 url.scheme(), net::GetHostOrSpecFromURL(url));
6193}
mcnee336ea2c2017-05-23 22:50:596194#endif // !defined(OS_ANDROID)
wjmaclean64951902016-04-29 20:59:126195
qinmin72e8bd02016-10-21 19:35:376196bool WebContentsImpl::HideDownloadUI() const {
6197 return is_overlay_content_;
6198}
6199
mlamouri5cd9ae82017-02-18 11:05:096200bool WebContentsImpl::HasPersistentVideo() const {
6201 return has_persistent_video_;
6202}
6203
Ian Vollick5d5c37f2019-06-19 22:50:576204bool WebContentsImpl::IsSpatialNavigationDisabled() const {
6205 return is_spatial_navigation_disabled_;
6206}
6207
Albert J. Wong65fe64d2019-09-20 02:48:146208RenderFrameHostImpl* WebContentsImpl::GetPendingMainFrame() {
clamy610c63b32017-12-22 15:05:186209 return GetRenderManager()->speculative_frame_host();
Alex Moshchuk27caae82017-09-11 23:11:186210}
6211
mlamourie52c1b542017-02-23 14:57:506212bool WebContentsImpl::HasActiveEffectivelyFullscreenVideo() const {
6213 return media_web_contents_observer_->HasActiveEffectivelyFullscreenVideo();
6214}
6215
François Beaufortad6c5232018-02-26 11:00:446216bool WebContentsImpl::IsPictureInPictureAllowedForFullscreenVideo() const {
6217 return media_web_contents_observer_
6218 ->IsPictureInPictureAllowedForFullscreenVideo();
6219}
6220
ekaramada110f642016-12-21 19:47:286221bool WebContentsImpl::IsFocusedElementEditable() {
6222 RenderFrameHostImpl* frame = GetFocusedFrame();
6223 return frame && frame->has_focused_editable_element();
6224}
6225
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416226bool WebContentsImpl::IsShowingContextMenu() {
ekaramadf6750aa2017-06-06 18:29:426227 return showing_context_menu_;
6228}
6229
6230void WebContentsImpl::SetShowingContextMenu(bool showing) {
6231 DCHECK_NE(showing_context_menu_, showing);
6232 showing_context_menu_ = showing;
6233
6234 if (auto* view = GetRenderWidgetHostView()) {
6235 // Notify the main frame's RWHV to run the platform-specific code, if any.
6236 static_cast<RenderWidgetHostViewBase*>(view)->SetShowingContextMenu(
6237 showing);
6238 }
6239}
6240
ekaramada110f642016-12-21 19:47:286241void WebContentsImpl::ClearFocusedElement() {
6242 if (auto* frame = GetFocusedFrame())
6243 frame->ClearFocusedElement();
6244}
6245
danakj77eb7e82020-01-09 19:38:466246bool WebContentsImpl::IsNeverComposited() {
[email protected]7912e822014-04-16 02:37:036247 if (!delegate_)
6248 return false;
danakj77eb7e82020-01-09 19:38:466249 return delegate_->IsNeverComposited(this);
[email protected]7912e822014-04-16 02:37:036250}
6251
[email protected]5a3bdf52012-05-24 15:12:576252RenderViewHostDelegateView* WebContentsImpl::GetDelegateView() {
6253 return render_view_host_delegate_view_;
[email protected]420ae012009-04-24 05:16:326254}
6255
Peter Marshall2dc74e92020-07-29 20:02:306256blink::mojom::RendererPreferences WebContentsImpl::GetRendererPrefs() const {
[email protected]840b1512009-07-21 16:53:466257 return renderer_preferences_;
[email protected]80d96fa2009-06-10 22:34:516258}
6259
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166260RenderFrameHostImpl* WebContentsImpl::GetOuterWebContentsFrame() {
6261 if (GetOuterDelegateFrameTreeNodeId() ==
6262 FrameTreeNode::kFrameTreeNodeInvalidId) {
6263 return nullptr;
6264 }
6265
6266 FrameTreeNode* outer_node =
6267 FrameTreeNode::GloballyFindByID(GetOuterDelegateFrameTreeNodeId());
6268 // The outer node should be in the outer WebContents.
6269 DCHECK_EQ(outer_node->frame_tree(), GetOuterWebContents()->GetFrameTree());
Alexander Timin381e7e182020-04-28 19:04:036270 return outer_node->parent();
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166271}
6272
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416273WebContentsImpl* WebContentsImpl::GetOuterWebContents() {
Lucas Furukawa Gadani105de1e812018-05-31 19:38:396274 return node_.outer_web_contents();
avallee0206f782016-07-28 18:55:336275}
6276
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166277std::vector<WebContents*> WebContentsImpl::GetInnerWebContents() {
6278 std::vector<WebContents*> all_inner_contents;
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166279 const auto& inner_contents = node_.GetInnerWebContents();
6280 all_inner_contents.insert(all_inner_contents.end(), inner_contents.begin(),
6281 inner_contents.end());
6282 return all_inner_contents;
6283}
6284
Jeremy Roman7e70bf92020-01-07 23:23:586285WebContentsImpl* WebContentsImpl::GetResponsibleWebContents() {
6286 // Iteratively ask delegates which other contents is responsible until a fixed
6287 // point is found.
6288 WebContentsImpl* contents = this;
6289 while (WebContentsDelegate* delegate = contents->GetDelegate()) {
6290 auto* responsible_contents = static_cast<WebContentsImpl*>(
6291 delegate->GetResponsibleWebContents(contents));
6292 if (responsible_contents == contents)
6293 break;
6294 contents = responsible_contents;
6295 }
6296 return contents;
6297}
6298
avallee0206f782016-07-28 18:55:336299WebContentsImpl* WebContentsImpl::GetFocusedWebContents() {
lfg601233692017-03-06 22:45:446300 return GetOutermostWebContents()->node_.focused_web_contents();
avallee0206f782016-07-28 18:55:336301}
6302
avallee9993fca2016-11-17 06:16:506303bool WebContentsImpl::ContainsOrIsFocusedWebContents() {
6304 for (WebContentsImpl* focused_contents = GetFocusedWebContents();
6305 focused_contents;
6306 focused_contents = focused_contents->GetOuterWebContents()) {
6307 if (focused_contents == this)
6308 return true;
6309 }
6310
6311 return false;
6312}
6313
W. James MacLean9437b5bf2019-12-06 17:33:446314void WebContentsImpl::RemoveBrowserPluginEmbedder() {
6315 browser_plugin_embedder_.reset();
6316}
6317
avallee0206f782016-07-28 18:55:336318WebContentsImpl* WebContentsImpl::GetOutermostWebContents() {
6319 WebContentsImpl* root = this;
6320 while (root->GetOuterWebContents())
6321 root = root->GetOuterWebContents();
6322 return root;
6323}
6324
avalleed68cdd12017-06-21 22:07:276325void WebContentsImpl::FocusOuterAttachmentFrameChain() {
6326 WebContentsImpl* outer_contents = GetOuterWebContents();
6327 if (!outer_contents)
6328 return;
6329
6330 FrameTreeNode* outer_node =
6331 FrameTreeNode::GloballyFindByID(GetOuterDelegateFrameTreeNodeId());
6332 outer_contents->frame_tree_.SetFocusedFrame(outer_node, nullptr);
6333
6334 // For a browser initiated focus change, let embedding renderer know of the
6335 // change. Otherwise, if the currently focused element is just across a
6336 // process boundary in focus order, it will not be possible to move across
6337 // that boundary. This is because the target element will already be focused
6338 // (that renderer was not notified) and drop the event.
6339 if (GetRenderManager()->GetProxyToOuterDelegate())
6340 GetRenderManager()->GetProxyToOuterDelegate()->SetFocusedFrame();
6341
6342 outer_contents->FocusOuterAttachmentFrameChain();
6343}
6344
Sean Toppingbbc4a2bd2019-01-30 02:16:146345void WebContentsImpl::InnerWebContentsCreated(WebContents* inner_web_contents) {
Alexander Timin90c20c32020-08-12 15:28:326346 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6347 observer->InnerWebContentsCreated(inner_web_contents);
6348 });
Sean Toppingbbc4a2bd2019-01-30 02:16:146349}
6350
Jeremy Roman03ce13ce2020-05-29 22:16:576351void WebContentsImpl::InnerWebContentsAttached(
6352 WebContents* inner_web_contents) {
6353 if (inner_web_contents->IsCurrentlyAudible())
6354 OnAudioStateChanged();
6355}
6356
6357void WebContentsImpl::InnerWebContentsDetached(
6358 WebContents* inner_web_contents) {
6359 if (!is_being_destroyed_)
6360 OnAudioStateChanged();
6361}
6362
[email protected]b172aee2012-04-10 17:05:266363void WebContentsImpl::RenderViewCreated(RenderViewHost* render_view_host) {
[email protected]86f98a22013-03-20 14:35:006364 if (delegate_)
[email protected]e85165c642014-06-10 14:34:316365 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
[email protected]a6b73c62013-02-11 23:05:086366
[email protected]8ff00d72012-10-23 19:12:216367 NotificationService::current()->Notify(
6368 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
6369 Source<WebContents>(this),
6370 Details<RenderViewHost>(render_view_host));
[email protected]420ae012009-04-24 05:16:326371
Alexander Timin90c20c32020-08-12 15:28:326372 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6373 observer->RenderViewCreated(render_view_host);
6374 });
Joel Einbinder848001c2017-09-19 21:39:316375 if (delegate_)
6376 RenderFrameDevToolsAgentHost::WebContentsCreated(this);
[email protected]420ae012009-04-24 05:16:326377}
6378
[email protected]b172aee2012-04-10 17:05:266379void WebContentsImpl::RenderViewReady(RenderViewHost* rvh) {
[email protected]151a63d2011-12-20 22:32:526380 if (rvh != GetRenderViewHost()) {
[email protected]420ae012009-04-24 05:16:326381 // Don't notify the world, since this came from a renderer in the
6382 // background.
6383 return;
6384 }
6385
dmazzoni62111452017-04-28 23:46:556386 RenderWidgetHostViewBase* rwhv =
6387 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
6388 if (rwhv)
6389 rwhv->SetMainFrameAXTreeID(GetMainFrame()->GetAXTreeID());
6390
[email protected]da7a7182013-09-06 08:11:116391 notify_disconnection_ = true;
[email protected]da7a7182013-09-06 08:11:116392
[email protected]be1f56ab2011-12-22 06:55:316393 bool was_crashed = IsCrashed();
[email protected]443b80e2010-12-14 00:42:236394 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING, 0);
[email protected]9d8a4642009-07-29 17:25:306395
6396 // Restore the focus to the tab (otherwise the focus will be on the top
6397 // window).
[email protected]484ae5912010-09-29 19:16:146398 if (was_crashed && !FocusLocationBarByDefault() &&
6399 (!delegate_ || delegate_->ShouldFocusPageAfterCrash())) {
[email protected]f3615f02013-02-26 06:09:066400 view_->Focus();
[email protected]484ae5912010-09-29 19:16:146401 }
[email protected]32ded2212011-11-10 18:51:436402
Alexander Timin90c20c32020-08-12 15:28:326403 observers_.ForEachObserver(
6404 [&](WebContentsObserver* observer) { observer->RenderViewReady(); });
Jinsuk Kim895b2c52018-07-03 06:49:166405 view_->RenderViewReady();
[email protected]420ae012009-04-24 05:16:326406}
6407
[email protected]ec6a7eb2013-04-22 17:34:226408void WebContentsImpl::RenderViewTerminated(RenderViewHost* rvh,
6409 base::TerminationStatus status,
6410 int error_code) {
[email protected]151a63d2011-12-20 22:32:526411 if (rvh != GetRenderViewHost()) {
[email protected]420ae012009-04-24 05:16:326412 // The pending page's RenderViewHost is gone.
6413 return;
6414 }
6415
[email protected]2fcdcc32014-03-05 02:14:076416 // Ensure fullscreen mode is exited in the |delegate_| since a crashed
6417 // renderer may not have made a clean exit.
Avi Drissman97aef042020-06-30 21:04:486418 if (IsFullscreen())
bokanece34a82016-01-28 19:49:466419 ExitFullscreenMode(false);
[email protected]2fcdcc32014-03-05 02:14:076420
Jennifer Apacibleb4b972a2018-06-07 04:41:026421 // Ensure any video in Picture-in-Picture is exited in the |delegate_| since
6422 // a crashed renderer may not have made a clean exit.
6423 if (HasPictureInPictureVideo())
6424 ExitPictureInPicture();
6425
[email protected]698191dc2014-02-25 01:06:136426 // Cancel any visible dialogs so they are not left dangling over the sad tab.
creis89a0f782015-05-27 16:13:176427 CancelActiveAndPendingDialogs();
[email protected]698191dc2014-02-25 01:06:136428
dalecurtis3d1e1302017-02-20 22:33:256429 audio_stream_monitor_.RenderProcessGone(rvh->GetProcess()->GetID());
6430
[email protected]960b0372014-05-19 18:01:006431 // Reset the loading progress. TODO(avi): What does it mean to have a
6432 // "renderer crash" when there is more than one renderer process serving a
6433 // webpage? Once this function is called at a more granular frame level, we
6434 // probably will need to more granularly reset the state here.
6435 ResetLoadProgressState();
clamy44e84ce2016-02-22 15:38:256436 NotifyDisconnected();
6437 SetIsCrashed(status, error_code);
[email protected]960b0372014-05-19 18:01:006438
Alexander Timin90c20c32020-08-12 15:28:326439 TRACE_EVENT0("content", "Dispatching WebContentsObserver::RenderProcessGone");
6440 // Some observers might destroy WebContents in RenderViewTerminated.
6441 base::WeakPtr<WebContentsImpl> weak_ptr = weak_factory_.GetWeakPtr();
6442 auto crashed_status = GetCrashedStatus();
6443 for (auto& observer : observers_.observer_list()) {
6444 observer.RenderProcessGone(crashed_status);
6445 if (!weak_ptr)
6446 return;
6447 }
6448
6449 // |this| might have been deleted. Do not add code here.
[email protected]420ae012009-04-24 05:16:326450}
6451
[email protected]b172aee2012-04-10 17:05:266452void WebContentsImpl::RenderViewDeleted(RenderViewHost* rvh) {
Alexander Timin90c20c32020-08-12 15:28:326453 observers_.ForEachObserver(
6454 [&](WebContentsObserver* observer) { observer->RenderViewDeleted(rvh); });
[email protected]2e4633c2009-07-09 16:58:066455}
6456
sky8b00392d2015-01-10 00:30:286457void WebContentsImpl::UpdateTargetURL(RenderViewHost* render_view_host,
6458 const GURL& url) {
6459 if (fullscreen_widget_routing_id_ != MSG_ROUTING_NONE) {
Lukasz Anforowiczfd707142018-02-07 19:46:136460 // If we're in flash fullscreen (i.e. Pepper plugin fullscreen) only update
6461 // the url if it's from the fullscreen renderer.
sky8b00392d2015-01-10 00:30:286462 RenderWidgetHostView* fs = GetFullscreenRenderWidgetHostView();
avif9ab5d942015-10-15 14:05:446463 if (fs && fs->GetRenderWidgetHost() != render_view_host->GetWidget())
sky8b00392d2015-01-10 00:30:286464 return;
6465 }
Lukasz Anforowiczfd707142018-02-07 19:46:136466
6467 // In case of racey updates from multiple RenderViewHosts, the last URL should
6468 // be shown - see also some discussion in https://crbug.com/807776.
6469 if (!url.is_valid() && render_view_host != view_that_set_last_target_url_)
6470 return;
6471 view_that_set_last_target_url_ = url.is_valid() ? render_view_host : nullptr;
6472
[email protected]6934a702011-12-20 00:04:516473 if (delegate_)
avi450ce00e2014-09-24 01:58:526474 delegate_->UpdateTargetURL(this, url);
[email protected]420ae012009-04-24 05:16:326475}
6476
Lukasz Anforowiczfd707142018-02-07 19:46:136477void WebContentsImpl::ClearTargetURL() {
6478 view_that_set_last_target_url_ = nullptr;
6479 if (delegate_)
6480 delegate_->UpdateTargetURL(this, GURL());
6481}
6482
[email protected]b172aee2012-04-10 17:05:266483void WebContentsImpl::Close(RenderViewHost* rvh) {
Avi Drissman7c57be72020-07-29 20:09:466484#if defined(OS_MAC)
[email protected]07707302009-11-06 00:50:296485 // The UI may be in an event-tracking loop, such as between the
6486 // mouse-down and mouse-up in text selection or a button click.
6487 // Defer the close until after tracking is complete, so that we
6488 // don't free objects out from under the UI.
[email protected]07707302009-11-06 00:50:296489 // TODO(shess): This could get more fine-grained. For instance,
6490 // closing a tab in another window while selecting text in the
6491 // current window's Omnibox should be just fine.
Christopher Cameron9ae31e0d2019-03-01 20:01:196492 if (view_->CloseTabAfterEventTrackingIfNeeded())
[email protected]07707302009-11-06 00:50:296493 return;
[email protected]60780f412013-02-25 16:34:106494#endif
[email protected]07707302009-11-06 00:50:296495
[email protected]420ae012009-04-24 05:16:326496 // Ignore this if it comes from a RenderViewHost that we aren't showing.
[email protected]151a63d2011-12-20 22:32:526497 if (delegate_ && rvh == GetRenderViewHost())
[email protected]6934a702011-12-20 00:04:516498 delegate_->CloseContents(this);
[email protected]420ae012009-04-24 05:16:326499}
6500
Avi Drissman014dec72018-06-07 02:34:016501void WebContentsImpl::RequestSetBounds(const gfx::Rect& new_bounds) {
Mike Wassermandabad612020-08-13 04:26:276502 if (!delegate_)
6503 return;
6504
6505 // Members of |new_bounds| may be 0 to indicate uninitialized values for newly
6506 // opened windows, even if the |GetContainerBounds()| inner rect is correct.
6507 // TODO(crbug.com/897300): Plumb values as specified; fallback on outer rect.
6508 auto bounds = new_bounds;
6509 if (bounds.IsEmpty())
6510 bounds.set_size(GetContainerBounds().size());
6511
6512 // Only requests from the main frame, not subframes, should reach this code.
6513 bounds = AdjustRequestedWindowBounds(bounds, GetMainFrame());
6514 delegate_->SetContentsBounds(this, bounds);
[email protected]420ae012009-04-24 05:16:326515}
6516
fdegansa696e5112015-04-17 01:57:596517void WebContentsImpl::DidStartLoading(FrameTreeNode* frame_tree_node,
[email protected]e3b10d12014-03-28 16:06:096518 bool to_different_document) {
Evan Stadec3b26022017-07-14 19:50:246519 LoadingStateChanged(frame_tree_node->IsMainFrame() && to_different_document,
Carlos IL07f282f2020-05-15 22:58:296520 nullptr);
dmazzonibf8cec42015-02-08 08:28:086521
Xiyuan Xia2a66b112018-12-06 15:52:166522 // Reset the focus state from DidStartNavigation to false if a new load starts
6523 // afterward, in case loading logic triggers a FocusLocationBarByDefault call.
6524 should_focus_location_bar_by_default_ = false;
Ian Prestcdd843d2020-01-28 18:59:586525
6526 // Notify accessibility that the user is navigating away from the
6527 // current document.
6528 // TODO(domfarolino, dmazzoni): Do this using WebContentsObserver. See
6529 // https://crbug.com/981271.
6530 BrowserAccessibilityManager* manager =
6531 frame_tree_node->current_frame_host()->browser_accessibility_manager();
6532 if (manager)
6533 manager->UserIsNavigatingAway();
[email protected]420ae012009-04-24 05:16:326534}
6535
fdegansc73eec22015-03-19 14:47:546536void WebContentsImpl::DidStopLoading() {
dcheng59716272016-04-09 05:19:086537 std::unique_ptr<LoadNotificationDetails> details;
[email protected]420ae012009-04-24 05:16:326538
[email protected]9595fd82013-04-19 21:28:496539 // Use the last committed entry rather than the active one, in case a
6540 // pending entry has been created.
6541 NavigationEntry* entry = controller_.GetLastCommittedEntry();
6542
[email protected]420ae012009-04-24 05:16:326543 // An entry may not exist for a stop when loading an initial blank page or
6544 // if an iframe injected by script into a blank page finishes loading.
6545 if (entry) {
[email protected]420ae012009-04-24 05:16:326546 details.reset(new LoadNotificationDetails(
[email protected]36fc0392011-12-25 03:59:516547 entry->GetVirtualURL(),
[email protected]420ae012009-04-24 05:16:326548 &controller_,
6549 controller_.GetCurrentEntryIndex()));
6550 }
6551
Carlos IL07f282f2020-05-15 22:58:296552 LoadingStateChanged(true, details.get());
[email protected]420ae012009-04-24 05:16:326553}
6554
fdegansa696e5112015-04-17 01:57:596555void WebContentsImpl::DidChangeLoadProgress() {
Nate Chapin22ea6592019-03-05 22:29:026556 if (is_being_destroyed_)
6557 return;
fdegansa696e5112015-04-17 01:57:596558 double load_progress = frame_tree_.load_progress();
6559
6560 // The delegate is notified immediately for the first and last updates. Also,
6561 // since the message loop may be pretty busy when a page is loaded, it might
6562 // not execute a posted task in a timely manner so the progress report is sent
6563 // immediately if enough time has passed.
6564 base::TimeDelta min_delay =
6565 base::TimeDelta::FromMilliseconds(kMinimumDelayBetweenLoadingUpdatesMS);
6566 bool delay_elapsed = loading_last_progress_update_.is_null() ||
6567 base::TimeTicks::Now() - loading_last_progress_update_ > min_delay;
6568
6569 if (load_progress == 0.0 || load_progress == 1.0 || delay_elapsed) {
6570 // If there is a pending task to send progress, it is now obsolete.
6571 loading_weak_factory_.InvalidateWeakPtrs();
6572
6573 // Notify the load progress change.
6574 SendChangeLoadProgress();
6575
6576 // Clean-up the states if needed.
6577 if (load_progress == 1.0)
6578 ResetLoadProgressState();
6579 return;
6580 }
6581
6582 if (loading_weak_factory_.HasWeakPtrs())
6583 return;
6584
skyostil95082a62015-06-05 19:53:076585 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
tzike2aca992017-09-05 08:50:546586 FROM_HERE,
6587 base::BindOnce(&WebContentsImpl::SendChangeLoadProgress,
6588 loading_weak_factory_.GetWeakPtr()),
fdegansa696e5112015-04-17 01:57:596589 min_delay);
6590}
6591
avid6d88b912017-01-13 00:16:006592std::vector<std::unique_ptr<NavigationThrottle>>
6593WebContentsImpl::CreateThrottlesForNavigation(
clamycbf524d42016-09-27 12:48:356594 NavigationHandle* navigation_handle) {
Charlie Reis96077362019-07-04 00:34:046595 auto throttles = GetContentClient()->browser()->CreateThrottlesForNavigation(
clamycbf524d42016-09-27 12:48:356596 navigation_handle);
Charlie Reis96077362019-07-04 00:34:046597
6598 // This is not a normal place to be adding a throttle. However, in the case
6599 // javascript dialogs, related logic is present in the web_contents/ layer,
6600 // and the purpose of the throttle is to ensure that navigation commits are
6601 // deferred for the entire WebContents. Most throttles are either added by
6602 // the embederrer outside of content/, or are per-frame and added by
6603 // NavigationThrottleRunner.
6604 std::unique_ptr<content::NavigationThrottle> dialog_throttle =
6605 JavaScriptDialogNavigationThrottle::MaybeCreateThrottleFor(
6606 navigation_handle);
6607 if (dialog_throttle)
6608 throttles.push_back(std::move(dialog_throttle));
6609
6610 return throttles;
clamycbf524d42016-09-27 12:48:356611}
6612
clamy1e5574e2016-09-29 16:48:446613std::unique_ptr<NavigationUIData> WebContentsImpl::GetNavigationUIData(
6614 NavigationHandle* navigation_handle) {
clamy1e5574e2016-09-29 16:48:446615 return GetContentClient()->browser()->GetNavigationUIData(navigation_handle);
6616}
6617
W. James MacLean1c40862c2020-04-27 21:05:576618void WebContentsImpl::RegisterExistingOriginToPreventOptInIsolation(
W. James MacLeanb70fab82020-05-01 18:51:146619 const url::Origin& origin,
6620 NavigationRequest* navigation_request_to_exclude) {
W. James MacLean1c40862c2020-04-27 21:05:576621 // Note: This function can be made static if we ever need call it without
6622 // a WebContentsImpl instance, in which case we can use a wrapper to
6623 // implement the override from NavigatorDelegate.
6624 for (WebContentsImpl* web_contents : GetAllWebContents()) {
6625 web_contents->controller_.RegisterExistingOriginToPreventOptInIsolation(
6626 origin);
W. James MacLeanb70fab82020-05-01 18:51:146627 // Walk the frame tree to pick up any frames without FrameNavigationEntries.
6628 // * Some frames won't have FrameNavigationEntries (Issues 524208, 608402).
6629 // * Some pending navigations won't have NavigationEntries.
6630 web_contents->GetFrameTree()->RegisterExistingOriginToPreventOptInIsolation(
6631 origin, navigation_request_to_exclude);
W. James MacLean1c40862c2020-04-27 21:05:576632 }
6633}
6634
pdr15f5b5b2017-06-20 00:58:006635void WebContentsImpl::DidCancelLoading() {
6636 controller_.DiscardNonCommittedEntries();
6637
6638 // Update the URL display.
6639 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
6640}
6641
[email protected]59167c22013-06-03 18:07:326642void WebContentsImpl::DidAccessInitialDocument() {
[email protected]b4c84012014-04-28 19:51:106643 has_accessed_initial_document_ = true;
6644
[email protected]d1371bf8e2014-04-19 03:26:246645 // We may have left a failed browser-initiated navigation in the address bar
6646 // to let the user edit it and try again. Clear it now that content might
6647 // show up underneath it.
6648 if (!IsLoading() && controller_.GetPendingEntry())
avi45a72532015-04-07 21:01:456649 controller_.DiscardPendingEntry(false);
[email protected]d1371bf8e2014-04-19 03:26:246650
[email protected]59167c22013-06-03 18:07:326651 // Update the URL display.
thestigc4cac8f2014-09-04 21:17:506652 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
[email protected]59167c22013-06-03 18:07:326653}
6654
alexmosbe2f4c32015-03-10 02:30:236655void WebContentsImpl::DidChangeName(RenderFrameHost* render_frame_host,
6656 const std::string& name) {
Alexander Timin90c20c32020-08-12 15:28:326657 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6658 observer->FrameNameChanged(render_frame_host, name);
6659 });
alexmosbe2f4c32015-03-10 02:30:236660}
6661
John Delaneyedd8d6c2019-01-25 00:23:576662void WebContentsImpl::DidReceiveFirstUserActivation(
6663 RenderFrameHost* render_frame_host) {
Alexander Timin90c20c32020-08-12 15:28:326664 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6665 observer->FrameReceivedFirstUserActivation(render_frame_host);
6666 });
John Delaneyedd8d6c2019-01-25 00:23:576667}
6668
John Delaney0146a742019-01-25 19:25:286669void WebContentsImpl::DidChangeDisplayState(RenderFrameHost* render_frame_host,
6670 bool is_display_none) {
Alexander Timin90c20c32020-08-12 15:28:326671 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6672 observer->FrameDisplayStateChanged(render_frame_host, is_display_none);
6673 });
John Delaney0146a742019-01-25 19:25:286674}
6675
6676void WebContentsImpl::FrameSizeChanged(RenderFrameHost* render_frame_host,
6677 const gfx::Size& frame_size) {
Alexander Timin90c20c32020-08-12 15:28:326678 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6679 observer->FrameSizeChanged(render_frame_host, frame_size);
6680 });
John Delaney0146a742019-01-25 19:25:286681}
6682
[email protected]39f2f9252014-05-03 00:54:016683void WebContentsImpl::DocumentOnLoadCompleted(
[email protected]50279492014-05-05 23:24:296684 RenderFrameHost* render_frame_host) {
falken52a56e32016-12-08 05:02:406685 ShowInsecureLocalhostWarningIfNeeded();
6686
Alexander Timindd0fa0c52019-11-06 13:03:376687 GetRenderViewHost()->DocumentOnLoadCompletedInMainFrame();
6688
Alexander Timin90c20c32020-08-12 15:28:326689 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6690 observer->DocumentOnLoadCompletedInMainFrame();
6691 });
[email protected]6578fef2013-10-14 02:35:096692
6693 // TODO(avi): Remove. http://crbug.com/170921
[email protected]8ff00d72012-10-23 19:12:216694 NotificationService::current()->Notify(
6695 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
6696 Source<WebContents>(this),
[email protected]50279492014-05-05 23:24:296697 NotificationService::NoDetails());
[email protected]25497492010-09-11 15:15:086698}
6699
creis8eb8ef22015-11-04 22:51:386700void WebContentsImpl::UpdateStateForFrame(RenderFrameHost* render_frame_host,
6701 const PageState& page_state) {
creis8eb8ef22015-11-04 22:51:386702 // The state update affects the last NavigationEntry associated with the given
6703 // |render_frame_host|. This may not be the last committed NavigationEntry (as
6704 // in the case of an UpdateState from a frame being swapped out). We track
6705 // which entry this is in the RenderFrameHost's nav_entry_id.
6706 RenderFrameHostImpl* rfhi =
6707 static_cast<RenderFrameHostImpl*>(render_frame_host);
6708 NavigationEntryImpl* entry =
6709 controller_.GetEntryWithUniqueID(rfhi->nav_entry_id());
6710 if (!entry)
6711 return;
6712
6713 FrameNavigationEntry* frame_entry =
6714 entry->GetFrameEntry(rfhi->frame_tree_node());
6715 if (!frame_entry)
6716 return;
6717
creisd06a9422015-11-11 03:08:456718 // The SiteInstance might not match if we do a cross-process navigation with
6719 // replacement (e.g., auto-subframe), in which case the swap out of the old
6720 // RenderFrameHost runs in the background after the old FrameNavigationEntry
6721 // has already been replaced and destroyed.
6722 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
6723 return;
6724
creis8eb8ef22015-11-04 22:51:386725 if (page_state == frame_entry->page_state())
6726 return; // Nothing to update.
6727
creis0cade2e2017-02-28 06:37:476728 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
nasko34634672016-07-29 18:46:066729
6730 // The document_sequence_number and item_sequence_number recorded in the
6731 // FrameNavigationEntry should not differ from the one coming with the update,
6732 // since it must come from the same document. Do not update it if a difference
6733 // is detected, as this indicates that |frame_entry| is not the correct one.
6734 ExplodedPageState exploded_state;
6735 if (!DecodePageState(page_state.ToEncodedData(), &exploded_state))
6736 return;
6737
6738 if (exploded_state.top.document_sequence_number !=
6739 frame_entry->document_sequence_number() ||
6740 exploded_state.top.item_sequence_number !=
6741 frame_entry->item_sequence_number()) {
6742 return;
6743 }
6744
nasko04a322f25a2016-09-01 00:00:346745 frame_entry->SetPageState(page_state);
creis8eb8ef22015-11-04 22:51:386746 controller_.NotifyEntryChanged(entry);
6747}
6748
[email protected]ef3adfc2014-05-11 00:04:546749void WebContentsImpl::UpdateTitle(RenderFrameHost* render_frame_host,
[email protected]ef3adfc2014-05-11 00:04:546750 const base::string16& title,
6751 base::i18n::TextDirection title_direction) {
[email protected]ef3adfc2014-05-11 00:04:546752 // Try to find the navigation entry, which might not be the current one.
avi286019ce2015-07-29 01:26:586753 // For example, it might be from a recently swapped out RFH.
avi1edc8552016-10-13 21:37:166754 NavigationEntryImpl* entry = controller_.GetEntryWithUniqueID(
creisad8c31a2016-05-24 17:07:046755 static_cast<RenderFrameHostImpl*>(render_frame_host)->nav_entry_id());
[email protected]ef3adfc2014-05-11 00:04:546756
6757 // We can handle title updates when we don't have an entry in
6758 // UpdateTitleForEntry, but only if the update is from the current RVH.
6759 // TODO(avi): Change to make decisions based on the RenderFrameHost.
avi286019ce2015-07-29 01:26:586760 if (!entry && render_frame_host != GetMainFrame())
[email protected]ef3adfc2014-05-11 00:04:546761 return;
6762
6763 // TODO(evan): make use of title_direction.
6764 // http://code.google.com/p/chromium/issues/detail?id=27094
afakhry6f0c1ec22016-07-14 13:55:136765 UpdateTitleForEntry(entry, title);
[email protected]ef3adfc2014-05-11 00:04:546766}
6767
alexmose7da5a12015-04-09 02:22:166768bool WebContentsImpl::ShouldRouteMessageEvent(
6769 RenderFrameHost* target_rfh,
6770 SiteInstance* source_site_instance) const {
6771 // Allow the message if this WebContents is dedicated to a browser plugin
6772 // guest.
[email protected]0eba810b2012-10-18 03:19:366773 // Note: This check means that an embedder could theoretically receive a
6774 // postMessage from anyone (not just its own guests). However, this is
6775 // probably not a risk for apps since other pages won't have references
6776 // to App windows.
alexmose7da5a12015-04-09 02:22:166777 return GetBrowserPluginGuest() || GetBrowserPluginEmbedder();
6778}
[email protected]f546640b2012-05-15 00:03:496779
alexmos58729042015-06-18 23:20:006780void WebContentsImpl::EnsureOpenerProxiesExist(RenderFrameHost* source_rfh) {
alexmose7da5a12015-04-09 02:22:166781 WebContentsImpl* source_web_contents = static_cast<WebContentsImpl*>(
6782 WebContents::FromRenderFrameHost(source_rfh));
[email protected]f546640b2012-05-15 00:03:496783
alexmose7da5a12015-04-09 02:22:166784 if (source_web_contents) {
lazyboy6ec48b2a2015-06-29 15:18:146785 // If this message is going to outer WebContents from inner WebContents,
6786 // then we should not create a RenderView. AttachToOuterWebContentsFrame()
6787 // already created a RenderFrameProxyHost for that purpose.
6788 if (GetBrowserPluginEmbedder() &&
W. James MacLean2539adb32019-12-13 00:40:446789 source_web_contents->browser_plugin_guest_) {
lazyboy6ec48b2a2015-06-29 15:18:146790 return;
W. James MacLean2539adb32019-12-13 00:40:446791 }
lazyboy6ec48b2a2015-06-29 15:18:146792
lfg812874d2016-02-09 22:26:136793 if (this != source_web_contents && GetBrowserPluginGuest()) {
naskob3041b98a42016-03-12 04:43:066794 // We create a RenderFrameProxyHost for the embedder in the guest's render
6795 // process but we intentionally do not expose the embedder's opener chain
6796 // to it.
6797 source_web_contents->GetRenderManager()->CreateRenderFrameProxy(
6798 GetSiteInstance());
[email protected]f546640b2012-05-15 00:03:496799 } else {
alexmos58729042015-06-18 23:20:006800 RenderFrameHostImpl* source_rfhi =
6801 static_cast<RenderFrameHostImpl*>(source_rfh);
6802 source_rfhi->frame_tree_node()->render_manager()->CreateOpenerProxies(
alexmos90325cf2015-09-02 17:18:396803 GetSiteInstance(), nullptr);
[email protected]f546640b2012-05-15 00:03:496804 }
6805 }
[email protected]f546640b2012-05-15 00:03:496806}
6807
avallee9993fca2016-11-17 06:16:506808void WebContentsImpl::SetAsFocusedWebContentsIfNecessary() {
Adithya Srinivasan11af2c52019-12-16 22:52:556809 DCHECK(!portal());
avallee9993fca2016-11-17 06:16:506810 // Only change focus if we are not currently focused.
6811 WebContentsImpl* old_contents = GetFocusedWebContents();
6812 if (old_contents == this)
6813 return;
6814
paulmeyerfeafc2d2017-04-25 21:46:406815 GetOutermostWebContents()->node_.SetFocusedWebContents(this);
6816
avallee9993fca2016-11-17 06:16:506817 // Send a page level blur to the old contents so that it displays inactive UI
6818 // and focus this contents to activate it.
6819 if (old_contents)
6820 old_contents->GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(false);
avalleec2ff1ef2017-01-21 00:12:306821
6822 // Make sure the outer web contents knows our frame is focused. Otherwise, the
6823 // outer renderer could have the element before or after the frame element
6824 // focused which would return early without actually advancing focus.
avalleed68cdd12017-06-21 22:07:276825 FocusOuterAttachmentFrameChain();
avalleec2ff1ef2017-01-21 00:12:306826
Carlos ILd51e7702020-05-07 18:51:396827 GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(true);
avallee9993fca2016-11-17 06:16:506828}
6829
avallee0206f782016-07-28 18:55:336830void WebContentsImpl::SetFocusedFrame(FrameTreeNode* node,
6831 SiteInstance* source) {
Adithya Srinivasan11af2c52019-12-16 22:52:556832 DCHECK(!portal());
avallee0206f782016-07-28 18:55:336833 frame_tree_.SetFocusedFrame(node, source);
avalleed68cdd12017-06-21 22:07:276834
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:576835 if (auto* inner_contents = node_.GetInnerWebContentsInFrame(node)) {
6836 // |this| is an outer WebContents and |node| represents an inner
6837 // WebContents. Transfer the focus to the inner contents if |this| is
6838 // focused.
6839 if (GetFocusedWebContents() == this)
6840 inner_contents->SetAsFocusedWebContentsIfNecessary();
6841 } else if (node_.OuterContentsFrameTreeNode() &&
6842 node_.OuterContentsFrameTreeNode()
6843 ->current_frame_host()
6844 ->GetSiteInstance() == source) {
6845 // |this| is an inner WebContents, |node| is its main FrameTreeNode and
6846 // the outer WebContents FrameTreeNode is at |source|'s SiteInstance.
6847 // Transfer the focus to the inner WebContents if the outer WebContents is
6848 // focused. This branch is used when an inner WebContents is focused through
Lowell Mannersa9530382019-08-01 09:46:576849 // its RenderFrameProxyHost (via FrameFocused mojo call, used to
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:576850 // implement the window.focus() API).
6851 if (GetFocusedWebContents() == GetOuterWebContents())
6852 SetAsFocusedWebContentsIfNecessary();
6853 } else if (!GetOuterWebContents()) {
6854 // This is an outermost WebContents.
6855 SetAsFocusedWebContentsIfNecessary();
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:576856 }
avalleed68cdd12017-06-21 22:07:276857}
6858
Avi Drissman36f801f2018-02-01 20:06:046859void WebContentsImpl::DidCallFocus() {
6860 // Any explicit focusing of another window while this WebContents is in
6861 // fullscreen can be used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:456862 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
6863 // The other contents is independent of this contents, so release the
6864 // fullscreen block.
6865 fullscreen_block.RunAndReset();
Avi Drissman36f801f2018-02-01 20:06:046866}
6867
avalleed68cdd12017-06-21 22:07:276868RenderFrameHost* WebContentsImpl::GetFocusedFrameIncludingInnerWebContents() {
6869 WebContentsImpl* contents = this;
6870 FrameTreeNode* focused_node = contents->frame_tree_.GetFocusedFrame();
6871
6872 // If there is no focused frame in the outer WebContents, we need to return
6873 // null.
6874 if (!focused_node)
6875 return nullptr;
6876
6877 // If the focused frame is embedding an inner WebContents, we must descend
6878 // into that contents. If the current WebContents does not have a focused
6879 // frame, return the main frame of this contents instead of the focused empty
6880 // frame embedding this contents.
6881 while (true) {
6882 contents = contents->node_.GetInnerWebContentsInFrame(focused_node);
6883 if (!contents)
6884 return focused_node->current_frame_host();
6885
6886 focused_node = contents->frame_tree_.GetFocusedFrame();
6887 if (!focused_node)
6888 return contents->GetMainFrame();
6889 }
avallee0206f782016-07-28 18:55:336890}
6891
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:576892void WebContentsImpl::OnAdvanceFocus(RenderFrameHostImpl* source_rfh) {
6893 // When a RenderFrame needs to advance focus to a RenderFrameProxy (by hitting
6894 // TAB), the RenderFrameProxy sends an IPC to RenderFrameProxyHost. When this
6895 // RenderFrameProxyHost represents an inner WebContents, the outer WebContents
6896 // needs to focus the inner WebContents.
6897 if (GetOuterWebContents() &&
6898 GetOuterWebContents() == source_rfh->delegate()->GetAsWebContents() &&
6899 GetFocusedWebContents() == GetOuterWebContents()) {
6900 SetAsFocusedWebContentsIfNecessary();
6901 }
6902}
6903
ekaramada110f642016-12-21 19:47:286904void WebContentsImpl::OnFocusedElementChangedInFrame(
6905 RenderFrameHostImpl* frame,
6906 const gfx::Rect& bounds_in_root_view) {
6907 RenderWidgetHostViewBase* root_view =
6908 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
6909 if (!root_view || !frame->GetView())
6910 return;
Katie De0131372020-07-09 23:03:106911 // Convert to screen coordinates from window coordinates by adding the
6912 // window's origin.
ekaramada110f642016-12-21 19:47:286913 gfx::Point origin = bounds_in_root_view.origin();
6914 origin += root_view->GetViewBounds().OffsetFromOrigin();
6915 gfx::Rect bounds_in_screen(origin, bounds_in_root_view.size());
6916
6917 root_view->FocusedNodeChanged(frame->has_focused_editable_element(),
6918 bounds_in_screen);
6919
6920 FocusedNodeDetails details = {frame->has_focused_editable_element(),
6921 bounds_in_screen};
6922
6923 // TODO(ekaramad): We should replace this with an observer notification
6924 // (https://crbug.com/675975).
6925 NotificationService::current()->Notify(
6926 NOTIFICATION_FOCUS_CHANGED_IN_PAGE,
6927 Source<RenderViewHost>(GetRenderViewHost()),
6928 Details<FocusedNodeDetails>(&details));
Jeff Fisher709b4c52019-07-29 20:07:346929
Alexander Timin90c20c32020-08-12 15:28:326930 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6931 observer->OnFocusChangedInPage(&details);
6932 });
ekaramada110f642016-12-21 19:47:286933}
6934
Lowell Manners1de5242e2019-04-25 10:18:466935bool WebContentsImpl::DidAddMessageToConsole(
6936 blink::mojom::ConsoleMessageLevel log_level,
6937 const base::string16& message,
6938 int32_t line_no,
6939 const base::string16& source_id) {
Alexander Timin90c20c32020-08-12 15:28:326940 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6941 observer->OnDidAddMessageToConsole(log_level, message, line_no, source_id);
6942 });
[email protected]a796f202012-05-30 14:14:256943 if (!delegate_)
6944 return false;
Lowell Manners1de5242e2019-04-25 10:18:466945 return delegate_->DidAddMessageToConsole(this, log_level, message, line_no,
avia90ae4e2016-11-11 20:49:336946 source_id);
[email protected]a796f202012-05-30 14:14:256947}
6948
Daniel Cheng90196c82018-04-25 21:49:146949void WebContentsImpl::DidReceiveInputEvent(
dominickn9c7ceaa32016-02-27 01:52:536950 RenderWidgetHostImpl* render_widget_host,
Emily Starkc7bd40c42020-07-21 19:12:556951 const blink::WebInputEvent& event) {
6952 if (!IsUserInteractionInputType(event.GetType()))
Daniel Cheng90196c82018-04-25 21:49:146953 return;
6954
kenrb19221852016-04-29 17:21:406955 // Ignore unless the widget is currently in the frame tree.
6956 if (!HasMatchingWidgetHost(&frame_tree_, render_widget_host))
avic3aa8422015-11-09 20:57:226957 return;
6958
Emily Starkc7bd40c42020-07-21 19:12:556959 if (event.GetType() != blink::WebInputEvent::Type::kGestureScrollBegin)
Daniel Cheng90196c82018-04-25 21:49:146960 last_interactive_input_event_time_ = ui::EventTimeForNow();
dominickn9c7ceaa32016-02-27 01:52:536961
Alexander Timin90c20c32020-08-12 15:28:326962 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6963 observer->DidGetUserInteraction(event);
6964 });
dominickn2dd142dd2015-10-29 05:30:506965}
6966
Avi Drissman738ea192018-08-29 20:24:166967bool WebContentsImpl::ShouldIgnoreInputEvents() {
6968 WebContentsImpl* web_contents = this;
6969 while (web_contents) {
6970 if (web_contents->ignore_input_events_)
6971 return true;
6972 web_contents = web_contents->GetOuterWebContents();
6973 }
6974
6975 return false;
6976}
6977
avallee9993fca2016-11-17 06:16:506978void WebContentsImpl::FocusOwningWebContents(
6979 RenderWidgetHostImpl* render_widget_host) {
Alex Moshchukc4f0a722019-11-19 22:41:286980 RenderWidgetHostImpl* main_frame_widget_host =
6981 GetMainFrame()->GetRenderWidgetHost();
avallee9993fca2016-11-17 06:16:506982 RenderWidgetHostImpl* focused_widget =
Alex Moshchukc4f0a722019-11-19 22:41:286983 GetFocusedRenderWidgetHost(main_frame_widget_host);
avallee9993fca2016-11-17 06:16:506984
6985 if (focused_widget != render_widget_host &&
avallee8e881592016-11-19 00:39:306986 (!focused_widget ||
6987 focused_widget->delegate() != render_widget_host->delegate())) {
avallee9993fca2016-11-17 06:16:506988 SetAsFocusedWebContentsIfNecessary();
6989 }
6990}
6991
[email protected]b172aee2012-04-10 17:05:266992void WebContentsImpl::OnIgnoredUIEvent() {
[email protected]31145092011-09-30 01:49:446993 // Notify observers.
Alexander Timin90c20c32020-08-12 15:28:326994 observers_.ForEachObserver(
6995 [&](WebContentsObserver* observer) { observer->DidGetIgnoredUIEvent(); });
[email protected]fa1cf0b82010-01-15 21:49:446996}
6997
avic3aa8422015-11-09 20:57:226998void WebContentsImpl::RendererUnresponsive(
Lukasz Anforowicz52b93722018-06-20 16:11:396999 RenderWidgetHostImpl* render_widget_host,
7000 base::RepeatingClosure hang_monitor_restarter) {
avic031d392017-03-03 03:09:427001 if (ShouldIgnoreUnresponsiveRenderer())
[email protected]e5fc1632011-08-08 07:51:537002 return;
7003
Lukasz Anforowicz4f0593d2018-09-21 18:33:547004 // Do not report hangs (to task manager, to hang renderer dialog, etc.) for
7005 // invisible tabs (like extension background page, background tabs). See
7006 // https://crbug.com/881812 for rationale and for choosing the visibility
7007 // (rather than process priority) as the signal here.
7008 if (GetVisibility() != Visibility::VISIBLE)
7009 return;
7010
Avi Drissman8920def2018-01-31 19:53:367011 if (!render_widget_host->renderer_initialized())
[email protected]55452902011-06-01 21:57:477012 return;
7013
Alexander Timin90c20c32020-08-12 15:28:327014 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7015 observer->OnRendererUnresponsive(render_widget_host->GetProcess());
7016 });
Dave Tapuskac6146c52017-12-20 22:48:157017 if (delegate_)
Lukasz Anforowicz52b93722018-06-20 16:11:397018 delegate_->RendererUnresponsive(this, render_widget_host,
7019 std::move(hang_monitor_restarter));
[email protected]420ae012009-04-24 05:16:327020}
7021
avic3aa8422015-11-09 20:57:227022void WebContentsImpl::RendererResponsive(
7023 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin90c20c32020-08-12 15:28:327024 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7025 observer->OnRendererResponsive(render_widget_host->GetProcess());
7026 });
[email protected]6934a702011-12-20 00:04:517027 if (delegate_)
Avi Drissman1572e8c3c2018-02-02 19:06:367028 delegate_->RendererResponsive(this, render_widget_host);
[email protected]420ae012009-04-24 05:16:327029}
7030
Alex Moshchuk7b4f0652019-05-30 18:54:417031void WebContentsImpl::SubframeCrashed(
7032 blink::mojom::FrameVisibility visibility) {
7033 // If a subframe crashed on a hidden tab, mark the tab for reload to avoid
7034 // showing a sad frame to the user if they ever switch back to that tab. Do
7035 // this for subframes that are either visible in viewport or visible but
7036 // scrolled out of view, but skip subframes that are not rendered (e.g., via
7037 // "display:none"), since in that case the user wouldn't see a sad frame
7038 // anyway.
7039 bool did_mark_for_reload = false;
7040 if (IsHidden() && visibility != blink::mojom::FrameVisibility::kNotRendered &&
7041 base::FeatureList::IsEnabled(
7042 features::kReloadHiddenTabsWithCrashedSubframes)) {
7043 controller_.SetNeedsReload(
7044 NavigationControllerImpl::NeedsReloadType::kCrashedSubframe);
7045 did_mark_for_reload = true;
7046 UMA_HISTOGRAM_ENUMERATION(
7047 "Stability.ChildFrameCrash.TabMarkedForReload.Visibility", visibility);
7048 }
7049
7050 UMA_HISTOGRAM_BOOLEAN("Stability.ChildFrameCrash.TabMarkedForReload",
7051 did_mark_for_reload);
7052}
7053
[email protected]b172aee2012-04-10 17:05:267054void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
[email protected]feaded02012-09-25 19:12:557055 bool proceed, const base::TimeTicks& proceed_time,
[email protected]420ae012009-04-24 05:16:327056 bool* proceed_to_fire_unload) {
Alexander Timin90c20c32020-08-12 15:28:327057 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7058 observer->BeforeUnloadFired(proceed, proceed_time);
7059 });
[email protected]6934a702011-12-20 00:04:517060 if (delegate_)
7061 delegate_->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
[email protected]e80af492013-06-24 21:52:097062 // Note: |this| might be deleted at this point.
[email protected]420ae012009-04-24 05:16:327063}
7064
[email protected]58d5cfe2013-07-10 02:40:527065void WebContentsImpl::RenderProcessGoneFromRenderManager(
[email protected]3a3d47472010-07-15 21:03:547066 RenderViewHost* render_view_host) {
[email protected]443b80e2010-12-14 00:42:237067 DCHECK(crashed_status_ != base::TERMINATION_STATUS_STILL_RUNNING);
[email protected]ec6a7eb2013-04-22 17:34:227068 RenderViewTerminated(render_view_host, crashed_status_, crashed_error_code_);
[email protected]3a3d47472010-07-15 21:03:547069}
7070
[email protected]af905902013-10-01 21:38:517071void WebContentsImpl::CancelModalDialogsForRenderManager() {
7072 // We need to cancel modal dialogs when doing a process swap, since the load
avi2460c762015-04-17 15:21:547073 // deferrer would prevent us from swapping out. We also clear the state
7074 // because this is a cross-process navigation, which means that it's a new
7075 // site that should not have to pay for the sins of its predecessor.
creis89a0f782015-05-27 16:13:177076 //
Lei Zhang6410ec1a2019-01-31 21:38:587077 // Note that we don't bother telling |browser_plugin_embedder_| because the
creis89a0f782015-05-27 16:13:177078 // cross-process navigation will either destroy the browser plugins or not
7079 // require their dialogs to close.
avi5d3b8692016-10-12 22:00:467080 if (dialog_manager_) {
avi6879fcf2017-01-21 05:27:537081 dialog_manager_->CancelDialogs(this, /*reset_state=*/true);
avi5d3b8692016-10-12 22:00:467082 }
[email protected]af905902013-10-01 21:38:517083}
7084
danakja0bce4c952020-05-12 20:40:287085void WebContentsImpl::NotifySwappedFromRenderManager(RenderFrameHost* old_frame,
7086 RenderFrameHost* new_frame,
[email protected]02d7b6e2014-06-24 21:01:507087 bool is_main_frame) {
7088 if (is_main_frame) {
danakja0bce4c952020-05-12 20:40:287089 // The |new_frame| and its various compadres are already swapped into place
7090 // for the WebContentsImpl when this method is called.
7091 DCHECK(GetMainFrame() == new_frame);
7092 DCHECK(GetRenderViewHost() == new_frame->GetRenderViewHost());
7093 DCHECK(GetRenderWidgetHostView() == new_frame->GetView());
7094
Fergal Daly6767b2e2020-02-04 03:15:167095 RenderViewHost* old_rvh =
danakja0bce4c952020-05-12 20:40:287096 old_frame ? old_frame->GetRenderViewHost() : nullptr;
7097 RenderViewHost* new_rvh = new_frame->GetRenderViewHost();
Fergal Daly6767b2e2020-02-04 03:15:167098 // |old_rvh| and |new_rvh| might be equal when navigating from a crashed
7099 // RenderFrameHost to a new same-site one. With RenderDocument, this will
7100 // happen for every same-site navigation.
7101 if (old_rvh != new_rvh)
7102 NotifyViewSwapped(old_rvh, new_rvh);
[email protected]a6b73c62013-02-11 23:05:087103
[email protected]02d7b6e2014-06-24 21:01:507104 // Make sure the visible RVH reflects the new delegate's preferences.
7105 if (delegate_)
7106 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
[email protected]d56a49e2013-02-23 00:47:397107
danakja0bce4c952020-05-12 20:40:287108 auto* rwhv = static_cast<RenderWidgetHostViewBase*>(new_frame->GetView());
7109 if (rwhv) {
7110 rwhv->SetMainFrameAXTreeID(new_frame->GetAXTreeID());
7111
7112 // The RenderWidgetHostView for the speculative RenderFrameHost is not
7113 // resized with the current RenderFrameHost while a navigation is
7114 // pending. So when we swap in the main frame, we need to update the
7115 // RenderWidgetHostView's size.
7116 //
7117 // Historically, this was done to fix b/1079768 for interstitials.
7118 rwhv->SetSize(GetSizeForMainFrame());
7119 }
[email protected]02d7b6e2014-06-24 21:01:507120 }
7121
danakja0bce4c952020-05-12 20:40:287122 NotifyFrameSwapped(old_frame, new_frame, is_main_frame);
[email protected]3a3d47472010-07-15 21:03:547123}
7124
naskof5940b9f2015-03-02 23:04:057125void WebContentsImpl::NotifyMainFrameSwappedFromRenderManager(
danakja0bce4c952020-05-12 20:40:287126 RenderFrameHost* old_frame,
7127 RenderFrameHost* new_frame) {
7128 NotifyViewSwapped(old_frame ? old_frame->GetRenderViewHost() : nullptr,
7129 new_frame->GetRenderViewHost());
naskof5940b9f2015-03-02 23:04:057130}
7131
[email protected]b172aee2012-04-10 17:05:267132NavigationControllerImpl& WebContentsImpl::GetControllerForRenderManager() {
[email protected]d1198fd2012-08-13 22:50:197133 return GetController();
[email protected]3a3d47472010-07-15 21:03:547134}
7135
dcheng59716272016-04-09 05:19:087136std::unique_ptr<WebUIImpl> WebContentsImpl::CreateWebUIForRenderFrameHost(
Miyoung Shin072d4052020-07-13 07:52:447137 RenderFrameHost* frame_host,
Denis Kuznetsov [CET]2c6f0159f2020-05-18 14:18:167138 const GURL& url) {
Miyoung Shin072d4052020-07-13 07:52:447139 return CreateWebUI(frame_host, url);
[email protected]420ae012009-04-24 05:16:327140}
7141
lfgbede6392015-09-11 21:54:067142void WebContentsImpl::CreateRenderWidgetHostViewForRenderManager(
7143 RenderViewHost* render_view_host) {
lfgc740d4b22016-04-15 16:45:337144 RenderWidgetHostViewBase* rwh_view =
W. James MacLean13d834d2019-12-04 16:06:457145 view_->CreateViewForWidget(render_view_host->GetWidget());
danakja0bce4c952020-05-12 20:40:287146 rwh_view->SetSize(GetSizeForMainFrame());
lfgbede6392015-09-11 21:54:067147}
7148
7149bool WebContentsImpl::CreateRenderViewForRenderManager(
7150 RenderViewHost* render_view_host,
Antonio Gomesb3dd5fc2020-05-25 22:53:277151 const base::Optional<base::UnguessableToken>& opener_frame_token,
Daniel Chengabfdb002020-06-04 06:02:307152 int proxy_routing_id) {
lfgbede6392015-09-11 21:54:067153 TRACE_EVENT0("browser,navigation",
7154 "WebContentsImpl::CreateRenderViewForRenderManager");
7155
piman00cf9402017-04-03 17:09:207156 if (proxy_routing_id == MSG_ROUTING_NONE)
lfg9431efd2016-12-14 14:45:267157 CreateRenderWidgetHostViewForRenderManager(render_view_host);
lfg9431efd2016-12-14 14:45:267158
piman00cf9402017-04-03 17:09:207159 if (!static_cast<RenderViewHostImpl*>(render_view_host)
Daniel Chengabfdb002020-06-04 06:02:307160 ->CreateRenderView(opener_frame_token, proxy_routing_id,
Antonio Gomesb3dd5fc2020-05-25 22:53:277161 created_with_opener_)) {
[email protected]a4127722011-04-27 23:13:527162 return false;
[email protected]14392a52012-05-02 20:28:447163 }
W. James MacLean62198672019-06-04 16:46:107164 // Set the TextAutosizer state from the main frame's renderer on the new view,
7165 // but only if it's not for the main frame. Main frame renderers should create
7166 // this state themselves from up-to-date values, so we shouldn't override it
7167 // with the cached values.
7168 if (!render_view_host->GetMainFrame()) {
Antonio Gomesda7e03d2020-08-05 15:03:087169 auto* proxy_host = GetRenderManager()->GetRenderFrameProxyHost(
7170 render_view_host->GetSiteInstance());
7171 proxy_host->GetAssociatedRemoteMainFrame()->UpdateTextAutosizerPageInfo(
7172 text_autosizer_page_info_.Clone());
W. James MacLean62198672019-06-04 16:46:107173 }
[email protected]a4127722011-04-27 23:13:527174
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:147175 if (proxy_routing_id == MSG_ROUTING_NONE && node_.outer_web_contents())
7176 ReattachToOuterWebContentsFrame();
7177
avi2b177592014-12-10 02:08:027178 SetHistoryOffsetAndLengthForView(render_view_host,
7179 controller_.GetLastCommittedEntryIndex(),
7180 controller_.GetEntryCount());
7181
Avi Drissman7c57be72020-07-29 20:09:467182#if defined(OS_POSIX) && !defined(OS_MAC) && !defined(OS_ANDROID)
[email protected]f8233cc2011-05-31 20:24:507183 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
7184 // linux. See crbug.com/83941.
avif9ab5d942015-10-15 14:05:447185 RenderWidgetHostView* rwh_view = render_view_host->GetWidget()->GetView();
[email protected]245f7d52011-11-28 15:36:447186 if (rwh_view) {
7187 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
Fady Samuel0b911822018-04-25 13:22:167188 render_widget_host->SynchronizeVisualProperties();
[email protected]245f7d52011-11-28 15:36:447189 }
[email protected]f8233cc2011-05-31 20:24:507190#endif
7191
[email protected]420ae012009-04-24 05:16:327192 return true;
7193}
7194
[email protected]82307f6b2014-08-07 03:30:127195bool WebContentsImpl::CreateRenderFrameForRenderManager(
7196 RenderFrameHost* render_frame_host,
arthursonzogni1efc7b962019-03-14 09:36:337197 int previous_routing_id,
Antonio Gomes9d150542020-05-25 18:32:117198 const base::Optional<base::UnguessableToken>& opener_frame_token,
japhete6adf142014-10-31 00:01:497199 int parent_routing_id,
alexmosa181efc2015-09-03 00:39:047200 int previous_sibling_routing_id) {
naskob8744d22014-08-28 17:07:437201 TRACE_EVENT0("browser,navigation",
7202 "WebContentsImpl::CreateRenderFrameForRenderManager");
[email protected]82307f6b2014-08-07 03:30:127203
7204 RenderFrameHostImpl* rfh =
7205 static_cast<RenderFrameHostImpl*>(render_frame_host);
Antonio Gomes9d150542020-05-25 18:32:117206 if (!rfh->CreateRenderFrame(previous_routing_id, opener_frame_token,
7207 parent_routing_id, previous_sibling_routing_id)) {
[email protected]82307f6b2014-08-07 03:30:127208 return false;
Antonio Gomes9d150542020-05-25 18:32:117209 }
[email protected]82307f6b2014-08-07 03:30:127210
7211 // TODO(nasko): When RenderWidgetHost is owned by RenderFrameHost, the passed
7212 // RenderFrameHost will have to be associated with the appropriate
7213 // RenderWidgetHostView or a new one should be created here.
7214
7215 return true;
7216}
7217
mfomitchev2b8b066a2016-01-28 19:23:157218#if defined(OS_ANDROID)
[email protected]fc2b46b2014-05-03 16:33:457219
[email protected]155c7f22013-12-09 17:07:187220base::android::ScopedJavaLocalRef<jobject>
7221WebContentsImpl::GetJavaWebContents() {
mostynb042582e2015-03-16 22:13:407222 DCHECK_CURRENTLY_ON(BrowserThread::UI);
[email protected]0e813a52014-08-13 10:34:567223 return GetWebContentsAndroid()->GetJavaObject();
7224}
[email protected]155c7f22013-12-09 17:07:187225
[email protected]0e813a52014-08-13 10:34:567226WebContentsAndroid* WebContentsImpl::GetWebContentsAndroid() {
Kevin McNee576bb5d82019-05-29 16:47:517227 if (!web_contents_android_) {
7228 web_contents_android_ = std::make_unique<WebContentsAndroid>(this);
[email protected]155c7f22013-12-09 17:07:187229 }
Kevin McNee576bb5d82019-05-29 16:47:517230 return web_contents_android_.get();
7231}
7232
7233void WebContentsImpl::ClearWebContentsAndroid() {
7234 DCHECK_CURRENTLY_ON(BrowserThread::UI);
7235 web_contents_android_.reset();
[email protected]155c7f22013-12-09 17:07:187236}
7237
paulmeyerc0b762b2016-04-13 11:55:177238void WebContentsImpl::ActivateNearestFindResult(float x,
7239 float y) {
7240 GetOrCreateFindRequestManager()->ActivateNearestFindResult(x, y);
7241}
7242
7243void WebContentsImpl::RequestFindMatchRects(int current_version) {
7244 GetOrCreateFindRequestManager()->RequestFindMatchRects(current_version);
7245}
7246
rockot400ea35b2016-10-15 19:15:327247service_manager::InterfaceProvider* WebContentsImpl::GetJavaInterfaces() {
sammcf5f1b0f2016-09-20 23:05:117248 if (!java_interfaces_) {
Gyuyoung Kim6c9ce9022019-11-26 05:40:087249 mojo::PendingRemote<service_manager::mojom::InterfaceProvider> provider;
7250 BindInterfaceRegistryForWebContents(
7251 provider.InitWithNewPipeAndPassReceiver(), this);
rockot400ea35b2016-10-15 19:15:327252 java_interfaces_.reset(new service_manager::InterfaceProvider);
sammcf5f1b0f2016-09-20 23:05:117253 java_interfaces_->Bind(std::move(provider));
7254 }
7255 return java_interfaces_.get();
7256}
7257
Francois Doray6c26f3342018-08-24 17:17:227258#endif
7259
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:417260bool WebContentsImpl::CompletedFirstVisuallyNonEmptyPaint() {
Carlos Caballero91fffb22019-10-29 15:24:307261 return GetRenderViewHost()->did_first_visually_non_empty_paint();
spqchane72c3cb2017-06-30 23:02:107262}
7263
pkotwicz75ca8ffd2016-02-16 23:10:197264void WebContentsImpl::OnDidDownloadImage(
Avi Drissmana5a52dd2018-03-27 03:39:027265 ImageDownloadCallback callback,
pkotwicz75ca8ffd2016-02-16 23:10:197266 int id,
7267 const GURL& image_url,
leon.hancbc4bc3c2016-02-26 07:08:527268 int32_t http_status_code,
leon.hanc2228532016-08-16 05:59:187269 const std::vector<SkBitmap>& images,
7270 const std::vector<gfx::Size>& original_image_sizes) {
Avi Drissmana5a52dd2018-03-27 03:39:027271 std::move(callback).Run(id, http_status_code, image_url, images,
7272 original_image_sizes);
pkotwicz75ca8ffd2016-02-16 23:10:197273}
7274
[email protected]6fba26d2014-04-29 09:38:287275void WebContentsImpl::OnDialogClosed(int render_process_id,
7276 int render_frame_id,
Dave Tapuskacdf545cc2020-01-23 18:38:527277 JavaScriptDialogCallback response_callback,
Avi Drissman1a55a9d62020-03-10 18:56:457278 base::ScopedClosureRunner fullscreen_block,
[email protected]87de04b02014-04-08 22:14:497279 bool dialog_was_suppressed,
[email protected]b172aee2012-04-10 17:05:267280 bool success,
[email protected]fcf75d42013-12-03 20:11:267281 const base::string16& user_input) {
[email protected]6fba26d2014-04-29 09:38:287282 RenderFrameHostImpl* rfh = RenderFrameHostImpl::FromID(render_process_id,
7283 render_frame_id);
[email protected]87de04b02014-04-08 22:14:497284 last_dialog_suppressed_ = dialog_was_suppressed;
Avi Drissman1a55a9d62020-03-10 18:56:457285 fullscreen_block.RunAndReset();
[email protected]87de04b02014-04-08 22:14:497286
Charlie Reis96077362019-07-04 00:34:047287 javascript_dialog_navigation_deferrer_.reset();
7288
[email protected]beb440c2009-11-06 04:08:547289 if (is_showing_before_unload_dialog_ && !success) {
clamybc6f4152016-04-01 20:14:237290 // It is possible for the current RenderFrameHost to have changed in the
7291 // meantime. Do not reset the navigation state in that case.
7292 if (rfh && rfh == rfh->frame_tree_node()->current_frame_host()) {
clamy44e84ce2016-02-22 15:38:257293 rfh->frame_tree_node()->BeforeUnloadCanceled();
clamybc6f4152016-04-01 20:14:237294 controller_.DiscardNonCommittedEntries();
7295 }
[email protected]ec8e8b02013-06-19 04:57:107296
Charles Reis15d60b132017-11-03 17:43:477297 // Update the URL display either way, to avoid showing a stale URL.
7298 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
7299
Alexander Timin90c20c32020-08-12 15:28:327300 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7301 observer->BeforeUnloadDialogCancelled();
7302 });
[email protected]beb440c2009-11-06 04:08:547303 }
[email protected]87de04b02014-04-08 22:14:497304
Dave Tapuskacdf545cc2020-01-23 18:38:527305 std::move(response_callback).Run(success, user_input);
Pavel Feldman3c1842b2017-08-02 05:00:167306
Dave Tapuskacdf545cc2020-01-23 18:38:527307 std::vector<protocol::PageHandler*> page_handlers =
7308 protocol::PageHandler::EnabledForWebContents(this);
7309 for (auto* handler : page_handlers)
7310 handler->DidCloseJavaScriptDialog(success, user_input);
avi1c51fb62017-02-27 20:43:037311
7312 is_showing_javascript_dialog_ = false;
7313 is_showing_before_unload_dialog_ = false;
[email protected]beb440c2009-11-06 04:08:547314}
7315
[email protected]1ac10dca2013-08-20 20:47:047316bool WebContentsImpl::IsHidden() {
Francois Doraye6161152018-03-27 22:05:377317 return !IsBeingCaptured() && visibility_ != Visibility::VISIBLE;
[email protected]1ac10dca2013-08-20 20:47:047318}
7319
rob97250742015-12-10 17:45:157320int WebContentsImpl::GetOuterDelegateFrameTreeNodeId() {
lfg601233692017-03-06 22:45:447321 return node_.outer_contents_frame_tree_node_id();
lazyboy6ec48b2a2015-06-29 15:18:147322}
7323
ekaramadaeb3c5c2016-11-09 03:22:357324RenderWidgetHostImpl* WebContentsImpl::GetFullscreenRenderWidgetHost() const {
7325 return RenderWidgetHostImpl::FromID(fullscreen_widget_process_id_,
7326 fullscreen_widget_routing_id_);
7327}
7328
[email protected]b0936d22013-11-28 06:47:367329RenderFrameHostManager* WebContentsImpl::GetRenderManager() const {
[email protected]fa944cb82013-11-15 17:51:217330 return frame_tree_.root()->render_manager();
7331}
7332
[email protected]f8497342013-02-05 22:15:027333BrowserPluginGuest* WebContentsImpl::GetBrowserPluginGuest() const {
[email protected]7a846df2012-09-20 19:17:397334 return browser_plugin_guest_.get();
7335}
7336
Albert J. Wongc55cc64d2018-10-12 02:50:047337void WebContentsImpl::SetBrowserPluginGuest(
7338 std::unique_ptr<BrowserPluginGuest> guest) {
7339 DCHECK(!browser_plugin_guest_);
7340 DCHECK(guest);
7341 browser_plugin_guest_ = std::move(guest);
[email protected]738f57a2013-06-29 21:06:547342}
7343
Aidan Wolter52bcc12a2018-11-14 03:27:297344base::UnguessableToken WebContentsImpl::GetAudioGroupId() {
Aidan Wolter52bcc12a2018-11-14 03:27:297345 return GetAudioStreamFactory()->group_id();
7346}
7347
Miyoung Shin5709ab02020-02-19 06:50:417348const std::vector<blink::mojom::FaviconURLPtr>&
7349WebContentsImpl::GetFaviconURLs() {
Mounir Lamouri7b4a1f232019-12-23 16:32:107350 return favicon_urls_;
7351}
7352
Mugdha Lakhani0a0d7862020-07-29 09:58:457353// The Mac implementation of the next two methods is in
7354// web_contents_impl_mac.mm
Avi Drissmand4d79f72020-07-30 18:35:187355#if !defined(OS_MAC)
Mugdha Lakhani0a0d7862020-07-29 09:58:457356
7357void WebContentsImpl::Resize(const gfx::Rect& new_bounds) {
7358#if defined(USE_AURA)
7359 aura::Window* window = GetNativeView();
7360 window->SetBounds(gfx::Rect(window->bounds().origin(), new_bounds.size()));
7361#elif defined(OS_ANDROID)
7362 content::RenderWidgetHostView* view = GetRenderWidgetHostView();
7363 if (view)
7364 view->SetBounds(new_bounds);
7365#endif
7366}
7367
7368gfx::Size WebContentsImpl::GetSize() {
7369#if defined(USE_AURA)
7370 aura::Window* window = GetNativeView();
7371 return window->bounds().size();
7372#elif defined(OS_ANDROID)
7373 ui::ViewAndroid* view_android = GetNativeView();
7374 return view_android->bounds().size();
7375#endif
7376}
7377
Avi Drissmand4d79f72020-07-30 18:35:187378#endif // !defined(OS_MAC)
Mugdha Lakhani0a0d7862020-07-29 09:58:457379
[email protected]f8497342013-02-05 22:15:027380BrowserPluginEmbedder* WebContentsImpl::GetBrowserPluginEmbedder() const {
[email protected]7a846df2012-09-20 19:17:397381 return browser_plugin_embedder_.get();
7382}
[email protected]8ff00d72012-10-23 19:12:217383
fsamuel60b42282015-03-10 03:29:147384void WebContentsImpl::CreateBrowserPluginEmbedderIfNecessary() {
7385 if (browser_plugin_embedder_)
7386 return;
7387 browser_plugin_embedder_.reset(BrowserPluginEmbedder::Create(this));
7388}
7389
danakja0bce4c952020-05-12 20:40:287390gfx::Size WebContentsImpl::GetSizeForMainFrame() {
7391 if (delegate_) {
7392 // The delegate has a chance to specify a size independent of the UI.
7393 gfx::Size delegate_size = delegate_->GetSizeForNewRenderView(this);
7394 if (!delegate_size.IsEmpty())
7395 return delegate_size;
7396 }
7397
7398 // Device emulation, when enabled, can specify a size independent of the UI.
7399 if (!device_emulation_size_.IsEmpty())
7400 return device_emulation_size_;
7401
7402 return GetContainerBounds().size();
[email protected]dc0fd432013-08-27 15:29:217403}
7404
[email protected]ae7eeda2014-07-04 01:53:267405void WebContentsImpl::OnFrameRemoved(RenderFrameHost* render_frame_host) {
Alexander Timin90c20c32020-08-12 15:28:327406 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7407 observer->FrameDeleted(render_frame_host);
7408 });
[email protected]9b159a52013-10-03 17:24:557409}
7410
[email protected]222f5822014-02-05 23:40:497411void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size& old_size) {
7412 if (!delegate_)
7413 return;
7414 const gfx::Size new_size = GetPreferredSize();
7415 if (new_size != old_size)
7416 delegate_->UpdatePreferredSize(this, new_size);
7417}
7418
Miyoung Shin072d4052020-07-13 07:52:447419std::unique_ptr<WebUIImpl> WebContentsImpl::CreateWebUI(
7420 RenderFrameHost* frame_host,
7421 const GURL& url) {
7422 std::unique_ptr<WebUIImpl> web_ui =
7423 std::make_unique<WebUIImpl>(this, frame_host);
Lei Zhangee3b63ad2018-06-06 23:25:317424 std::unique_ptr<WebUIController> controller(
avie865b1d2016-10-24 19:42:597425 WebUIControllerFactoryRegistry::GetInstance()
Lei Zhangee3b63ad2018-06-06 23:25:317426 ->CreateWebUIControllerForURL(web_ui.get(), url));
dbeama1b926a2015-08-31 23:17:517427 if (controller) {
Lei Zhangee3b63ad2018-06-06 23:25:317428 web_ui->SetController(std::move(controller));
dbeama1b926a2015-08-31 23:17:517429 return web_ui;
7430 }
7431
avie865b1d2016-10-24 19:42:597432 return nullptr;
dbeama1b926a2015-08-31 23:17:517433}
7434
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:417435FindRequestManager* WebContentsImpl::GetFindRequestManager() {
7436 for (auto* contents = this; contents;
paulmeyerfeafc2d2017-04-25 21:46:407437 contents = contents->GetOuterWebContents()) {
7438 if (contents->find_request_manager_)
7439 return contents->find_request_manager_.get();
7440 }
7441
7442 return nullptr;
7443}
7444
paulmeyerc0b762b2016-04-13 11:55:177445FindRequestManager* WebContentsImpl::GetOrCreateFindRequestManager() {
paulmeyerfeafc2d2017-04-25 21:46:407446 if (FindRequestManager* manager = GetFindRequestManager())
7447 return manager;
7448
Ehsan Karamad6beb2ea2018-11-25 18:15:137449 DCHECK(!browser_plugin_guest_ || GetOuterWebContents());
7450
paulmeyerfeafc2d2017-04-25 21:46:407451 // No existing FindRequestManager found, so one must be created.
7452 find_request_manager_.reset(new FindRequestManager(this));
7453
7454 // Concurrent find sessions must not overlap, so destroy any existing
7455 // FindRequestManagers in any inner WebContentses.
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:167456 for (WebContents* contents : GetWebContentsAndAllInner()) {
7457 auto* web_contents_impl = static_cast<WebContentsImpl*>(contents);
7458 if (web_contents_impl == this)
paulmeyerfeafc2d2017-04-25 21:46:407459 continue;
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:167460 if (web_contents_impl->find_request_manager_) {
7461 web_contents_impl->find_request_manager_->StopFinding(
7462 STOP_FIND_ACTION_CLEAR_SELECTION);
7463 web_contents_impl->find_request_manager_.release();
paulmeyerfeafc2d2017-04-25 21:46:407464 }
7465 }
paulmeyerc0b762b2016-04-13 11:55:177466
7467 return find_request_manager_.get();
7468}
7469
7470void WebContentsImpl::NotifyFindReply(int request_id,
7471 int number_of_matches,
7472 const gfx::Rect& selection_rect,
7473 int active_match_ordinal,
7474 bool final_update) {
Sebastien Marchandcf97ed52017-07-24 23:50:347475 if (delegate_ && !is_being_destroyed_ &&
Lukasz Anforowicze9ae3722017-09-29 17:37:387476 !GetMainFrame()->GetProcess()->FastShutdownStarted()) {
paulmeyerc0b762b2016-04-13 11:55:177477 delegate_->FindReply(this, request_id, number_of_matches, selection_rect,
7478 active_match_ordinal, final_update);
7479 }
7480}
7481
ortuno467e5792016-06-10 04:32:397482void WebContentsImpl::IncrementBluetoothConnectedDeviceCount() {
7483 // Trying to invalidate the tab state while being destroyed could result in a
7484 // use after free.
7485 if (IsBeingDestroyed()) {
7486 return;
7487 }
7488 // Notify for UI updates if the state changes.
7489 bluetooth_connected_device_count_++;
7490 if (bluetooth_connected_device_count_ == 1) {
Francois Doray66766a572019-12-17 20:56:497491 OnIsConnectedToBluetoothDeviceChanged(true);
ortuno467e5792016-06-10 04:32:397492 }
7493}
7494
7495void WebContentsImpl::DecrementBluetoothConnectedDeviceCount() {
7496 // Trying to invalidate the tab state while being destroyed could result in a
7497 // use after free.
7498 if (IsBeingDestroyed()) {
7499 return;
7500 }
7501 // Notify for UI updates if the state changes.
Lukasz Anforowicze9ae3722017-09-29 17:37:387502 DCHECK_NE(bluetooth_connected_device_count_, 0u);
ortuno467e5792016-06-10 04:32:397503 bluetooth_connected_device_count_--;
7504 if (bluetooth_connected_device_count_ == 0) {
Francois Doray66766a572019-12-17 20:56:497505 OnIsConnectedToBluetoothDeviceChanged(false);
7506 }
7507}
7508
7509void WebContentsImpl::OnIsConnectedToBluetoothDeviceChanged(
7510 bool is_connected_to_bluetooth_device) {
7511 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
Alexander Timin90c20c32020-08-12 15:28:327512 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7513 observer->OnIsConnectedToBluetoothDeviceChanged(
Francois Doray66766a572019-12-17 20:56:497514 is_connected_to_bluetooth_device);
Alexander Timin90c20c32020-08-12 15:28:327515 });
ortuno467e5792016-06-10 04:32:397516}
7517
Ovidio Henriquez76696f62020-07-08 03:06:597518void WebContentsImpl::IncrementBluetoothScanningSessionsCount() {
7519 // Trying to invalidate the tab state while being destroyed could result in a
7520 // use after free.
7521 if (IsBeingDestroyed())
7522 return;
7523
7524 // Notify for UI updates if the state changes.
7525 bluetooth_scanning_sessions_count_++;
7526 if (bluetooth_scanning_sessions_count_ == 1)
7527 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
7528}
7529
7530void WebContentsImpl::DecrementBluetoothScanningSessionsCount() {
7531 // Trying to invalidate the tab state while being destroyed could result in a
7532 // use after free.
7533 if (IsBeingDestroyed())
7534 return;
7535
7536 DCHECK_NE(0u, bluetooth_scanning_sessions_count_);
7537 bluetooth_scanning_sessions_count_--;
7538 if (bluetooth_scanning_sessions_count_ == 0)
7539 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
7540}
7541
Reilly Grant5e7c79b22019-04-09 17:26:207542void WebContentsImpl::IncrementSerialActiveFrameCount() {
7543 // Trying to invalidate the tab state while being destroyed could result in a
7544 // use after free.
7545 if (IsBeingDestroyed())
7546 return;
7547
7548 // Notify for UI updates if the state changes.
7549 serial_active_frame_count_++;
7550 if (serial_active_frame_count_ == 1)
7551 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
7552}
7553
7554void WebContentsImpl::DecrementSerialActiveFrameCount() {
7555 // Trying to invalidate the tab state while being destroyed could result in a
7556 // use after free.
7557 if (IsBeingDestroyed())
7558 return;
7559
7560 // Notify for UI updates if the state changes.
7561 DCHECK_NE(0u, serial_active_frame_count_);
7562 serial_active_frame_count_--;
7563 if (serial_active_frame_count_ == 0)
7564 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
7565}
7566
Matt Reynoldse8c6c1f2019-11-02 09:53:537567void WebContentsImpl::IncrementHidActiveFrameCount() {
7568 // Trying to invalidate the tab state while being destroyed could result in a
7569 // use after free.
7570 if (IsBeingDestroyed())
7571 return;
7572
7573 // Notify for UI updates if the active frame count transitions from zero to
7574 // non-zero.
7575 hid_active_frame_count_++;
7576 if (hid_active_frame_count_ == 1)
7577 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
7578}
7579
7580void WebContentsImpl::DecrementHidActiveFrameCount() {
7581 // Trying to invalidate the tab state while being destroyed could result in a
7582 // use after free.
7583 if (IsBeingDestroyed())
7584 return;
7585
7586 // Notify for UI updates if the active frame count transitions from non-zero
7587 // to zero.
7588 DCHECK_NE(0u, hid_active_frame_count_);
7589 hid_active_frame_count_--;
7590 if (hid_active_frame_count_ == 0)
7591 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
7592}
7593
Marijn Kruisselbrink29051042019-08-06 22:56:557594void WebContentsImpl::IncrementNativeFileSystemHandleCount() {
7595 // Trying to invalidate the tab state while being destroyed could result in a
7596 // use after free.
7597 if (IsBeingDestroyed())
7598 return;
7599
7600 // Notify for UI updates if the state changes. Need both TYPE_TAB and TYPE_URL
7601 // to update both the tab-level usage indicator and the usage indicator in the
7602 // omnibox.
7603 native_file_system_handle_count_++;
7604 if (native_file_system_handle_count_ == 1) {
7605 NotifyNavigationStateChanged(static_cast<content::InvalidateTypes>(
7606 INVALIDATE_TYPE_TAB | INVALIDATE_TYPE_URL));
7607 }
7608}
7609
7610void WebContentsImpl::DecrementNativeFileSystemHandleCount() {
7611 // Trying to invalidate the tab state while being destroyed could result in a
7612 // use after free.
7613 if (IsBeingDestroyed())
7614 return;
7615
7616 // Notify for UI updates if the state changes. Need both TYPE_TAB and TYPE_URL
7617 // to update both the tab-level usage indicator and the usage indicator in the
7618 // omnibox.
7619 DCHECK_NE(0u, native_file_system_handle_count_);
7620 native_file_system_handle_count_--;
7621 if (native_file_system_handle_count_ == 0) {
7622 NotifyNavigationStateChanged(static_cast<content::InvalidateTypes>(
7623 INVALIDATE_TYPE_TAB | INVALIDATE_TYPE_URL));
7624 }
7625}
7626
zqzhang8ac49002017-03-16 21:51:357627void WebContentsImpl::SetHasPersistentVideo(bool has_persistent_video) {
7628 if (has_persistent_video_ == has_persistent_video)
mlamouri5cd9ae82017-02-18 11:05:097629 return;
7630
zqzhang8ac49002017-03-16 21:51:357631 has_persistent_video_ = has_persistent_video;
mlamouri5cd9ae82017-02-18 11:05:097632 NotifyPreferencesChanged();
zqzhang8ac49002017-03-16 21:51:357633 media_web_contents_observer()->RequestPersistentVideo(has_persistent_video);
mlamouri5cd9ae82017-02-18 11:05:097634}
7635
Ian Vollick5d5c37f2019-06-19 22:50:577636void WebContentsImpl::SetSpatialNavigationDisabled(bool disabled) {
7637 if (is_spatial_navigation_disabled_ == disabled)
7638 return;
7639
7640 is_spatial_navigation_disabled_ = disabled;
7641 NotifyPreferencesChanged();
7642}
7643
paulmeyerfeafc2d2017-04-25 21:46:407644void WebContentsImpl::BrowserPluginGuestWillDetach() {
7645 WebContentsImpl* outermost = GetOutermostWebContents();
7646 if (this != outermost && ContainsOrIsFocusedWebContents())
7647 outermost->SetAsFocusedWebContentsIfNecessary();
7648}
7649
Becca Hughes112832e2019-06-11 17:19:027650PictureInPictureResult WebContentsImpl::EnterPictureInPicture(
Mounir Lamouri11e9ef42018-05-22 03:10:167651 const viz::SurfaceId& surface_id,
7652 const gfx::Size& natural_size) {
François Beaufortf09e4462019-01-18 14:34:517653 return delegate_
7654 ? delegate_->EnterPictureInPicture(this, surface_id, natural_size)
Becca Hughes112832e2019-06-11 17:19:027655 : PictureInPictureResult::kNotSupported;
Mounir Lamouri11e9ef42018-05-22 03:10:167656}
7657
Mounir Lamouri6d759e12018-05-16 20:01:307658void WebContentsImpl::ExitPictureInPicture() {
7659 if (delegate_)
7660 delegate_->ExitPictureInPicture();
7661}
7662
paulmeyerc0b762b2016-04-13 11:55:177663#if defined(OS_ANDROID)
7664void WebContentsImpl::NotifyFindMatchRectsReply(
7665 int version,
7666 const std::vector<gfx::RectF>& rects,
7667 const gfx::RectF& active_rect) {
7668 if (delegate_)
7669 delegate_->FindMatchRectsReply(this, version, rects, active_rect);
7670}
7671#endif
7672
[email protected]34ff1cfc2014-08-20 06:16:057673void WebContentsImpl::SetForceDisableOverscrollContent(bool force_disable) {
7674 force_disable_overscroll_content_ = force_disable;
7675 if (view_)
7676 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
7677}
7678
Jianzhou Fengd8720c72018-01-18 03:06:307679bool WebContentsImpl::SetDeviceEmulationSize(const gfx::Size& new_size) {
7680 device_emulation_size_ = new_size;
7681 RenderWidgetHostView* rwhv = GetMainFrame()->GetView();
7682
7683 const gfx::Size current_size = rwhv->GetViewBounds().size();
7684 if (view_size_before_emulation_.IsEmpty())
7685 view_size_before_emulation_ = current_size;
7686
7687 if (current_size != new_size)
7688 rwhv->SetSize(new_size);
7689
7690 return current_size != new_size;
7691}
7692
7693void WebContentsImpl::ClearDeviceEmulationSize() {
7694 RenderWidgetHostView* rwhv = GetMainFrame()->GetView();
7695 // WebContentsView could get resized during emulation, which also resizes
7696 // RWHV. If it happens, assume user would like to keep using the size after
7697 // emulation.
7698 // TODO(jzfeng): Prohibit resizing RWHV through any other means (at least when
7699 // WebContentsView size changes).
Dmitry Gozmanc63707182018-03-06 00:09:397700 if (!view_size_before_emulation_.IsEmpty() && rwhv &&
7701 rwhv->GetViewBounds().size() == device_emulation_size_) {
Jianzhou Fengd8720c72018-01-18 03:06:307702 rwhv->SetSize(view_size_before_emulation_);
Dmitry Gozmanc63707182018-03-06 00:09:397703 }
Jianzhou Fengd8720c72018-01-18 03:06:307704 device_emulation_size_ = gfx::Size();
7705 view_size_before_emulation_ = gfx::Size();
7706}
7707
Max Morin5bc74f52018-05-09 07:00:217708ForwardingAudioStreamFactory* WebContentsImpl::GetAudioStreamFactory() {
7709 if (!audio_stream_factory_) {
7710 audio_stream_factory_.emplace(
7711 this,
Max Morinddebb972018-09-20 10:04:147712 // BrowserMainLoop::GetInstance() may be null in unit tests.
7713 BrowserMainLoop::GetInstance()
7714 ? static_cast<media::UserInputMonitorBase*>(
7715 BrowserMainLoop::GetInstance()->user_input_monitor())
7716 : nullptr,
Ken Rockot72964402019-12-06 10:40:517717 AudioStreamBrokerFactory::CreateImpl());
Max Morin5bc74f52018-05-09 07:00:217718 }
7719
7720 return &*audio_stream_factory_;
7721}
7722
dalecurtis88c240072015-12-09 02:11:187723void WebContentsImpl::MediaStartedPlaying(
billorr21c005d2016-11-17 03:57:047724 const WebContentsObserver::MediaPlayerInfo& media_info,
Mounir Lamouri0f5bdf52019-04-04 16:32:357725 const MediaPlayerId& id) {
billorr21c005d2016-11-17 03:57:047726 if (media_info.has_video)
7727 currently_playing_video_count_++;
7728
Alexander Timin90c20c32020-08-12 15:28:327729 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7730 observer->MediaStartedPlaying(media_info, id);
7731 });
dalecurtis88c240072015-12-09 02:11:187732}
7733
7734void WebContentsImpl::MediaStoppedPlaying(
billorr21c005d2016-11-17 03:57:047735 const WebContentsObserver::MediaPlayerInfo& media_info,
Mounir Lamouri0f5bdf52019-04-04 16:32:357736 const MediaPlayerId& id,
Becca Hughes220bfc102017-11-14 18:24:077737 WebContentsObserver::MediaStoppedReason reason) {
billorr21c005d2016-11-17 03:57:047738 if (media_info.has_video)
7739 currently_playing_video_count_--;
7740
Alexander Timin90c20c32020-08-12 15:28:327741 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7742 observer->MediaStoppedPlaying(media_info, id, reason);
7743 });
billorr21c005d2016-11-17 03:57:047744}
7745
Mounir Lamouri0f5bdf52019-04-04 16:32:357746void WebContentsImpl::MediaResized(const gfx::Size& size,
7747 const MediaPlayerId& id) {
peconn257951522017-06-09 18:24:597748 cached_video_sizes_[id] = size;
7749
Alexander Timin90c20c32020-08-12 15:28:327750 observers_.ForEachObserver(
7751 [&](WebContentsObserver* observer) { observer->MediaResized(size, id); });
peconn257951522017-06-09 18:24:597752}
7753
Michael Crousee75c7a42020-07-31 21:11:557754void WebContentsImpl::MediaBufferUnderflow(const MediaPlayerId& id) {
Alexander Timin90c20c32020-08-12 15:28:327755 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7756 observer->MediaBufferUnderflow(id);
7757 });
Michael Crousee75c7a42020-07-31 21:11:557758}
7759
Peter E Conneccb34c22017-09-08 09:37:587760void WebContentsImpl::MediaEffectivelyFullscreenChanged(bool is_fullscreen) {
Alexander Timin90c20c32020-08-12 15:28:327761 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7762 observer->MediaEffectivelyFullscreenChanged(is_fullscreen);
7763 });
Peter E Conneccb34c22017-09-08 09:37:587764}
7765
Peter Conn31c726a2017-08-17 11:07:347766base::Optional<gfx::Size> WebContentsImpl::GetFullscreenVideoSize() {
Mounir Lamouri0f5bdf52019-04-04 16:32:357767 base::Optional<MediaPlayerId> id =
Peter Conn31c726a2017-08-17 11:07:347768 media_web_contents_observer_->GetFullscreenVideoMediaPlayerId();
Jan Wilken Dörrie531be7ca2019-06-07 10:05:577769 if (id && base::Contains(cached_video_sizes_, id.value()))
Peter Conn31c726a2017-08-17 11:07:347770 return base::Optional<gfx::Size>(cached_video_sizes_[id.value()]);
Lei Zhang6410ec1a2019-01-31 21:38:587771 return base::nullopt;
peconn257951522017-06-09 18:24:597772}
7773
billorr21c005d2016-11-17 03:57:047774int WebContentsImpl::GetCurrentlyPlayingVideoCount() {
7775 return currently_playing_video_count_;
dalecurtis88c240072015-12-09 02:11:187776}
7777
Raymond Toye413650c2018-08-31 00:12:477778void WebContentsImpl::AudioContextPlaybackStarted(RenderFrameHost* host,
7779 int context_id) {
7780 WebContentsObserver::AudioContextId audio_context_id(host, context_id);
Alexander Timin90c20c32020-08-12 15:28:327781 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7782 observer->AudioContextPlaybackStarted(audio_context_id);
7783 });
Raymond Toye413650c2018-08-31 00:12:477784}
7785
7786void WebContentsImpl::AudioContextPlaybackStopped(RenderFrameHost* host,
7787 int context_id) {
7788 WebContentsObserver::AudioContextId audio_context_id(host, context_id);
Alexander Timin90c20c32020-08-12 15:28:327789 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7790 observer->AudioContextPlaybackStopped(audio_context_id);
7791 });
Raymond Toye413650c2018-08-31 00:12:477792}
7793
Chris Hamilton16ca64a2020-05-14 23:13:177794void WebContentsImpl::OnFrameAudioStateChanged(RenderFrameHost* host,
7795 bool is_audible) {
Alexander Timin90c20c32020-08-12 15:28:327796 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7797 observer->OnFrameAudioStateChanged(host, is_audible);
7798 });
Chris Hamilton16ca64a2020-05-14 23:13:177799}
7800
evliu7f736f02019-11-07 17:43:507801media::MediaMetricsProvider::RecordAggregateWatchTimeCallback
7802WebContentsImpl::GetRecordAggregateWatchTimeCallback() {
Becca Hughes53652442020-03-17 15:35:427803 if (!delegate_ || !delegate_->GetDelegateWeakPtr())
7804 return base::DoNothing();
7805
evliu7f736f02019-11-07 17:43:507806 return base::BindRepeating(
Becca Hughes53652442020-03-17 15:35:427807 [](base::WeakPtr<WebContentsDelegate> delegate, GURL last_committed_url,
7808 base::TimeDelta total_watch_time, base::TimeDelta time_stamp,
7809 bool has_video, bool has_audio) {
evliua283c9e2019-11-08 22:57:227810 content::MediaPlayerWatchTime watch_time(
7811 last_committed_url, last_committed_url.GetOrigin(),
7812 total_watch_time, time_stamp, has_video, has_audio);
evliu7f736f02019-11-07 17:43:507813
7814 // Save the watch time if the delegate is still alive.
7815 if (delegate)
7816 delegate->MediaWatchTimeChanged(watch_time);
7817 },
Becca Hughes53652442020-03-17 15:35:427818 delegate_->GetDelegateWeakPtr(), GetMainFrameLastCommittedURL());
evliu7f736f02019-11-07 17:43:507819}
7820
Ehsan Karamad1c631762019-05-13 23:04:017821RenderFrameHostImpl* WebContentsImpl::GetMainFrameForInnerDelegate(
7822 FrameTreeNode* frame_tree_node) {
7823 if (auto* web_contents = node_.GetInnerWebContentsInFrame(frame_tree_node))
7824 return web_contents->GetMainFrame();
7825 return nullptr;
7826}
7827
John Budorickee1c9512019-10-17 15:32:197828bool WebContentsImpl::IsFrameLowPriority(
7829 const RenderFrameHost* render_frame_host) {
7830 if (!delegate_)
7831 return false;
7832 return delegate_->IsFrameLowPriority(this, render_frame_host);
7833}
7834
Roger Tawa03ffdbd2020-01-16 18:12:547835void WebContentsImpl::IsClipboardPasteAllowed(
7836 const GURL& url,
7837 const ui::ClipboardFormatType& data_type,
7838 const std::string& data,
7839 IsClipboardPasteAllowedCallback callback) {
Dominique Fauteux-Chapleau99244382020-07-08 20:37:007840 ++suppress_unresponsive_renderer_count_;
Roger Tawa03ffdbd2020-01-16 18:12:547841 GetContentClient()->browser()->IsClipboardPasteAllowed(
Dominique Fauteux-Chapleau99244382020-07-08 20:37:007842 this, url, data_type, data,
7843 base::BindOnce(&WebContentsImpl::IsClipboardPasteAllowedWrapperCallback,
7844 weak_factory_.GetWeakPtr(), std::move(callback)));
7845}
7846
7847void WebContentsImpl::IsClipboardPasteAllowedWrapperCallback(
7848 IsClipboardPasteAllowedCallback callback,
7849 ClipboardPasteAllowed allowed) {
7850 std::move(callback).Run(allowed);
7851 --suppress_unresponsive_renderer_count_;
Roger Tawa03ffdbd2020-01-16 18:12:547852}
7853
Lan Weif81c6e7c2020-02-12 16:46:097854bool WebContentsImpl::HasSeenRecentScreenOrientationChange() {
7855 static constexpr base::TimeDelta kMaxInterval =
7856 base::TimeDelta::FromSeconds(1);
7857 base::TimeDelta delta =
7858 ui::EventTimeForNow() - last_screen_orientation_change_time_;
7859 // Return whether there is a screen orientation change happened in the recent
7860 // 1 second.
7861 return delta <= kMaxInterval;
7862}
7863
7864void WebContentsImpl::DidChangeScreenOrientation() {
7865 last_screen_orientation_change_time_ = ui::EventTimeForNow();
7866}
7867
Miyoung Shin8f2e1832020-04-27 09:00:027868bool WebContentsImpl::ShowPopupMenu(
Miyoung Shin4d947d22020-04-24 04:48:337869 RenderFrameHostImpl* render_frame_host,
Miyoung Shin8f2e1832020-04-27 09:00:027870 mojo::PendingRemote<blink::mojom::PopupMenuClient>* popup_client,
Miyoung Shin4d947d22020-04-24 04:48:337871 const gfx::Rect& bounds,
7872 int32_t item_height,
7873 double font_size,
7874 int32_t selected_item,
7875 std::vector<blink::mojom::MenuItemPtr>* menu_items,
7876 bool right_aligned,
7877 bool allow_multiple_selection) {
Alexander Timin90c20c32020-08-12 15:28:327878 for (auto& observer : observers_.observer_list()) {
Miyoung Shin8f2e1832020-04-27 09:00:027879 if (observer.ShowPopupMenu(render_frame_host, popup_client, bounds,
7880 item_height, font_size, selected_item,
7881 menu_items, right_aligned,
7882 allow_multiple_selection)) {
Miyoung Shin4d947d22020-04-24 04:48:337883 return true;
7884 }
7885 }
7886 return false;
7887}
7888
Francois Doraye6161152018-03-27 22:05:377889void WebContentsImpl::UpdateWebContentsVisibility(Visibility visibility) {
Francois Doray3f2afbd2018-04-06 19:18:187890 // Occlusion is disabled when |features::kWebContentsOcclusion| is disabled
7891 // (for power and speed impact assessment) or when
7892 // |switches::kDisableBackgroundingOccludedWindowsForTesting| is specified on
7893 // the command line (to avoid flakiness in browser tests).
7894 const bool occlusion_is_disabled =
7895 !base::FeatureList::IsEnabled(features::kWebContentsOcclusion) ||
Francois Doraye6161152018-03-27 22:05:377896 base::CommandLine::ForCurrentProcess()->HasSwitch(
7897 switches::kDisableBackgroundingOccludedWindowsForTesting);
7898 if (occlusion_is_disabled && visibility == Visibility::OCCLUDED)
7899 visibility = Visibility::VISIBLE;
7900
tapted65ff2ea72016-03-01 23:39:007901 if (!did_first_set_visible_) {
Francois Doraye6161152018-03-27 22:05:377902 if (visibility == Visibility::VISIBLE) {
7903 // A WebContents created with CreateParams::initially_hidden = false
7904 // starts with GetVisibility() == Visibility::VISIBLE even though it is
7905 // not really visible. Call WasShown() when it becomes visible for real as
7906 // the page load mechanism and some WebContentsObserver rely on that.
tapted65ff2ea72016-03-01 23:39:007907 WasShown();
Francois Dorayfe4a1772018-02-17 04:17:097908 did_first_set_visible_ = true;
tapted65ff2ea72016-03-01 23:39:007909 }
Francois Doraye6161152018-03-27 22:05:377910
7911 // Trust the initial visibility of the WebContents and do not switch it to
7912 // HIDDEN or OCCLUDED before it becomes VISIBLE for real. Doing so would
7913 // result in destroying resources that would immediately be recreated (e.g.
7914 // UpdateWebContents(HIDDEN) can be called when a WebContents is added to a
7915 // hidden window that is about to be shown).
7916
tapted65ff2ea72016-03-01 23:39:007917 return;
7918 }
Francois Doraye6161152018-03-27 22:05:377919
7920 if (visibility == visibility_)
tapted65ff2ea72016-03-01 23:39:007921 return;
7922
Collin Baker989e0882019-11-01 01:27:177923 UpdateVisibilityAndNotifyPageAndView(visibility);
tapted65ff2ea72016-03-01 23:39:007924}
7925
aelias5252baa2016-04-10 01:18:027926void WebContentsImpl::UpdateOverridingUserAgent() {
mlamouri5cd9ae82017-02-18 11:05:097927 NotifyPreferencesChanged();
aelias5252baa2016-04-10 01:18:027928}
7929
avid53461d2016-02-25 17:15:047930void WebContentsImpl::SetJavaScriptDialogManagerForTesting(
7931 JavaScriptDialogManager* dialog_manager) {
7932 dialog_manager_ = dialog_manager;
7933}
7934
Julie Jeongeun Kim7d0986172019-12-04 03:17:257935void WebContentsImpl::RemoveReceiverSet(const std::string& interface_name) {
7936 auto it = receiver_sets_.find(interface_name);
7937 if (it != receiver_sets_.end())
7938 receiver_sets_.erase(it);
rockotf62002a2016-09-15 00:08:597939}
7940
nzolghadrd87a308d2016-12-07 15:45:567941bool WebContentsImpl::AddDomainInfoToRapporSample(rappor::Sample* sample) {
nzolghadrbbffc6c2017-05-25 17:56:397942 // Here we associate this metric to the main frame URL regardless of what
7943 // caused it.
nzolghadrd87a308d2016-12-07 15:45:567944 sample->SetStringField("Domain", ::rappor::GetDomainAndRegistrySampleFromGURL(
7945 GetLastCommittedURL()));
nzolghadrd87a308d2016-12-07 15:45:567946 return true;
7947}
7948
falken52a56e32016-12-08 05:02:407949void WebContentsImpl::ShowInsecureLocalhostWarningIfNeeded() {
7950 bool allow_localhost = base::CommandLine::ForCurrentProcess()->HasSwitch(
7951 switches::kAllowInsecureLocalhost);
7952 if (!allow_localhost)
7953 return;
7954
7955 content::NavigationEntry* entry = GetController().GetLastCommittedEntry();
Rob Wuf79b3ba2018-01-14 01:54:317956 if (!entry || !net::IsLocalhost(entry->GetURL()))
falken52a56e32016-12-08 05:02:407957 return;
7958
7959 content::SSLStatus ssl_status = entry->GetSSL();
Matt Mueller936511442019-09-03 18:15:127960 if (!net::IsCertStatusError(ssl_status.cert_status))
falken52a56e32016-12-08 05:02:407961 return;
7962
7963 GetMainFrame()->AddMessageToConsole(
Abhijeet Kandalkara5928a0a2019-03-13 05:04:427964 blink::mojom::ConsoleMessageLevel::kWarning,
falken52a56e32016-12-08 05:02:407965 base::StringPrintf("This site does not have a valid SSL "
7966 "certificate! Without SSL, your site's and "
7967 "visitors' data is vulnerable to theft and "
7968 "tampering. Get a valid SSL certificate before"
7969 " releasing your website to the public."));
7970}
7971
ekaramadf6750aa2017-06-06 18:29:427972bool WebContentsImpl::IsShowingContextMenuOnPage() const {
7973 return showing_context_menu_;
7974}
7975
Min Qina904f3302018-02-13 23:33:347976download::DownloadUrlParameters::RequestHeadersType
7977WebContentsImpl::ParseDownloadHeaders(const std::string& headers) {
7978 download::DownloadUrlParameters::RequestHeadersType request_headers;
Megan Jablonski2f6a4c52017-07-10 23:01:257979 for (const base::StringPiece& key_value : base::SplitStringPiece(
7980 headers, "\r\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) {
7981 std::vector<std::string> pair = base::SplitString(
7982 key_value, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
7983 if (2ul == pair.size())
7984 request_headers.push_back(make_pair(pair[0], pair[1]));
7985 }
7986 return request_headers;
7987}
7988
lukasza6f8ac622017-06-06 03:10:207989void WebContentsImpl::SetOpenerForNewContents(FrameTreeNode* opener,
7990 bool opener_suppressed) {
7991 if (opener) {
7992 FrameTreeNode* new_root = GetFrameTree()->root();
7993
7994 // For the "original opener", track the opener's main frame instead, because
7995 // if the opener is a subframe, the opener tracking could be easily bypassed
7996 // by spawning from a subframe and deleting the subframe.
7997 // https://crbug.com/705316
7998 new_root->SetOriginalOpener(opener->frame_tree()->root());
7999
8000 if (!opener_suppressed) {
8001 new_root->SetOpener(opener);
8002 created_with_opener_ = true;
8003 }
8004 }
8005}
8006
Mounir Lamouri0f5bdf52019-04-04 16:32:358007void WebContentsImpl::MediaMutedStatusChanged(const MediaPlayerId& id,
8008 bool muted) {
Alexander Timin90c20c32020-08-12 15:28:328009 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8010 observer->MediaMutedStatusChanged(id, muted);
8011 });
Becca Hughes9f6fd4b82017-06-15 10:01:408012}
8013
EhsanK2075c7e2017-08-21 02:42:398014void WebContentsImpl::SetVisibilityForChildViews(bool visible) {
8015 GetMainFrame()->SetVisibilityForChildViews(visible);
8016}
8017
Alison Maher7f366dc62020-03-03 19:46:008018void WebContentsImpl::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) {
8019 DCHECK(native_theme_observer_.IsObserving(observed_theme));
8020
8021 bool using_dark_colors = observed_theme->ShouldUseDarkColors();
8022 ui::NativeTheme::PreferredColorScheme preferred_color_scheme =
8023 observed_theme->GetPreferredColorScheme();
8024 bool preferences_changed = false;
8025
8026 if (using_dark_colors_ != using_dark_colors) {
8027 using_dark_colors_ = using_dark_colors;
8028 preferences_changed = true;
8029 }
8030 if (preferred_color_scheme_ != preferred_color_scheme) {
8031 preferred_color_scheme_ = preferred_color_scheme;
8032 preferences_changed = true;
8033 }
8034
8035 if (preferences_changed)
8036 NotifyPreferencesChanged();
8037}
8038
Dave Tapuska58a099e2020-06-08 21:48:408039blink::mojom::FrameWidgetInputHandler*
8040WebContentsImpl::GetFocusedFrameWidgetInputHandler() {
8041 auto* focused_render_widget_host =
8042 GetFocusedRenderWidgetHost(GetMainFrame()->GetRenderWidgetHost());
8043 if (!focused_render_widget_host)
Dave Tapuskae782bea2019-07-09 16:21:518044 return nullptr;
Dave Tapuska58a099e2020-06-08 21:48:408045 return focused_render_widget_host->GetFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:518046}
8047
Alexander Timine3ec4192020-04-20 16:39:408048ukm::SourceId WebContentsImpl::GetCurrentPageUkmSourceId() {
8049 return GetMainFrame()->GetPageUkmSourceId();
8050}
8051
Yuzu Saijo232076f2020-05-29 07:14:028052std::set<RenderViewHostImpl*>
8053WebContentsImpl::GetRenderViewHostsIncludingBackForwardCached() {
8054 std::set<RenderViewHostImpl*> render_view_hosts;
8055
8056 // Add RenderViewHostImpls outside of BackForwardCache.
8057 for (auto& render_view_host : frame_tree_.render_view_hosts()) {
8058 render_view_hosts.insert(render_view_host.second);
8059 }
8060
8061 // Add RenderViewHostImpls in BackForwardCache.
8062 const auto& entries = GetController().GetBackForwardCache().GetEntries();
8063 for (const auto& entry : entries) {
8064 std::set<RenderViewHostImpl*> bfcached_hosts = entry->render_view_hosts;
8065 render_view_hosts.insert(bfcached_hosts.begin(), bfcached_hosts.end());
8066 }
8067
8068 return render_view_hosts;
8069}
8070
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:508071void WebContentsImpl::RenderFrameHostStateChanged(
8072 RenderFrameHost* render_frame_host,
8073 LifecycleState old_state,
8074 LifecycleState new_state) {
8075 if (render_frame_host->GetParent())
8076 return;
8077
8078 if (old_state == LifecycleState::kActive &&
8079 new_state != LifecycleState::kActive) {
8080 // TODO(sreejakshetty): Remove this reset when ColorChooser becomes
8081 // per-frame.
8082 // Close the color chooser popup when RenderFrameHost changes state from
8083 // kActive.
8084 color_chooser_.reset();
8085 }
8086}
8087
[email protected]8ff00d72012-10-23 19:12:218088} // namespace content