blob: 8194f70244b5d14799dd02d8f8916fbd2edd6908 [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"
Yuzu Saijoa11069a2020-04-22 10:56:5578#include "content/browser/plugin_content_origin_allowlist.h"
Kevin McNee94ea52f52020-06-23 17:42:0679#include "content/browser/portal/portal.h"
David Black9cca3592019-11-06 23:02:2280#include "content/browser/renderer_host/frame_token_message_queue.h"
[email protected]f3b1a082011-11-18 00:34:3081#include "content/browser/renderer_host/render_process_host_impl.h"
[email protected]21161032014-05-05 16:56:5082#include "content/browser/renderer_host/render_view_host_delegate_view.h"
[email protected]b3c41c0b2012-03-06 15:48:3283#include "content/browser/renderer_host/render_view_host_impl.h"
[email protected]bafe6cd2012-05-23 23:09:5084#include "content/browser/renderer_host/render_widget_host_impl.h"
kenrb2a565f82015-09-02 20:24:5985#include "content/browser/renderer_host/render_widget_host_input_event_router.h"
[email protected]cfd80b02014-05-01 17:46:4886#include "content/browser/renderer_host/render_widget_host_view_base.h"
Ken Buchanandaef006b2017-08-17 18:32:1587#include "content/browser/renderer_host/render_widget_host_view_child_frame.h"
ekaramadadd882292016-06-08 15:22:5688#include "content/browser/renderer_host/text_input_manager.h"
Mike Wassermanb213b9352020-04-16 00:32:3489#include "content/browser/screen_enumeration/screen_change_monitor.h"
leon.han552e9de2017-02-09 14:37:3090#include "content/browser/screen_orientation/screen_orientation_provider.h"
[email protected]b6583592012-01-25 19:52:3391#include "content/browser/site_instance_impl.h"
Charlie Reis96077362019-07-04 00:34:0492#include "content/browser/web_contents/javascript_dialog_navigation_deferrer.h"
lfgc740d4b22016-04-15 16:45:3393#include "content/browser/web_contents/web_contents_view_child_frame.h"
Tsuyoshi Horob0d8d902020-03-12 00:09:3994#include "content/browser/web_package/save_as_web_bundle_job.h"
[email protected]86a0a6e2013-01-28 06:33:0395#include "content/browser/webui/web_ui_controller_factory_registry.h"
[email protected]d2353452012-01-19 19:53:5696#include "content/browser/webui/web_ui_impl.h"
[email protected]8eb04562013-03-06 03:41:1497#include "content/common/browser_plugin/browser_plugin_constants.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:2098#include "content/common/content_switches_internal.h"
Paul Meyer0c58c3712016-11-17 22:59:5199#include "content/common/drag_messages.h"
[email protected]f114fa42013-12-06 17:06:44100#include "content/common/frame_messages.h"
[email protected]1f3fc1d2014-04-03 14:50:17101#include "content/common/input_messages.h"
lfgdb5c4ed2016-03-04 23:09:07102#include "content/common/page_messages.h"
nasko34634672016-07-29 18:46:06103#include "content/common/page_state_serialization.h"
rockot5c478a72016-09-28 23:14:18104#include "content/common/render_message_filter.mojom.h"
[email protected]2c5569662011-03-22 20:45:02105#include "content/common/view_messages.h"
Albert J. Wong3c93c182018-09-27 17:29:43106#include "content/common/widget_messages.h"
Abigail Kleinabb428332019-09-13 18:26:21107#include "content/public/browser/accessibility_tree_formatter.h"
[email protected]31a71eaf2014-03-13 01:47:36108#include "content/public/browser/ax_event_notification_details.h"
[email protected]ccb797302011-12-15 16:55:11109#include "content/public/browser/browser_context.h"
[email protected]139355f2014-05-11 14:21:28110#include "content/public/browser/browser_plugin_guest_manager.h"
Eric Seckler8652dcd52018-09-20 10:42:28111#include "content/public/browser/browser_task_traits.h"
Gabriel Charette790754c2018-03-16 21:32:59112#include "content/public/browser/browser_thread.h"
[email protected]87f3c082011-10-19 18:07:44113#include "content/public/browser/content_browser_client.h"
Lukasz Anforowicz8c4446dc2020-03-11 22:16:42114#include "content/public/browser/context_menu_params.h"
Ken Rockotce010f02019-12-12 23:32:32115#include "content/public/browser/device_service.h"
[email protected]e582fdd2011-12-20 16:48:17116#include "content/public/browser/download_manager.h"
Kent Tamura512a27e2018-10-04 00:49:32117#include "content/public/browser/file_select_listener.h"
ekaramada110f642016-12-21 19:47:28118#include "content/public/browser/focused_node_details.h"
Danyao Wanga78f3dd22020-03-05 05:31:27119#include "content/public/browser/global_routing_id.h"
[email protected]d9083482012-01-06 00:38:46120#include "content/public/browser/invalidate_type.h"
[email protected]71a88bb2013-02-01 22:05:15121#include "content/public/browser/javascript_dialog_manager.h"
skyf65d9bb2017-03-24 02:26:39122#include "content/public/browser/keyboard_event_processing_result.h"
[email protected]09d31d52012-03-11 22:30:27123#include "content/public/browser/load_notification_details.h"
[email protected]5b96836f2011-12-22 07:39:00124#include "content/public/browser/navigation_details.h"
[email protected]375fa1b2012-05-22 22:05:37125#include "content/public/browser/notification_details.h"
[email protected]be2510c02012-05-28 14:52:14126#include "content/public/browser/notification_service.h"
scottmg011d96e32016-06-29 19:15:08127#include "content/public/browser/notification_types.h"
[email protected]95640212014-07-26 18:14:30128#include "content/public/browser/render_widget_host_iterator.h"
Lukasz Anforowicze1b954d92017-10-30 21:28:06129#include "content/public/browser/restore_type.h"
estark5ea80e52015-06-19 18:43:12130#include "content/public/browser/security_style_explanations.h"
falken52a56e32016-12-08 05:02:40131#include "content/public/browser/ssl_status.h"
[email protected]4c3a23582012-08-18 08:54:34132#include "content/public/browser/storage_partition.h"
[email protected]674bc592011-12-20 23:00:42133#include "content/public/browser/web_contents_delegate.h"
Julie Jeongeun Kim7d0986172019-12-04 03:17:25134#include "content/public/browser/web_contents_receiver_set.h"
Lei Zhangee3b63ad2018-06-06 23:25:31135#include "content/public/browser/web_ui_controller.h"
[email protected]e091df82011-10-11 18:13:21136#include "content/public/common/bindings_policy.h"
alexmosc9e76ec2016-05-16 22:59:37137#include "content/public/common/child_process_host.h"
Hans Wennborg5ffd1392019-10-16 11:00:02138#include "content/public/common/content_client.h"
[email protected]54087fe2011-10-28 22:02:48139#include "content/public/common/content_constants.h"
Francois Doray3f2afbd2018-04-06 19:18:18140#include "content/public/common/content_features.h"
[email protected]64d69de42012-02-06 00:19:54141#include "content/public/common/content_switches.h"
Lukasz Anforowicze1b954d92017-10-30 21:28:06142#include "content/public/common/page_state.h"
Leon Han963dc182018-11-06 05:41:48143#include "content/public/common/referrer_type_converters.h"
[email protected]04cbd3d2013-12-04 04:58:20144#include "content/public/common/result_codes.h"
[email protected]f16cc6782013-12-16 23:42:57145#include "content/public/common/url_utils.h"
danakjffc8baf2019-10-10 23:49:42146#include "content/public/common/use_zoom_for_dsf_policy.h"
[email protected]b3a97b52014-07-09 06:25:05147#include "content/public/common/web_preferences.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20148#include "media/base/media_switches.h"
Max Morinddebb972018-09-20 10:04:14149#include "media/base/user_input_monitor.h"
wjmaclean64951902016-04-29 20:59:12150#include "net/base/url_util.h"
[email protected]8bfc8272013-09-09 20:10:53151#include "net/http/http_cache.h"
152#include "net/http/http_transaction_factory.h"
David Van Clevef99881632020-07-16 19:41:13153#include "net/http/http_util.h"
rhalavati0fbaeef32017-06-01 15:56:30154#include "net/traffic_annotation/network_traffic_annotation.h"
Scott Violet02e38b92018-03-27 23:42:14155#include "ppapi/buildflags/buildflags.h"
Mounir Lamourifd9dcefa2017-07-06 10:26:55156#include "services/metrics/public/cpp/ukm_recorder.h"
John Abd-El-Malekb175a612018-12-03 20:11:58157#include "services/network/public/cpp/features.h"
arthursonzognib93a4472020-04-10 07:38:00158#include "services/network/public/cpp/web_sandbox_flags.h"
159#include "services/network/public/mojom/web_sandbox_flags.mojom.h"
rockot734fb662016-10-15 16:41:30160#include "services/service_manager/public/cpp/interface_provider.h"
Becca Hughes6daf5662018-06-27 16:50:54161#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
Blink Reformata30d4232018-04-07 15:31:06162#include "third_party/blink/public/common/mime_util/mime_util.h"
danakj938b37a62019-09-24 18:35:54163#include "third_party/blink/public/common/page/page_zoom.h"
Sergio Villar Senin9d9d4f52019-10-15 10:57:57164#include "third_party/blink/public/common/security/security_style.h"
Abhijeet Kandalkarde7348e2020-01-13 06:06:54165#include "third_party/blink/public/mojom/frame/frame.mojom.h"
Dave Tapuskaa4189512019-10-15 20:27:34166#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
Takuto Ikutaaa3b796c2019-02-06 02:54:56167#include "third_party/blink/public/mojom/loader/pause_subresource_loading_handle.mojom.h"
Antonio Gomes0d42960a2019-06-05 12:35:51168#include "third_party/blink/public/mojom/mediastream/media_stream.mojom-shared.h"
halton.huoca2eabd2015-07-06 08:17:40169#include "third_party/skia/include/core/SkBitmap.h"
dmazzonid95ae842016-04-12 21:17:39170#include "ui/accessibility/ax_tree_combiner.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20171#include "ui/base/device_form_factor.h"
Mugdha Lakhani0a0d7862020-07-29 09:58:45172#if defined(USE_AURA)
173#include "ui/aura/window.h"
174#endif
[email protected]a08412b62012-05-29 21:28:56175#include "ui/base/layout.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20176#include "ui/base/ui_base_features.h"
177#include "ui/base/ui_base_switches.h"
178#include "ui/display/screen.h"
Daniel Cheng90196c82018-04-25 21:49:14179#include "ui/events/base_event_utils.h"
chongz4a9751942016-08-17 17:49:39180#include "ui/events/blink/web_input_event_traits.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20181#include "ui/gfx/animation/animation.h"
[email protected]66bd5512012-08-01 02:02:52182#include "ui/gl/gl_switches.h"
[email protected]3c733bde2010-12-21 19:56:31183
ekaramada110f642016-12-21 19:47:28184#if defined(OS_WIN)
185#include "content/browser/renderer_host/dip_util.h"
186#include "ui/gfx/geometry/dip_util.h"
187#endif
188
[email protected]583418cc2013-01-17 14:01:10189#if defined(OS_ANDROID)
mfomitchev2b8b066a2016-01-28 19:23:15190#include "content/browser/android/date_time_chooser_android.h"
sammcf5f1b0f2016-09-20 23:05:11191#include "content/browser/android/java_interfaces_impl.h"
Leon Hanccb985f2019-08-26 02:43:24192#include "content/browser/android/nfc_host.h"
[email protected]155c7f22013-12-09 17:07:18193#include "content/browser/web_contents/web_contents_android.h"
Ke He31d0bb02018-02-24 07:16:24194#include "services/device/public/mojom/nfc.mojom.h"
Mugdha Lakhani0a0d7862020-07-29 09:58:45195#include "ui/android/view_android.h"
mcnee336ea2c2017-05-23 22:50:59196#else // !OS_ANDROID
197#include "content/browser/host_zoom_map_impl.h"
mfomitchev2b8b066a2016-01-28 19:23:15198#endif // OS_ANDROID
[email protected]583418cc2013-01-17 14:01:10199
brettw4b461082016-11-19 18:55:16200#if BUILDFLAG(ENABLE_PLUGINS)
zqzhang181047e62016-07-01 13:37:17201#include "content/browser/media/session/pepper_playback_observer.h"
Lei Zhangebcc6302018-01-12 19:46:45202#endif
zqzhang181047e62016-07-01 13:37:17203
[email protected]8ff00d72012-10-23 19:12:21204namespace content {
Abigail Kleinaa898742019-11-01 02:31:25205
206using AccessibilityEventCallback =
207 base::RepeatingCallback<void(const std::string&)>;
208
[email protected]420ae012009-04-24 05:16:32209namespace {
210
[email protected]960b0372014-05-19 18:01:00211const int kMinimumDelayBetweenLoadingUpdatesMS = 100;
[email protected]82114f52012-03-20 22:53:41212const char kDotGoogleDotCom[] = ".google.com";
[email protected]ca406032011-07-19 21:53:05213
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:50214using LifecycleState = RenderFrameHostImpl::LifecycleState;
215
Alexander Timin33bd754c02020-03-10 22:50:18216// TODO(crbug.com/1059903): Clean up after the initial investigation.
217constexpr base::Feature kCheckWebContentsAccessFromNonCurrentFrame{
218 "CheckWebContentsAccessFromNonCurrentFrame",
219 base::FEATURE_DISABLED_BY_DEFAULT};
220
Avi Drissmana9114822018-03-23 18:25:55221base::LazyInstance<std::vector<
222 WebContentsImpl::FriendWrapper::CreatedCallback>>::DestructorAtExit
223 g_created_callbacks = LAZY_INSTANCE_INITIALIZER;
[email protected]cbb1ef592013-06-05 19:49:46224
dcheng57e39e22016-01-21 00:25:38225bool HasMatchingProcess(FrameTree* tree, int render_process_id) {
226 for (FrameTreeNode* node : tree->Nodes()) {
227 if (node->current_frame_host()->GetProcess()->GetID() == render_process_id)
228 return true;
alexmos4cf2aa32015-07-15 23:40:43229 }
dcheng57e39e22016-01-21 00:25:38230 return false;
[email protected]95640212014-07-26 18:14:30231}
232
kenrb19221852016-04-29 17:21:40233bool HasMatchingWidgetHost(FrameTree* tree, RenderWidgetHost* host) {
234 // This method scans the frame tree rather than checking whether
235 // host->delegate() == this, which allows it to return false when the host
236 // for a frame that is pending or pending deletion.
237 if (!host)
238 return false;
239
240 for (FrameTreeNode* node : tree->Nodes()) {
241 if (node->current_frame_host()->GetRenderWidgetHost() == host)
242 return true;
243 }
244 return false;
245}
246
dmazzonif8a31042016-12-03 00:52:13247void UpdateAccessibilityModeOnFrame(RenderFrameHost* frame_host) {
248 static_cast<RenderFrameHostImpl*>(frame_host)->UpdateAccessibilityMode();
[email protected]95640212014-07-26 18:14:30249}
250
dtseng0dd3fa12015-07-22 19:00:52251void ResetAccessibility(RenderFrameHost* rfh) {
252 static_cast<RenderFrameHostImpl*>(rfh)->AccessibilityReset();
253}
254
Ian Clelland5cbaaf82017-11-27 22:00:03255RenderFrameHostImpl* FindOpenerRFH(const WebContents::CreateParams& params) {
256 RenderFrameHostImpl* opener_rfh = nullptr;
alexmose201c7cd2015-06-10 17:14:21257 if (params.opener_render_frame_id != MSG_ROUTING_NONE) {
Ian Clelland5cbaaf82017-11-27 22:00:03258 opener_rfh = RenderFrameHostImpl::FromID(params.opener_render_process_id,
259 params.opener_render_frame_id);
alexmose201c7cd2015-06-10 17:14:21260 }
Ian Clelland5cbaaf82017-11-27 22:00:03261 return opener_rfh;
lukasza6f8ac622017-06-06 03:10:20262}
263
Dominick Ng37a15052018-07-17 23:56:35264// Returns |true| if |type| is the kind of user input that should trigger the
265// user interaction observers.
266bool IsUserInteractionInputType(blink::WebInputEvent::Type type) {
267 // Ideally, this list would be based more off of
268 // https://whatwg.org/C/interaction.html#triggered-by-user-activation.
Dave Tapuska347d60a2020-04-21 23:55:47269 return type == blink::WebInputEvent::Type::kMouseDown ||
270 type == blink::WebInputEvent::Type::kGestureScrollBegin ||
271 type == blink::WebInputEvent::Type::kTouchStart ||
272 type == blink::WebInputEvent::Type::kRawKeyDown;
Dominick Ng37a15052018-07-17 23:56:35273}
274
Pavel Feldman3c1842b2017-08-02 05:00:16275// Ensures that OnDialogClosed is only called once.
276class CloseDialogCallbackWrapper
277 : public base::RefCountedThreadSafe<CloseDialogCallbackWrapper> {
278 public:
Avi Drissmane04d3992017-10-05 15:11:36279 using CloseCallback =
280 base::OnceCallback<void(bool, bool, const base::string16&)>;
281
282 explicit CloseDialogCallbackWrapper(CloseCallback callback)
283 : callback_(std::move(callback)) {}
Pavel Feldman3c1842b2017-08-02 05:00:16284
285 void Run(bool dialog_was_suppressed,
286 bool success,
287 const base::string16& user_input) {
Avi Drissmane04d3992017-10-05 15:11:36288 if (callback_.is_null())
Pavel Feldman3c1842b2017-08-02 05:00:16289 return;
Avi Drissmane04d3992017-10-05 15:11:36290 std::move(callback_).Run(dialog_was_suppressed, success, user_input);
Pavel Feldman3c1842b2017-08-02 05:00:16291 }
292
293 private:
294 friend class base::RefCountedThreadSafe<CloseDialogCallbackWrapper>;
295 ~CloseDialogCallbackWrapper() {}
Avi Drissmane04d3992017-10-05 15:11:36296
297 CloseCallback callback_;
Pavel Feldman3c1842b2017-08-02 05:00:16298};
299
Arthur Sonzogni929d29f2018-09-17 14:19:44300bool FrameCompareDepth(RenderFrameHostImpl* a, RenderFrameHostImpl* b) {
301 return a->frame_tree_node()->depth() < b->frame_tree_node()->depth();
302}
303
Raymes Khoury58373df2019-08-06 06:29:20304bool AreValidRegisterProtocolHandlerArguments(const std::string& protocol,
305 const GURL& url,
306 const url::Origin& origin) {
307 ChildProcessSecurityPolicyImpl* policy =
308 ChildProcessSecurityPolicyImpl::GetInstance();
309 if (policy->IsPseudoScheme(protocol))
310 return false;
311
312 url::Origin url_origin = url::Origin::Create(url);
313 if (url_origin.opaque())
314 return false;
315
316 if (!url_origin.IsSameOriginWith(origin))
317 return false;
318
319 return true;
320}
321
yilkal796e89e2019-10-02 23:58:28322void RecordMaxFrameCountUMA(size_t max_frame_count) {
323 UMA_HISTOGRAM_COUNTS_10000("Navigation.MainFrame.MaxFrameCount",
324 max_frame_count);
325}
326
Jeremy Roman03ce13ce2020-05-29 22:16:57327// Returns whether the condition provided applies to any inner contents.
328// This check is not recursive (however, the predicate provided may itself
329// recurse each contents' own inner contents).
330//
331// For example, if this is used to aggregate state from inner contents to outer
332// contents, then that propagation will gather transitive descendants without
333// need for this helper to do so. In fact, in such cases recursing on inner
334// contents here would make that operation quadratic rather than linear.
335template <typename Functor>
336bool AnyInnerWebContents(WebContents* web_contents, const Functor& f) {
337 const auto& inner_contents = web_contents->GetInnerWebContents();
338 return std::any_of(inner_contents.begin(), inner_contents.end(), f);
339}
340
Xuehui Xieb2300ae42020-06-09 20:25:05341std::vector<RenderFrameHost*> GetAllFramesImpl(FrameTree& frame_tree,
342 bool include_pending) {
343 std::vector<RenderFrameHost*> frame_hosts;
344 for (FrameTreeNode* node : frame_tree.Nodes()) {
345 frame_hosts.push_back(node->current_frame_host());
346 if (include_pending) {
347 RenderFrameHostImpl* pending_frame_host =
348 node->render_manager()->speculative_frame_host();
349 if (pending_frame_host)
350 frame_hosts.push_back(pending_frame_host);
351 }
352 }
353 return frame_hosts;
354}
355
356int SendToAllFramesImpl(FrameTree& frame_tree,
357 bool include_pending,
358 IPC::Message* message) {
359 int number_of_messages = 0;
360 std::vector<RenderFrameHost*> frame_hosts =
361 GetAllFramesImpl(frame_tree, include_pending);
362 for (RenderFrameHost* rfh : frame_hosts) {
363 if (!rfh->IsRenderFrameLive())
364 continue;
365
366 ++number_of_messages;
367 IPC::Message* message_copy = new IPC::Message(*message);
368 message_copy->set_routing_id(rfh->GetRoutingID());
369 rfh->Send(message_copy);
370 }
371 delete message;
372 return number_of_messages;
373}
374
Avi Drissman33972942020-06-19 14:16:01375// Returns the set of all WebContentses that are reachable from |web_contents|
376// by applying some combination of WebContents::GetOriginalOpener() and
377// WebContents::GetOuterWebContents(). The |web_contents| parameter will be
378// included in the returned set.
379base::flat_set<WebContentsImpl*> GetAllOpeningWebContents(
380 WebContentsImpl* web_contents) {
381 base::flat_set<WebContentsImpl*> result;
382 base::flat_set<WebContentsImpl*> current;
383
384 current.insert(web_contents);
385
386 while (!current.empty()) {
387 WebContentsImpl* current_contents = *current.begin();
388 current.erase(current.begin());
389 auto insert_result = result.insert(current_contents);
390
391 if (insert_result.second) {
392 RenderFrameHostImpl* opener_rfh = current_contents->GetOriginalOpener();
393 if (opener_rfh) {
394 current.insert(static_cast<WebContentsImpl*>(
395 WebContents::FromRenderFrameHost(opener_rfh)));
396 }
397
398 WebContentsImpl* outer_contents = current_contents->GetOuterWebContents();
399 if (outer_contents)
400 current.insert(outer_contents);
401 }
402 }
403
404 return result;
405}
406
Rakina Zata Amni4029b6d2020-07-28 02:36:20407#if defined(OS_ANDROID)
408float GetDeviceScaleAdjustment(int min_width) {
409 static const float kMinFSM = 1.05f;
410 static const int kWidthForMinFSM = 320;
411 static const float kMaxFSM = 1.3f;
412 static const int kWidthForMaxFSM = 800;
413
414 if (min_width <= kWidthForMinFSM)
415 return kMinFSM;
416 if (min_width >= kWidthForMaxFSM)
417 return kMaxFSM;
418
419 // The font scale multiplier varies linearly between kMinFSM and kMaxFSM.
420 float ratio = static_cast<float>(min_width - kWidthForMinFSM) /
421 (kWidthForMaxFSM - kWidthForMinFSM);
422 return ratio * (kMaxFSM - kMinFSM) + kMinFSM;
423}
424#endif
425
Avi Drissman33972942020-06-19 14:16:01426// Used to attach the "set of fullscreen contents" to a browser context. Storing
427// sets of WebContents on their browser context is done for two reasons. One,
428// related WebContentses must necessarily share a browser context, so this saves
429// lookup time by restricting to one specific browser context. Two, separating
430// by browser context is preemptive paranoia about keeping things separate.
431class FullscreenContentsHolder : public base::SupportsUserData::Data {
432 public:
433 FullscreenContentsHolder() = default;
434 ~FullscreenContentsHolder() override = default;
435
436 FullscreenContentsHolder(const FullscreenContentsHolder&) = delete;
437 FullscreenContentsHolder& operator=(const FullscreenContentsHolder&) = delete;
438
439 base::flat_set<WebContentsImpl*>* set() { return &set_; }
440
441 private:
442 base::flat_set<WebContentsImpl*> set_;
443};
444
445const char kFullscreenContentsSet[] = "fullscreen-contents";
446
447base::flat_set<WebContentsImpl*>* FullscreenContentsSet(
448 BrowserContext* browser_context) {
449 auto* set_holder = static_cast<FullscreenContentsHolder*>(
450 browser_context->GetUserData(kFullscreenContentsSet));
451 if (!set_holder) {
452 auto new_holder = std::make_unique<FullscreenContentsHolder>();
453 set_holder = new_holder.get();
454 browser_context->SetUserData(kFullscreenContentsSet, std::move(new_holder));
455 }
456
457 return set_holder->set();
458}
459
lukasza6f8ac622017-06-06 03:10:20460} // namespace
461
Joel Hockey8c2011b22020-04-30 05:07:19462CreatedWindow::CreatedWindow() = default;
463CreatedWindow::CreatedWindow(std::unique_ptr<WebContentsImpl> contents,
464 GURL target_url)
465 : contents(std::move(contents)), target_url(std::move(target_url)) {}
466CreatedWindow::~CreatedWindow() = default;
467CreatedWindow::CreatedWindow(CreatedWindow&&) = default;
468CreatedWindow& CreatedWindow::operator=(CreatedWindow&&) = default;
469
Erik Chenbb8e738e2018-04-28 14:10:43470std::unique_ptr<WebContents> WebContents::Create(
471 const WebContents::CreateParams& params) {
Albert J. Wong65fe64d2019-09-20 02:48:14472 return WebContentsImpl::Create(params);
473}
474
475std::unique_ptr<WebContentsImpl> WebContentsImpl::Create(
476 const CreateParams& params) {
477 return CreateWithOpener(params, FindOpenerRFH(params));
[email protected]d1198fd2012-08-13 22:50:19478}
479
erikchenade1fef2018-05-02 22:07:57480std::unique_ptr<WebContents> WebContents::CreateWithSessionStorage(
[email protected]54944cde2012-12-09 09:24:59481 const WebContents::CreateParams& params,
[email protected]fdac6ade2013-07-20 01:06:30482 const SessionStorageNamespaceMap& session_storage_namespace_map) {
erikchenade1fef2018-05-02 22:07:57483 std::unique_ptr<WebContentsImpl> new_contents(
484 new WebContentsImpl(params.browser_context));
Ian Clelland5cbaaf82017-11-27 22:00:03485 RenderFrameHostImpl* opener_rfh = FindOpenerRFH(params);
486 FrameTreeNode* opener = nullptr;
487 if (opener_rfh)
488 opener = opener_rfh->frame_tree_node();
489 new_contents->SetOpenerForNewContents(opener, params.opener_suppressed);
[email protected]fdac6ade2013-07-20 01:06:30490
jdoerrie55ec69d2018-10-08 13:34:46491 for (auto it = session_storage_namespace_map.begin();
492 it != session_storage_namespace_map.end(); ++it) {
Fergal Daly09d6c762020-05-29 02:05:18493 new_contents->GetController().SetSessionStorageNamespace(it->first,
494 it->second.get());
[email protected]fdac6ade2013-07-20 01:06:30495 }
496
Sean Toppingbbc4a2bd2019-01-30 02:16:14497 WebContentsImpl* outer_web_contents = nullptr;
Sam McNally69a33772018-06-27 16:54:12498 if (params.guest_delegate) {
499 // This makes |new_contents| act as a guest.
500 // For more info, see comment above class BrowserPluginGuest.
Albert J. Wongc55cc64d2018-10-12 02:50:04501 BrowserPluginGuest::CreateInWebContents(new_contents.get(),
502 params.guest_delegate);
Sean Toppingbbc4a2bd2019-01-30 02:16:14503 outer_web_contents = static_cast<WebContentsImpl*>(
504 params.guest_delegate->GetOwnerWebContents());
Sam McNally69a33772018-06-27 16:54:12505 }
506
[email protected]54944cde2012-12-09 09:24:59507 new_contents->Init(params);
Sean Toppingbbc4a2bd2019-01-30 02:16:14508 if (outer_web_contents)
509 outer_web_contents->InnerWebContentsCreated(new_contents.get());
[email protected]d1198fd2012-08-13 22:50:19510 return new_contents;
[email protected]a81343d232011-12-27 07:39:20511}
[email protected]746d3052012-05-22 15:15:47512
benwells5e7260d2017-03-20 23:36:33513void WebContentsImpl::FriendWrapper::AddCreatedCallbackForTesting(
nickf9acfbe2014-12-23 19:12:37514 const CreatedCallback& callback) {
[email protected]cbb1ef592013-06-05 19:49:46515 g_created_callbacks.Get().push_back(callback);
516}
517
benwells5e7260d2017-03-20 23:36:33518void WebContentsImpl::FriendWrapper::RemoveCreatedCallbackForTesting(
nickf9acfbe2014-12-23 19:12:37519 const CreatedCallback& callback) {
[email protected]cbb1ef592013-06-05 19:49:46520 for (size_t i = 0; i < g_created_callbacks.Get().size(); ++i) {
Robert Liao1db5a352019-06-05 20:57:34521 if (g_created_callbacks.Get().at(i) == callback) {
[email protected]cbb1ef592013-06-05 19:49:46522 g_created_callbacks.Get().erase(g_created_callbacks.Get().begin() + i);
523 return;
524 }
525 }
526}
527
avidf38c952015-10-27 13:45:13528WebContents* WebContents::FromRenderViewHost(RenderViewHost* rvh) {
529 if (!rvh)
530 return nullptr;
[email protected]746d3052012-05-22 15:15:47531 return rvh->GetDelegate()->GetAsWebContents();
532}
533
[email protected]a86c0e962013-12-17 17:10:39534WebContents* WebContents::FromRenderFrameHost(RenderFrameHost* rfh) {
avidf38c952015-10-27 13:45:13535 if (!rfh)
536 return nullptr;
Alexander Timin33bd754c02020-03-10 22:50:18537 if (!rfh->IsCurrent() && base::FeatureList::IsEnabled(
538 kCheckWebContentsAccessFromNonCurrentFrame)) {
539 // TODO(crbug.com/1059903): return nullptr here eventually.
540 base::debug::DumpWithoutCrashing();
541 }
avidf38c952015-10-27 13:45:13542 return static_cast<RenderFrameHostImpl*>(rfh)->delegate()->GetAsWebContents();
[email protected]a86c0e962013-12-17 17:10:39543}
544
ananta4b7467a52016-09-23 01:42:38545WebContents* WebContents::FromFrameTreeNodeId(int frame_tree_node_id) {
546 FrameTreeNode* frame_tree_node =
547 FrameTreeNode::GloballyFindByID(frame_tree_node_id);
anantab8cfa3b2016-10-14 22:43:19548 if (!frame_tree_node)
549 return nullptr;
jam8c4edd02017-05-06 18:50:33550 return WebContentsImpl::FromFrameTreeNode(frame_tree_node);
ananta4b7467a52016-09-23 01:42:38551}
552
leon.han552e9de2017-02-09 14:37:30553void WebContents::SetScreenOrientationDelegate(
554 ScreenOrientationDelegate* delegate) {
555 ScreenOrientationProvider::SetDelegate(delegate);
556}
557
[email protected]7fff43e2013-05-21 20:21:10558// WebContentsImpl::DestructionObserver ----------------------------------------
559
560class WebContentsImpl::DestructionObserver : public WebContentsObserver {
561 public:
562 DestructionObserver(WebContentsImpl* owner, WebContents* watched_contents)
Fergal Daly09d6c762020-05-29 02:05:18563 : WebContentsObserver(watched_contents), owner_(owner) {}
[email protected]7fff43e2013-05-21 20:21:10564
565 // WebContentsObserver:
dchengc2282aa2014-10-21 12:07:58566 void WebContentsDestroyed() override {
[email protected]12a46832014-05-09 13:35:58567 owner_->OnWebContentsDestroyed(
568 static_cast<WebContentsImpl*>(web_contents()));
[email protected]7fff43e2013-05-21 20:21:10569 }
570
571 private:
572 WebContentsImpl* owner_;
573
574 DISALLOW_COPY_AND_ASSIGN(DestructionObserver);
575};
576
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:50577// TODO(sreejakshetty): Make |WebContentsImpl::ColorChooser| per-frame instead
578// of WebContents-owned.
Joel Hockey85b379d2017-12-11 10:42:13579// WebContentsImpl::ColorChooser ----------------------------------------------
Joel Hockey163835a2017-12-20 11:51:57580class WebContentsImpl::ColorChooser : public blink::mojom::ColorChooser {
Joel Hockey85b379d2017-12-11 10:42:13581 public:
582 ColorChooser(content::ColorChooser* chooser,
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20583 mojo::PendingReceiver<blink::mojom::ColorChooser> receiver,
584 mojo::PendingRemote<blink::mojom::ColorChooserClient> client)
Joel Hockey85b379d2017-12-11 10:42:13585 : chooser_(chooser),
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20586 receiver_(this, std::move(receiver)),
Joel Hockey85b379d2017-12-11 10:42:13587 client_(std::move(client)) {
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20588 receiver_.set_disconnect_handler(
Joel Hockey85b379d2017-12-11 10:42:13589 base::BindOnce([](content::ColorChooser* chooser) { chooser->End(); },
590 base::Unretained(chooser)));
591 }
[email protected]8ed16472014-04-11 19:02:48592
Joel Hockey85b379d2017-12-11 10:42:13593 ~ColorChooser() override { chooser_->End(); }
[email protected]8ed16472014-04-11 19:02:48594
Joel Hockey85b379d2017-12-11 10:42:13595 void SetSelectedColor(SkColor color) override {
596 chooser_->SetSelectedColor(color);
597 }
598
599 void DidChooseColorInColorChooser(SkColor color) {
600 client_->DidChooseColor(color);
601 }
602
603 private:
604 // Color chooser that was opened by this tab.
605 std::unique_ptr<content::ColorChooser> chooser_;
606
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20607 // mojo receiver.
608 mojo::Receiver<blink::mojom::ColorChooser> receiver_;
Joel Hockey85b379d2017-12-11 10:42:13609
610 // mojo renderer client.
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20611 mojo::Remote<blink::mojom::ColorChooserClient> client_;
Joel Hockey85b379d2017-12-11 10:42:13612};
nicka0ac8382016-12-15 23:59:23613
lazyboy6ec48b2a2015-06-29 15:18:14614// WebContentsImpl::WebContentsTreeNode ----------------------------------------
lfg601233692017-03-06 22:45:44615WebContentsImpl::WebContentsTreeNode::WebContentsTreeNode(
616 WebContentsImpl* current_web_contents)
617 : current_web_contents_(current_web_contents),
618 outer_web_contents_(nullptr),
lazyboy6ec48b2a2015-06-29 15:18:14619 outer_contents_frame_tree_node_id_(
avallee0206f782016-07-28 18:55:33620 FrameTreeNode::kFrameTreeNodeInvalidId),
lfg601233692017-03-06 22:45:44621 focused_web_contents_(current_web_contents) {}
lazyboy6ec48b2a2015-06-29 15:18:14622
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18623WebContentsImpl::WebContentsTreeNode::~WebContentsTreeNode() {}
lazyboy6ec48b2a2015-06-29 15:18:14624
Lucas Furukawa Gadani99125822019-01-03 15:41:49625std::unique_ptr<WebContents>
626WebContentsImpl::WebContentsTreeNode::DisconnectFromOuterWebContents() {
627 std::unique_ptr<WebContents> inner_contents =
628 outer_web_contents_->node_.DetachInnerWebContents(current_web_contents_);
629 OuterContentsFrameTreeNode()->RemoveObserver(this);
630 outer_contents_frame_tree_node_id_ = FrameTreeNode::kFrameTreeNodeInvalidId;
631 outer_web_contents_ = nullptr;
632 return inner_contents;
633}
634
paulmeyerfeafc2d2017-04-25 21:46:40635void WebContentsImpl::WebContentsTreeNode::AttachInnerWebContents(
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:50636 std::unique_ptr<WebContents> inner_web_contents,
637 RenderFrameHostImpl* render_frame_host) {
638 WebContentsImpl* inner_web_contents_impl =
639 static_cast<WebContentsImpl*>(inner_web_contents.get());
640 WebContentsTreeNode& inner_web_contents_node = inner_web_contents_impl->node_;
641
642 inner_web_contents_node.focused_web_contents_ = nullptr;
643 inner_web_contents_node.outer_web_contents_ = current_web_contents_;
644 inner_web_contents_node.outer_contents_frame_tree_node_id_ =
645 render_frame_host->frame_tree_node()->frame_tree_node_id();
646
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18647 inner_web_contents_.push_back(std::move(inner_web_contents));
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:50648
649 render_frame_host->frame_tree_node()->AddObserver(&inner_web_contents_node);
Jeremy Roman03ce13ce2020-05-29 22:16:57650 current_web_contents_->InnerWebContentsAttached(inner_web_contents_impl);
paulmeyerfeafc2d2017-04-25 21:46:40651}
652
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18653std::unique_ptr<WebContents>
654WebContentsImpl::WebContentsTreeNode::DetachInnerWebContents(
paulmeyerfeafc2d2017-04-25 21:46:40655 WebContentsImpl* inner_web_contents) {
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18656 std::unique_ptr<WebContents> detached_contents;
657 for (std::unique_ptr<WebContents>& web_contents : inner_web_contents_) {
658 if (web_contents.get() == inner_web_contents) {
659 detached_contents = std::move(web_contents);
660 std::swap(web_contents, inner_web_contents_.back());
661 inner_web_contents_.pop_back();
Jeremy Roman03ce13ce2020-05-29 22:16:57662 current_web_contents_->InnerWebContentsDetached(inner_web_contents);
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18663 return detached_contents;
664 }
665 }
666
667 NOTREACHED();
668 return nullptr;
paulmeyerfeafc2d2017-04-25 21:46:40669}
670
lfga3e2bdc2017-03-07 20:44:01671FrameTreeNode*
672WebContentsImpl::WebContentsTreeNode::OuterContentsFrameTreeNode() const {
673 return FrameTreeNode::GloballyFindByID(outer_contents_frame_tree_node_id_);
lfg601233692017-03-06 22:45:44674}
675
lfga3e2bdc2017-03-07 20:44:01676void WebContentsImpl::WebContentsTreeNode::OnFrameTreeNodeDestroyed(
677 FrameTreeNode* node) {
678 DCHECK_EQ(outer_contents_frame_tree_node_id_, node->frame_tree_node_id())
679 << "WebContentsTreeNode should only receive notifications for the "
680 "FrameTreeNode in its outer WebContents that hosts it.";
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18681
682 // Deletes |this| too.
683 outer_web_contents_->node_.DetachInnerWebContents(current_web_contents_);
lazyboy6ec48b2a2015-06-29 15:18:14684}
685
avallee0206f782016-07-28 18:55:33686void WebContentsImpl::WebContentsTreeNode::SetFocusedWebContents(
687 WebContentsImpl* web_contents) {
688 DCHECK(!outer_web_contents())
689 << "Only the outermost WebContents tracks focus.";
690 focused_web_contents_ = web_contents;
691}
692
paulmeyerfeafc2d2017-04-25 21:46:40693WebContentsImpl*
694WebContentsImpl::WebContentsTreeNode::GetInnerWebContentsInFrame(
695 const FrameTreeNode* frame) {
696 auto ftn_id = frame->frame_tree_node_id();
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18697 for (auto& contents : inner_web_contents_) {
698 WebContentsImpl* impl = static_cast<WebContentsImpl*>(contents.get());
699 if (impl->node_.outer_contents_frame_tree_node_id() == ftn_id) {
700 return impl;
paulmeyerfeafc2d2017-04-25 21:46:40701 }
702 }
703 return nullptr;
704}
705
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18706std::vector<WebContentsImpl*>
707WebContentsImpl::WebContentsTreeNode::GetInnerWebContents() const {
708 std::vector<WebContentsImpl*> inner_web_contents;
709 for (auto& contents : inner_web_contents_)
710 inner_web_contents.push_back(static_cast<WebContentsImpl*>(contents.get()));
711
712 return inner_web_contents;
paulmeyerfeafc2d2017-04-25 21:46:40713}
714
Alexander Timin90c20c32020-08-12 15:28:32715// WebContentsObserverList -----------------------------------------------------
716WebContentsImpl::WebContentsObserverList::WebContentsObserverList() = default;
717WebContentsImpl::WebContentsObserverList::~WebContentsObserverList() = default;
718
719void WebContentsImpl::WebContentsObserverList::AddObserver(
720 WebContentsObserver* observer) {
721 observers_.AddObserver(observer);
722}
723
724void WebContentsImpl::WebContentsObserverList::RemoveObserver(
725 WebContentsObserver* observer) {
726 observers_.RemoveObserver(observer);
727}
728
[email protected]b172aee2012-04-10 17:05:26729// WebContentsImpl -------------------------------------------------------------
[email protected]420ae012009-04-24 05:16:32730
alexmose201c7cd2015-06-10 17:14:21731WebContentsImpl::WebContentsImpl(BrowserContext* browser_context)
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28732 : delegate_(nullptr),
[email protected]69e797f2013-04-30 01:10:22733 controller_(this, browser_context),
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28734 render_view_host_delegate_view_(nullptr),
alexmose201c7cd2015-06-10 17:14:21735 created_with_opener_(false),
Lucas Furukawa Gadani99125822019-01-03 15:41:49736 node_(this),
Fergal Daly09d6c762020-05-29 02:05:18737 frame_tree_(&controller_, this, this, this, this, this),
[email protected]6dfed692014-05-22 04:18:03738 is_load_to_different_document_(false),
[email protected]443b80e2010-12-14 00:42:23739 crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING),
740 crashed_error_code_(0),
[email protected]d5f942ba2008-09-26 19:30:34741 waiting_for_response_(false),
[email protected]fcf75d42013-12-03 20:11:26742 load_state_(net::LOAD_STATE_IDLE, base::string16()),
[email protected]094e5b22009-09-25 04:23:56743 upload_size_(0),
744 upload_position_(0),
dfalcantarae6b7b46752015-07-10 18:14:16745 is_resume_pending_(false),
[email protected]b4c84012014-04-28 19:51:10746 has_accessed_initial_document_(false),
Collin Bakerc5259962019-11-14 17:51:58747 visible_capturer_count_(0),
748 hidden_capturer_count_(0),
[email protected]fdd61c62009-04-22 19:22:57749 is_being_destroyed_(false),
[email protected]fdd61c62009-04-22 19:22:57750 notify_disconnection_(false),
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28751 dialog_manager_(nullptr),
[email protected]7ab1e7d62009-10-14 23:32:01752 is_showing_before_unload_dialog_(false),
gab0dccfef2015-05-20 18:43:39753 last_active_time_(base::TimeTicks::Now()),
[email protected]ebf40a72010-07-22 01:46:38754 closed_by_user_gesture_(false),
danakj938b37a62019-09-24 18:35:54755 minimum_zoom_percent_(
756 static_cast<int>(blink::kMinimumPageZoomFactor * 100)),
757 maximum_zoom_percent_(
758 static_cast<int>(blink::kMaximumPageZoomFactor * 100)),
w.shackleton49bcd392016-01-06 17:38:22759 zoom_scroll_remainder_(0),
alexmosc9e76ec2016-05-16 22:59:37760 fullscreen_widget_process_id_(ChildProcessHost::kInvalidUniqueID),
[email protected]5dcaf8e2013-12-28 01:31:42761 fullscreen_widget_routing_id_(MSG_ROUTING_NONE),
[email protected]0b431992014-06-24 00:08:03762 fullscreen_widget_had_focus_at_shutdown_(false),
[email protected]34ff1cfc2014-08-20 06:16:05763 force_disable_overscroll_content_(false),
[email protected]95640212014-07-26 18:14:30764 last_dialog_suppressed_(false),
waffles1c12bf402016-02-10 17:45:48765 accessibility_mode_(
Dominic Mazzoni21fb0282019-02-13 18:32:47766 GetContentClient()->browser()->GetAXModeForBrowserContext(
767 browser_context)),
avayvodcc85bbd2015-08-28 19:11:15768 audio_stream_monitor_(this),
Thomas Guilbert882c4cec2019-02-14 05:55:45769 media_web_contents_observer_(
770 std::make_unique<MediaWebContentsObserver>(this)),
mcnee336ea2c2017-05-23 22:50:59771#if !defined(OS_ANDROID)
mcnee432e47d2015-11-09 19:37:46772 page_scale_factor_is_one_(true),
mcnee336ea2c2017-05-23 22:50:59773#endif // !defined(OS_ANDROID)
qinmin72e8bd02016-10-21 19:35:37774 is_overlay_content_(false),
ekaramadf6750aa2017-06-06 18:29:42775 showing_context_menu_(false),
W. James MacLean62198672019-06-04 16:46:10776 text_autosizer_page_info_({0, 0, 1.f}),
shivanigithubcceeacf2020-03-06 20:00:27777 native_theme_observer_(this) {
danakjf4b9e942019-11-29 15:43:04778 frame_tree_.SetFrameRemoveListener(base::BindRepeating(
779 &WebContentsImpl::OnFrameRemoved, base::Unretained(this)));
brettw4b461082016-11-19 18:55:16780#if BUILDFLAG(ENABLE_PLUGINS)
zqzhang181047e62016-07-01 13:37:17781 pepper_playback_observer_.reset(new PepperPlaybackObserver(this));
782#endif
blundelle75a8f92017-03-27 08:11:17783
Becca Hughes86334622018-07-09 21:29:38784#if defined(OS_ANDROID)
Elly Fong-Jonescdd7ae82019-02-20 23:26:33785 display_cutout_host_impl_ = std::make_unique<DisplayCutoutHostImpl>(this);
Becca Hughes86334622018-07-09 21:29:38786#endif
John Delaney732721e92020-02-07 23:11:27787
Alison Maher7f366dc62020-03-03 19:46:00788 ui::NativeTheme* native_theme = ui::NativeTheme::GetInstanceForWeb();
789 native_theme_observer_.Add(native_theme);
790 using_dark_colors_ = native_theme->ShouldUseDarkColors();
791 preferred_color_scheme_ = native_theme->GetPreferredColorScheme();
792
Mike Wassermanb213b9352020-04-16 00:32:34793 screen_change_monitor_ =
794 std::make_unique<ScreenChangeMonitor>(base::BindRepeating(
795 &WebContentsImpl::OnScreensChange, base::Unretained(this)));
796
John Delaney732721e92020-02-07 23:11:27797 // ConversionHost takes a weak ref on |this|, so it must be created outside of
798 // the initializer list.
Charlie Harrison405f6212020-04-14 21:57:32799 if (base::FeatureList::IsEnabled(features::kConversionMeasurement)) {
800 conversion_host_ = std::make_unique<ConversionHost>(this);
801 }
[email protected]332af7732009-03-11 13:21:35802}
initial.commit09911bf2008-07-26 23:55:29803
[email protected]b172aee2012-04-10 17:05:26804WebContentsImpl::~WebContentsImpl() {
creisba91ba82017-05-12 22:56:19805 // Imperfect sanity check against double free, given some crashes unexpectedly
806 // observed in the wild.
807 CHECK(!is_being_destroyed_);
808
809 // We generally keep track of is_being_destroyed_ to let other features know
810 // to avoid certain actions during destruction.
[email protected]420ae012009-04-24 05:16:32811 is_being_destroyed_ = true;
812
creis97867aa2017-02-17 18:39:45813 // A WebContents should never be deleted while it is notifying observers,
creisba91ba82017-05-12 22:56:19814 // since this will lead to a use-after-free as it continues to notify later
creis97867aa2017-02-17 18:39:45815 // observers.
Alexander Timin90c20c32020-08-12 15:28:32816 CHECK(!observers_.is_notifying_observers());
creis97867aa2017-02-17 18:39:45817
Avi Drissman33972942020-06-19 14:16:01818 FullscreenContentsSet(GetBrowserContext())->erase(this);
819
kenrb2a565f82015-09-02 20:24:59820 rwh_input_event_router_.reset();
821
Julie Jeongeun Kim7d0986172019-12-04 03:17:25822 for (auto& entry : receiver_sets_)
823 entry.second->CloseAllReceivers();
rockotf62002a2016-09-15 00:08:59824
avallee0206f782016-07-28 18:55:33825 WebContentsImpl* outermost = GetOutermostWebContents();
avallee9993fca2016-11-17 06:16:50826 if (this != outermost && ContainsOrIsFocusedWebContents()) {
avallee0206f782016-07-28 18:55:33827 // If the current WebContents is in focus, unset it.
avallee9993fca2016-11-17 06:16:50828 outermost->SetAsFocusedWebContentsIfNecessary();
avallee0206f782016-07-28 18:55:33829 }
830
Nick Carterd73635b2018-03-13 18:31:41831 if (mouse_lock_widget_)
James Hollyerd5c9de462020-03-10 19:02:45832 mouse_lock_widget_->RejectMouseLockOrUnlockIfNecessary(
833 blink::mojom::PointerLockResult::kElementDestroyed);
Nick Carterd73635b2018-03-13 18:31:41834
dcheng72be33c2016-01-21 04:11:31835 for (FrameTreeNode* node : frame_tree_.Nodes()) {
836 // Delete all RFHs pending shutdown, which will lead the corresponding RVHs
837 // to be shutdown and be deleted as well.
dcheng57e39e22016-01-21 00:25:38838 node->render_manager()->ClearRFHsPendingShutdown();
dcheng57e39e22016-01-21 00:25:38839 node->render_manager()->ClearWebUIInstances();
dcheng72be33c2016-01-21 04:11:31840 }
carlosk35f35af2015-12-01 10:55:40841
dcheng57e39e22016-01-21 00:25:38842 for (RenderWidgetHostImpl* widget : created_widgets_)
843 widget->DetachDelegate();
[email protected]b24b68a2012-09-24 21:57:26844 created_widgets_.clear();
845
[email protected]3ab9cb82011-06-03 18:02:07846 // Clear out any JavaScript state.
avi5d3b8692016-10-12 22:00:46847 if (dialog_manager_) {
avi6879fcf2017-01-21 05:27:53848 dialog_manager_->CancelDialogs(this, /*reset_state=*/true);
avi5d3b8692016-10-12 22:00:46849 }
[email protected]3ab9cb82011-06-03 18:02:07850
Joel Hockey85b379d2017-12-11 10:42:13851 color_chooser_.reset();
Rakina Zata Amni16196122018-11-14 02:14:00852 find_request_manager_.reset();
[email protected]da8543762012-03-20 08:52:20853
[email protected]420ae012009-04-24 05:16:32854 NotifyDisconnected();
[email protected]420ae012009-04-24 05:16:32855
[email protected]ca13a442012-04-17 14:00:12856 // Notify any observer that have a reference on this WebContents.
[email protected]8ff00d72012-10-23 19:12:21857 NotificationService::current()->Notify(
858 NOTIFICATION_WEB_CONTENTS_DESTROYED,
859 Source<WebContents>(this),
860 NotificationService::NoDetails());
[email protected]420ae012009-04-24 05:16:32861
Arthur Sonzogni5a9a88c2018-10-18 13:16:00862 // Destroy all subframes now. This notifies observers.
863 GetMainFrame()->ResetChildren();
[email protected]df0c843f2014-05-23 20:37:23864 GetRenderManager()->ResetProxyHosts();
[email protected]c06c58c2014-03-12 20:31:59865
clamy0e119882015-07-31 16:12:33866 // Manually call the observer methods for the root frame tree node. It is
867 // necessary to manually delete all objects tracking navigations
868 // (NavigationHandle, NavigationRequest) for observers to be properly
869 // notified of these navigations stopping before the WebContents is
870 // destroyed.
[email protected]df0c843f2014-05-23 20:37:23871 RenderFrameHostManager* root = GetRenderManager();
naskob21fe4872015-02-24 14:15:56872
Lowell Manners20250112019-10-18 15:06:15873 GetController().GetBackForwardCache().Shutdown();
874
naskob21fe4872015-02-24 14:15:56875 root->current_frame_host()->SetRenderFrameCreated(false);
clamyfc3850d2018-02-23 14:35:28876 root->current_frame_host()->ResetNavigationRequests();
clamy0e119882015-07-31 16:12:33877
Arthur Hemeryc3380172018-01-22 14:00:17878 // Do not update state as the WebContents is being destroyed.
Arthur Hemery241b9392019-10-24 11:08:41879 frame_tree_.root()->ResetNavigationRequest(true);
Arthur Hemeryc3380172018-01-22 14:00:17880 if (root->speculative_frame_host()) {
danakjf2342432019-05-15 21:46:09881 root->speculative_frame_host()->DeleteRenderFrame(
882 FrameDeleteIntention::kSpeculativeMainFrameForShutdown);
Arthur Hemeryc3380172018-01-22 14:00:17883 root->speculative_frame_host()->SetRenderFrameCreated(false);
clamyfc3850d2018-02-23 14:35:28884 root->speculative_frame_host()->ResetNavigationRequests();
clamy0e119882015-07-31 16:12:33885 }
[email protected]f273ee52013-10-18 16:05:27886
brettw4b461082016-11-19 18:55:16887#if BUILDFLAG(ENABLE_PLUGINS)
zqzhang181047e62016-07-01 13:37:17888 // Call this before WebContentsDestroyed() is broadcasted since
889 // AudioFocusManager will be destroyed after that.
890 pepper_playback_observer_.reset();
891#endif // defined(ENABLED_PLUGINS)
892
Chris Hamiltondf0d72cd2018-05-29 16:23:53893 // If audio is playing then notify external observers of the audio stream
894 // disappearing.
895 if (is_currently_audible_) {
896 is_currently_audible_ = false;
Alexander Timin90c20c32020-08-12 15:28:32897 observers_.ForEachObserver([&](WebContentsObserver* observer) {
898 observer->OnAudioStateChanged(false);
899 });
Chris Hamiltondf0d72cd2018-05-29 16:23:53900 if (GetOuterWebContents())
901 GetOuterWebContents()->OnAudioStateChanged();
902 }
903
Alexander Timin90c20c32020-08-12 15:28:32904 observers_.ForEachObserver([&](WebContentsObserver* observer) {
905 observer->FrameDeleted(root->current_frame_host());
906 });
907 observers_.ForEachObserver([&](WebContentsObserver* observer) {
908 observer->RenderViewDeleted(root->current_host());
909 });
Kevin McNee576bb5d82019-05-29 16:47:51910#if defined(OS_ANDROID)
911 // For simplicity, destroy the Java WebContents before we notify of the
912 // destruction of the WebContents.
913 ClearWebContentsAndroid();
914#endif
915
Alexander Timin90c20c32020-08-12 15:28:32916 observers_.ForEachObserver(
917 [&](WebContentsObserver* observer) { observer->WebContentsDestroyed(); });
Becca Hughesd11d6502018-07-31 17:01:28918 if (display_cutout_host_impl_)
919 display_cutout_host_impl_->WebContentsDestroyed();
920
Alexander Timin90c20c32020-08-12 15:28:32921 observers_.ForEachObserver(
922 [&](WebContentsObserver* observer) { observer->ResetWebContents(); });
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28923 SetDelegate(nullptr);
[email protected]b5a1d11c2011-02-17 03:09:42924}
925
erikchen50735fd2018-05-05 15:08:33926std::unique_ptr<WebContentsImpl> WebContentsImpl::CreateWithOpener(
[email protected]54944cde2012-12-09 09:24:59927 const WebContents::CreateParams& params,
Ian Clelland5cbaaf82017-11-27 22:00:03928 RenderFrameHostImpl* opener_rfh) {
[email protected]e11f0e92013-06-12 15:12:03929 TRACE_EVENT0("browser", "WebContentsImpl::CreateWithOpener");
Ian Clelland5cbaaf82017-11-27 22:00:03930 FrameTreeNode* opener = nullptr;
931 if (opener_rfh)
932 opener = opener_rfh->frame_tree_node();
erikchen50735fd2018-05-05 15:08:33933 std::unique_ptr<WebContentsImpl> new_contents(
934 new WebContentsImpl(params.browser_context));
lukasza6f8ac622017-06-06 03:10:20935 new_contents->SetOpenerForNewContents(opener, params.opener_suppressed);
alexmose201c7cd2015-06-10 17:14:21936
alexmosaedfc6f2016-01-21 23:57:38937 // If the opener is sandboxed, a new popup must inherit the opener's sandbox
938 // flags, and these flags take effect immediately. An exception is if the
939 // opener's sandbox flags lack the PropagatesToAuxiliaryBrowsingContexts
940 // bit (which is controlled by the "allow-popups-to-escape-sandbox" token).
941 // See https://html.spec.whatwg.org/#attr-iframe-sandbox.
lukasza6f8ac622017-06-06 03:10:20942 FrameTreeNode* new_root = new_contents->GetFrameTree()->root();
alexmosaedfc6f2016-01-21 23:57:38943 if (opener) {
arthursonzognib93a4472020-04-10 07:38:00944 network::mojom::WebSandboxFlags opener_flags =
Antonio Gomes7096ac02020-02-14 14:29:54945 opener_rfh->active_sandbox_flags();
arthursonzognib93a4472020-04-10 07:38:00946 const network::mojom::WebSandboxFlags inherit_flag =
947 network::mojom::WebSandboxFlags::kPropagatesToAuxiliaryBrowsingContexts;
Ehsan Karamad39407082019-02-19 23:38:19948 bool sandbox_propagates_to_auxilary_context =
949 (opener_flags & inherit_flag) == inherit_flag;
950 if (sandbox_propagates_to_auxilary_context)
Charlie Hue1b77ac2019-12-13 21:30:17951 new_root->SetPendingFramePolicy({opener_flags,
952 {} /* container_policy */,
953 {} /* required_document_policy */});
arthursonzognib93a4472020-04-10 07:38:00954 if (opener_flags == network::mojom::WebSandboxFlags::kNone ||
Ehsan Karamad39407082019-02-19 23:38:19955 sandbox_propagates_to_auxilary_context) {
956 // TODO(ekaramad, iclelland): Do not propagate feature policies from non-
957 // sandboxed disowned openers (rel=noopener).
958 // If the current page is not sandboxed, or if the sandbox is to propagate
959 // to the popups then opener's feature policy will apply to the new popup
960 // as well.
961 new_root->SetOpenerFeaturePolicyState(
Ehsan Karamad34d10682019-02-26 20:55:04962 opener_rfh->feature_policy()->GetFeatureState());
alexmosaedfc6f2016-01-21 23:57:38963 }
964 }
965
mark a. foltzef394fce2017-10-21 09:11:02966 // Apply starting sandbox flags.
Luna Luc3fdacdf2017-11-08 04:48:53967 blink::FramePolicy frame_policy(new_root->pending_frame_policy());
mark a. foltzef394fce2017-10-21 09:11:02968 frame_policy.sandbox_flags |= params.starting_sandbox_flags;
969 new_root->SetPendingFramePolicy(frame_policy);
Charlie Hu5ffc0152019-12-06 15:59:53970 new_root->CommitFramePolicy(frame_policy);
mark a. foltzef394fce2017-10-21 09:11:02971
alexmose201c7cd2015-06-10 17:14:21972 // This may be true even when opener is null, such as when opening blocked
973 // popups.
alexmos090fae8e2015-05-28 17:09:28974 if (params.created_with_opener)
975 new_contents->created_with_opener_ = true;
976
Sean Toppingbbc4a2bd2019-01-30 02:16:14977 WebContentsImpl* outer_web_contents = nullptr;
[email protected]4858e432014-06-23 18:14:17978 if (params.guest_delegate) {
[email protected]83100cd2014-05-10 11:50:06979 // This makes |new_contents| act as a guest.
980 // For more info, see comment above class BrowserPluginGuest.
Albert J. Wongc55cc64d2018-10-12 02:50:04981 BrowserPluginGuest::CreateInWebContents(new_contents.get(),
982 params.guest_delegate);
Sean Toppingbbc4a2bd2019-01-30 02:16:14983 outer_web_contents = static_cast<WebContentsImpl*>(
984 params.guest_delegate->GetOwnerWebContents());
[email protected]83100cd2014-05-10 11:50:06985 }
mark a. foltzef394fce2017-10-21 09:11:02986
[email protected]54944cde2012-12-09 09:24:59987 new_contents->Init(params);
Sean Toppingbbc4a2bd2019-01-30 02:16:14988 if (outer_web_contents)
989 outer_web_contents->InnerWebContentsCreated(new_contents.get());
[email protected]d1198fd2012-08-13 22:50:19990 return new_contents;
991}
992
[email protected]95640212014-07-26 18:14:30993// static
994std::vector<WebContentsImpl*> WebContentsImpl::GetAllWebContents() {
995 std::vector<WebContentsImpl*> result;
dcheng59716272016-04-09 05:19:08996 std::unique_ptr<RenderWidgetHostIterator> widgets(
[email protected]95640212014-07-26 18:14:30997 RenderWidgetHostImpl::GetRenderWidgetHosts());
[email protected]95640212014-07-26 18:14:30998 while (RenderWidgetHost* rwh = widgets->GetNextHost()) {
[email protected]95640212014-07-26 18:14:30999 RenderViewHost* rvh = RenderViewHost::From(rwh);
1000 if (!rvh)
1001 continue;
1002 WebContents* web_contents = WebContents::FromRenderViewHost(rvh);
1003 if (!web_contents)
1004 continue;
avidf38c952015-10-27 13:45:131005 if (web_contents->GetRenderViewHost() != rvh)
1006 continue;
1007 // Because a WebContents can only have one current RVH at a time, there will
1008 // be no duplicate WebContents here.
1009 result.push_back(static_cast<WebContentsImpl*>(web_contents));
[email protected]95640212014-07-26 18:14:301010 }
1011 return result;
1012}
1013
clamya16aa8172015-05-26 13:07:251014// static
1015WebContentsImpl* WebContentsImpl::FromFrameTreeNode(
paulmeyerfeafc2d2017-04-25 21:46:401016 const FrameTreeNode* frame_tree_node) {
clamya16aa8172015-05-26 13:07:251017 return static_cast<WebContentsImpl*>(
1018 WebContents::FromRenderFrameHost(frame_tree_node->current_frame_host()));
1019}
1020
clamy0d32d6d2015-11-24 11:16:261021// static
Patrick Monette275a6f92b2020-01-09 21:05:041022WebContents* WebContentsImpl::FromRenderFrameHostID(
1023 GlobalFrameRoutingId render_frame_host_id) {
1024 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI) ||
1025 !BrowserThread::IsThreadInitialized(BrowserThread::UI));
Patrick Monette7364e6972020-01-09 22:56:021026 RenderFrameHost* render_frame_host =
1027 RenderFrameHost::FromID(render_frame_host_id);
1028 if (!render_frame_host)
1029 return nullptr;
1030
1031 return WebContents::FromRenderFrameHost(render_frame_host);
Patrick Monette275a6f92b2020-01-09 21:05:041032}
1033
1034// static
clamy0d32d6d2015-11-24 11:16:261035WebContents* WebContentsImpl::FromRenderFrameHostID(int render_process_host_id,
1036 int render_frame_host_id) {
Patrick Monette7364e6972020-01-09 22:56:021037 return FromRenderFrameHostID(
1038 GlobalFrameRoutingId(render_process_host_id, render_frame_host_id));
clamy0d32d6d2015-11-24 11:16:261039}
1040
paulmeyerfeafc2d2017-04-25 21:46:401041// static
1042WebContentsImpl* WebContentsImpl::FromOuterFrameTreeNode(
1043 const FrameTreeNode* frame_tree_node) {
1044 return WebContentsImpl::FromFrameTreeNode(frame_tree_node)
1045 ->node_.GetInnerWebContentsInFrame(frame_tree_node);
1046}
1047
[email protected]b0936d22013-11-28 06:47:361048RenderFrameHostManager* WebContentsImpl::GetRenderManagerForTesting() {
[email protected]fa944cb82013-11-15 17:51:211049 return GetRenderManager();
[email protected]765187182012-01-11 23:59:281050}
1051
nicka0ac8382016-12-15 23:59:231052bool WebContentsImpl::OnMessageReceived(RenderViewHostImpl* render_view_host,
[email protected]7bb761892012-07-20 09:32:471053 const IPC::Message& message) {
Alexander Timin90c20c32020-08-12 15:28:321054 for (auto& observer : observers_.observer_list()) {
Lukasz Anforowicz89f2c1b2017-08-30 21:36:461055 // TODO(nick, creis): https://crbug.com/758026: Replace all uses of this
1056 // variant of OnMessageReceived with the version that takes a
1057 // RenderFrameHost, and then delete it.
nicka0ac8382016-12-15 23:59:231058 if (observer.OnMessageReceived(message))
1059 return true;
[email protected]64ffefa2014-05-10 12:06:331060 }
[email protected]403415a2011-01-10 18:57:531061
Henrique Ferreiroba535472020-04-21 11:38:361062#if BUILDFLAG(ENABLE_PLUGINS)
[email protected]724159a2010-12-30 01:11:181063 bool handled = true;
nicka0ac8382016-12-15 23:59:231064 IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(WebContentsImpl, message, render_view_host)
nicka0ac8382016-12-15 23:59:231065 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission,
1066 OnRequestPpapiBrokerPermission)
nicka0ac8382016-12-15 23:59:231067 IPC_MESSAGE_UNHANDLED(handled = false)
1068 IPC_END_MESSAGE_MAP()
nicka0ac8382016-12-15 23:59:231069 return handled;
Henrique Ferreiroba535472020-04-21 11:38:361070#else
1071 return false;
1072#endif
nicka0ac8382016-12-15 23:59:231073}
1074
1075bool WebContentsImpl::OnMessageReceived(RenderFrameHostImpl* render_frame_host,
1076 const IPC::Message& message) {
Alexander Timin90c20c32020-08-12 15:28:321077 for (auto& observer : observers_.observer_list()) {
nicka0ac8382016-12-15 23:59:231078 if (observer.OnMessageReceived(message, render_frame_host))
1079 return true;
1080 }
1081
1082 bool handled = true;
brettw4b461082016-11-19 18:55:161083#if BUILDFLAG(ENABLE_PLUGINS)
Hiroki Nakagawa761b9b02020-07-13 11:12:021084 IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(WebContentsImpl, message, render_frame_host)
emaxxe70f5e12015-05-29 11:26:001085 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceCreated,
1086 OnPepperInstanceCreated)
1087 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceDeleted,
1088 OnPepperInstanceDeleted)
tommyclie6633ca72014-10-31 00:40:421089 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung, OnPepperPluginHung)
zqzhang181047e62016-07-01 13:37:171090 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperStartsPlayback,
1091 OnPepperStartsPlayback)
1092 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperStopsPlayback,
1093 OnPepperStopsPlayback)
tommyclie6633ca72014-10-31 00:40:421094 IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed, OnPluginCrashed)
[email protected]724159a2010-12-30 01:11:181095 IPC_MESSAGE_UNHANDLED(handled = false)
[email protected]e44d1342014-05-16 21:29:331096 IPC_END_MESSAGE_MAP()
Hiroki Nakagawa761b9b02020-07-13 11:12:021097#else
1098 handled = false;
1099#endif
[email protected]724159a2010-12-30 01:11:181100
[email protected]724159a2010-12-30 01:11:181101 return handled;
1102}
1103
[email protected]d1198fd2012-08-13 22:50:191104NavigationControllerImpl& WebContentsImpl::GetController() {
[email protected]f5fa20e2011-12-21 22:35:561105 return controller_;
1106}
1107
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411108BrowserContext* WebContentsImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:551109 return controller_.GetBrowserContext();
[email protected]627e0512011-12-21 22:55:301110}
1111
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411112const GURL& WebContentsImpl::GetURL() {
Peter Boström101d7672018-12-15 00:43:591113 return GetVisibleURL();
[email protected]be1f56ab2011-12-22 06:55:311114}
1115
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411116const GURL& WebContentsImpl::GetVisibleURL() {
[email protected]c854a7e2013-05-21 16:42:241117 // We may not have a navigation entry yet.
[email protected]59167c22013-06-03 18:07:321118 NavigationEntry* entry = controller_.GetVisibleEntry();
[email protected]c854a7e2013-05-21 16:42:241119 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
1120}
1121
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411122const GURL& WebContentsImpl::GetLastCommittedURL() {
[email protected]c854a7e2013-05-21 16:42:241123 // We may not have a navigation entry yet.
1124 NavigationEntry* entry = controller_.GetLastCommittedEntry();
1125 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
1126}
1127
[email protected]8ff00d72012-10-23 19:12:211128WebContentsDelegate* WebContentsImpl::GetDelegate() {
[email protected]be1f56ab2011-12-22 06:55:311129 return delegate_;
1130}
1131
[email protected]8ff00d72012-10-23 19:12:211132void WebContentsImpl::SetDelegate(WebContentsDelegate* delegate) {
[email protected]be1f56ab2011-12-22 06:55:311133 // TODO(cbentzel): remove this debugging code?
1134 if (delegate == delegate_)
1135 return;
1136 if (delegate_)
1137 delegate_->Detach(this);
1138 delegate_ = delegate;
[email protected]a6b73c62013-02-11 23:05:081139 if (delegate_) {
[email protected]be1f56ab2011-12-22 06:55:311140 delegate_->Attach(this);
[email protected]a6b73c62013-02-11 23:05:081141 // Ensure the visible RVH reflects the new delegate's preferences.
[email protected]86f98a22013-03-20 14:35:001142 if (view_)
[email protected]e85165c642014-06-10 14:34:311143 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
Joel Einbinder848001c2017-09-19 21:39:311144 if (GetRenderViewHost())
1145 RenderFrameDevToolsAgentHost::WebContentsCreated(this);
[email protected]a6b73c62013-02-11 23:05:081146 }
[email protected]be1f56ab2011-12-22 06:55:311147}
1148
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411149RenderFrameHostImpl* WebContentsImpl::GetMainFrame() {
[email protected]94d0cc12013-12-18 00:07:411150 return frame_tree_.root()->current_frame_host();
[email protected]60eca4eb2013-12-06 00:02:161151}
1152
nick53d5cbf2015-04-23 22:50:141153RenderFrameHostImpl* WebContentsImpl::GetFocusedFrame() {
1154 FrameTreeNode* focused_node = frame_tree_.GetFocusedFrame();
1155 if (!focused_node)
1156 return nullptr;
1157 return focused_node->current_frame_host();
[email protected]9c9343b2014-03-08 02:56:071158}
1159
rob3e2a0732016-01-06 21:22:091160RenderFrameHostImpl* WebContentsImpl::FindFrameByFrameTreeNodeId(
creisf71a2632017-05-04 19:03:501161 int frame_tree_node_id,
1162 int process_id) {
1163 FrameTreeNode* frame = frame_tree_.FindByID(frame_tree_node_id);
1164
1165 // Sanity check that this is in the caller's expected process. Otherwise a
1166 // recent cross-process navigation may have led to a privilege change that the
1167 // caller is not expecting.
1168 if (!frame ||
1169 frame->current_frame_host()->GetProcess()->GetID() != process_id)
1170 return nullptr;
1171
1172 return frame->current_frame_host();
1173}
1174
1175RenderFrameHostImpl* WebContentsImpl::UnsafeFindFrameByFrameTreeNodeId(
rob3e2a0732016-01-06 21:22:091176 int frame_tree_node_id) {
creisf71a2632017-05-04 19:03:501177 // Beware using this! The RenderFrameHost may have changed since the caller
1178 // obtained frame_tree_node_id.
rob3e2a0732016-01-06 21:22:091179 FrameTreeNode* frame = frame_tree_.FindByID(frame_tree_node_id);
1180 return frame ? frame->current_frame_host() : nullptr;
1181}
1182
[email protected]a86c0e962013-12-17 17:10:391183void WebContentsImpl::ForEachFrame(
Lei Zhangebcc6302018-01-12 19:46:451184 const base::RepeatingCallback<void(RenderFrameHost*)>& on_frame) {
dcheng57e39e22016-01-21 00:25:381185 for (FrameTreeNode* node : frame_tree_.Nodes()) {
1186 on_frame.Run(node->current_frame_host());
1187 }
[email protected]a86c0e962013-12-17 17:10:391188}
1189
dchengafb53e22016-02-04 08:11:081190std::vector<RenderFrameHost*> WebContentsImpl::GetAllFrames() {
Xuehui Xieb2300ae42020-06-09 20:25:051191 return GetAllFramesImpl(frame_tree_, /*include_pending=*/false);
1192}
1193
1194std::vector<RenderFrameHost*> WebContentsImpl::GetAllFramesIncludingPending() {
1195 return GetAllFramesImpl(frame_tree_, /*include_pending=*/true);
dchengafb53e22016-02-04 08:11:081196}
1197
lukaszacbdf52e2016-01-15 21:19:511198int WebContentsImpl::SendToAllFrames(IPC::Message* message) {
Xuehui Xieb2300ae42020-06-09 20:25:051199 return SendToAllFramesImpl(frame_tree_, /*include_pending=*/false, message);
1200}
lukasza1a9ab2422016-03-02 18:47:251201
Xuehui Xieb2300ae42020-06-09 20:25:051202int WebContentsImpl::SendToAllFramesIncludingPending(IPC::Message* message) {
1203 return SendToAllFramesImpl(frame_tree_, /*include_pending=*/true, message);
[email protected]a86c0e962013-12-17 17:10:391204}
1205
lfgdb5c4ed2016-03-04 23:09:071206void WebContentsImpl::SendPageMessage(IPC::Message* msg) {
alexmos136fd6e62016-08-15 20:58:411207 frame_tree_.root()->render_manager()->SendPageMessage(msg, nullptr);
lfgdb5c4ed2016-03-04 23:09:071208}
1209
Gyuyoung Kim877e86d2020-07-21 04:01:021210void WebContentsImpl::ExecutePageBroadcastMethod(
1211 PageBroadcastMethodCallback callback) {
1212 frame_tree_.root()->render_manager()->ExecutePageBroadcastMethod(callback);
1213}
1214
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411215RenderViewHostImpl* WebContentsImpl::GetRenderViewHost() {
[email protected]fa944cb82013-11-15 17:51:211216 return GetRenderManager()->current_host();
[email protected]be1f56ab2011-12-22 06:55:311217}
1218
creis89a0f782015-05-27 16:13:171219void WebContentsImpl::CancelActiveAndPendingDialogs() {
Evan Stade753fc202020-07-13 18:09:541220 if (dialog_manager_) {
avi6879fcf2017-01-21 05:27:531221 dialog_manager_->CancelDialogs(this, /*reset_state=*/false);
Evan Stade753fc202020-07-13 18:09:541222 }
creis89a0f782015-05-27 16:13:171223 if (browser_plugin_embedder_)
1224 browser_plugin_embedder_->CancelGuestDialogs();
1225}
1226
naskoc0fceff2015-04-30 15:53:521227void WebContentsImpl::ClosePage() {
1228 GetRenderViewHost()->ClosePage();
1229}
1230
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411231RenderWidgetHostView* WebContentsImpl::GetRenderWidgetHostView() {
[email protected]fa944cb82013-11-15 17:51:211232 return GetRenderManager()->GetRenderWidgetHostView();
[email protected]be1f56ab2011-12-22 06:55:311233}
1234
lfg265a2672016-04-23 03:11:021235RenderWidgetHostView* WebContentsImpl::GetTopLevelRenderWidgetHostView() {
1236 if (GetOuterWebContents())
1237 return GetOuterWebContents()->GetTopLevelRenderWidgetHostView();
1238 return GetRenderManager()->GetRenderWidgetHostView();
1239}
1240
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411241RenderWidgetHostView* WebContentsImpl::GetFullscreenRenderWidgetHostView() {
vmpstr6d9996c82017-02-23 00:43:251242 if (auto* widget_host = GetFullscreenRenderWidgetHost())
ekaramadaeb3c5c2016-11-09 03:22:351243 return widget_host->GetView();
1244 return nullptr;
[email protected]4aebbca2013-09-17 22:26:491245}
1246
[email protected]8ff00d72012-10-23 19:12:211247WebContentsView* WebContentsImpl::GetView() const {
[email protected]be1f56ab2011-12-22 06:55:311248 return view_.get();
1249}
1250
Mike Wassermanb213b9352020-04-16 00:32:341251void WebContentsImpl::OnScreensChange() {
1252 for (FrameTreeNode* node : frame_tree_.Nodes()) {
1253 RenderFrameHostImpl* rfh = node->current_frame_host();
1254 rfh->GetAssociatedLocalFrame()->OnScreensChange();
1255 }
1256}
1257
leon.han552e9de2017-02-09 14:37:301258void WebContentsImpl::OnScreenOrientationChange() {
1259 DCHECK(screen_orientation_provider_);
Lan Weif81c6e7c2020-02-12 16:46:091260 DidChangeScreenOrientation();
Becca Hughese9e27952018-06-25 17:08:271261 screen_orientation_provider_->OnOrientationChange();
leon.hane4db177a2017-02-07 14:19:161262}
1263
Alan Cutter92d59252019-03-29 02:32:331264base::Optional<SkColor> WebContentsImpl::GetThemeColor() {
Carlos Caballero1215f882019-10-29 15:58:431265 return GetRenderViewHost()->theme_color();
yusufod41c5f92015-03-06 00:14:281266}
1267
Doug Turner63f3c7b2017-07-29 05:10:011268void WebContentsImpl::SetAccessibilityMode(ui::AXMode mode) {
[email protected]95640212014-07-26 18:14:301269 if (mode == accessibility_mode_)
1270 return;
1271
dmazzonif8a31042016-12-03 00:52:131272 // Don't allow accessibility to be enabled for WebContents that are never
danakj77eb7e82020-01-09 19:38:461273 // user-visible, like background pages.
1274 if (IsNeverComposited())
dmazzonif8a31042016-12-03 00:52:131275 return;
1276
[email protected]95640212014-07-26 18:14:301277 accessibility_mode_ = mode;
dcheng57e39e22016-01-21 00:25:381278
1279 for (FrameTreeNode* node : frame_tree_.Nodes()) {
dmazzonif8a31042016-12-03 00:52:131280 UpdateAccessibilityModeOnFrame(node->current_frame_host());
clamy610c63b32017-12-22 15:05:181281 // Also update accessibility mode on the speculative RenderFrameHost for
1282 // this FrameTreeNode, if one exists.
Alex Moshchuk3d8a1f392017-10-24 19:01:261283 RenderFrameHost* speculative_frame_host =
1284 node->render_manager()->speculative_frame_host();
1285 if (speculative_frame_host)
1286 UpdateAccessibilityModeOnFrame(speculative_frame_host);
dcheng57e39e22016-01-21 00:25:381287 }
[email protected]95640212014-07-26 18:14:301288}
1289
Doug Turner63f3c7b2017-07-29 05:10:011290void WebContentsImpl::AddAccessibilityMode(ui::AXMode mode) {
1291 ui::AXMode new_mode(accessibility_mode_);
dougtcd3dad732017-03-14 03:26:231292 new_mode |= mode;
1293 SetAccessibilityMode(new_mode);
[email protected]95640212014-07-26 18:14:301294}
1295
Avi Drissman1e620f32018-03-16 13:57:291296// Helper class used by WebContentsImpl::RequestAXTreeSnapshot.
1297// Handles the callbacks from parallel snapshot requests to each frame,
1298// and feeds the results to an AXTreeCombiner, which converts them into a
1299// single combined accessibility tree.
1300class WebContentsImpl::AXTreeSnapshotCombiner
1301 : public base::RefCounted<AXTreeSnapshotCombiner> {
1302 public:
1303 explicit AXTreeSnapshotCombiner(AXTreeSnapshotCallback callback)
1304 : callback_(std::move(callback)) {}
1305
1306 AXTreeSnapshotCallback AddFrame(bool is_root) {
1307 // Adds a reference to |this|.
1308 return base::BindOnce(&AXTreeSnapshotCombiner::ReceiveSnapshot, this,
1309 is_root);
1310 }
1311
1312 void ReceiveSnapshot(bool is_root, const ui::AXTreeUpdate& snapshot) {
1313 combiner_.AddTree(snapshot, is_root);
1314 }
1315
1316 private:
1317 friend class base::RefCounted<AXTreeSnapshotCombiner>;
1318
1319 // This is called automatically after the last call to ReceiveSnapshot
1320 // when there are no more references to this object.
1321 ~AXTreeSnapshotCombiner() {
1322 combiner_.Combine();
1323 std::move(callback_).Run(combiner_.combined());
1324 }
1325
1326 ui::AXTreeCombiner combiner_;
1327 AXTreeSnapshotCallback callback_;
1328};
1329
1330void WebContentsImpl::RequestAXTreeSnapshot(AXTreeSnapshotCallback callback,
1331 ui::AXMode ax_mode) {
dmazzonid95ae842016-04-12 21:17:391332 // Send a request to each of the frames in parallel. Each one will return
1333 // an accessibility tree snapshot, and AXTreeSnapshotCombiner will combine
1334 // them into a single tree and call |callback| with that result, then
1335 // delete |combiner|.
Avi Drissman1e620f32018-03-16 13:57:291336 FrameTreeNode* root_node = frame_tree_.root();
tzik58faa742018-08-01 10:54:181337 auto combiner =
1338 base::MakeRefCounted<AXTreeSnapshotCombiner>(std::move(callback));
Avi Drissman1e620f32018-03-16 13:57:291339
tzik58faa742018-08-01 10:54:181340 RecursiveRequestAXTreeSnapshotOnFrame(root_node, combiner.get(), ax_mode);
Avi Drissman1e620f32018-03-16 13:57:291341}
1342
1343void WebContentsImpl::RecursiveRequestAXTreeSnapshotOnFrame(
1344 FrameTreeNode* root_node,
1345 AXTreeSnapshotCombiner* combiner,
1346 ui::AXMode ax_mode) {
dmazzonid95ae842016-04-12 21:17:391347 for (FrameTreeNode* frame_tree_node : frame_tree_.Nodes()) {
Avi Drissman1e620f32018-03-16 13:57:291348 WebContentsImpl* inner_contents =
1349 node_.GetInnerWebContentsInFrame(frame_tree_node);
1350 if (inner_contents) {
1351 inner_contents->RecursiveRequestAXTreeSnapshotOnFrame(root_node, combiner,
1352 ax_mode);
1353 } else {
1354 bool is_root = frame_tree_node == root_node;
1355 frame_tree_node->current_frame_host()->RequestAXTreeSnapshot(
1356 combiner->AddFrame(is_root), ax_mode);
1357 }
dmazzonid95ae842016-04-12 21:17:391358 }
dmazzoni83ba5c82015-04-14 07:11:511359}
1360
Becca Hughes3b5a43482018-07-17 22:31:551361void WebContentsImpl::NotifyViewportFitChanged(
1362 blink::mojom::ViewportFit value) {
Alexander Timin90c20c32020-08-12 15:28:321363 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1364 observer->ViewportFitChanged(value);
1365 });
Becca Hughes3b5a43482018-07-17 22:31:551366}
1367
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411368FindRequestManager* WebContentsImpl::GetFindRequestManagerForTesting() {
Ehsan Karamad6beb2ea2018-11-25 18:15:131369 return GetFindRequestManager();
1370}
1371
mcnee336ea2c2017-05-23 22:50:591372#if !defined(OS_ANDROID)
akabac6bd1212018-06-25 20:10:481373void WebContentsImpl::UpdateZoom() {
1374 RenderWidgetHostImpl* rwh = GetRenderViewHost()->GetWidget();
1375 if (rwh->GetView())
1376 rwh->SynchronizeVisualProperties();
wjmaclean64951902016-04-29 20:59:121377}
1378
wjmaclean64951902016-04-29 20:59:121379
1380void WebContentsImpl::UpdateZoomIfNecessary(const std::string& scheme,
akabac6bd1212018-06-25 20:10:481381 const std::string& host) {
wjmaclean64951902016-04-29 20:59:121382 NavigationEntry* entry = GetController().GetLastCommittedEntry();
1383 if (!entry)
1384 return;
1385
1386 GURL url = HostZoomMap::GetURLFromEntry(entry);
1387 if (host != net::GetHostOrSpecFromURL(url) ||
1388 (!scheme.empty() && !url.SchemeIs(scheme))) {
1389 return;
1390 }
1391
akabac6bd1212018-06-25 20:10:481392 UpdateZoom();
wjmaclean64951902016-04-29 20:59:121393}
mcnee336ea2c2017-05-23 22:50:591394#endif // !defined(OS_ANDROID)
wjmaclean64951902016-04-29 20:59:121395
Julie Jeongeun Kim7d0986172019-12-04 03:17:251396base::OnceClosure WebContentsImpl::AddReceiverSet(
rockotf62002a2016-09-15 00:08:591397 const std::string& interface_name,
Julie Jeongeun Kim7d0986172019-12-04 03:17:251398 WebContentsReceiverSet* receiver_set) {
rockotf62002a2016-09-15 00:08:591399 auto result =
Julie Jeongeun Kim7d0986172019-12-04 03:17:251400 receiver_sets_.insert(std::make_pair(interface_name, receiver_set));
rockotf62002a2016-09-15 00:08:591401 DCHECK(result.second);
Julie Jeongeun Kim7d0986172019-12-04 03:17:251402 return base::BindOnce(&WebContentsImpl::RemoveReceiverSet,
danakjf4b9e942019-11-29 15:43:041403 weak_factory_.GetWeakPtr(), interface_name);
rockotf62002a2016-09-15 00:08:591404}
1405
Julie Jeongeun Kim7d0986172019-12-04 03:17:251406WebContentsReceiverSet* WebContentsImpl::GetReceiverSet(
rockot8bbad222017-03-22 04:34:051407 const std::string& interface_name) {
Julie Jeongeun Kim7d0986172019-12-04 03:17:251408 auto it = receiver_sets_.find(interface_name);
1409 if (it == receiver_sets_.end())
rockot8bbad222017-03-22 04:34:051410 return nullptr;
1411 return it->second;
1412}
1413
John Delaney732721e92020-02-07 23:11:271414void WebContentsImpl::RemoveReceiverSetForTesting(
1415 const std::string& interface_name) {
1416 RemoveReceiverSet(interface_name);
1417}
1418
paulmeyerfeafc2d2017-04-25 21:46:401419std::vector<WebContentsImpl*> WebContentsImpl::GetWebContentsAndAllInner() {
1420 std::vector<WebContentsImpl*> all_contents(1, this);
1421
1422 for (size_t i = 0; i != all_contents.size(); ++i) {
1423 for (auto* inner_contents : all_contents[i]->GetInnerWebContents()) {
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:161424 all_contents.push_back(static_cast<WebContentsImpl*>(inner_contents));
paulmeyerfeafc2d2017-04-25 21:46:401425 }
1426 }
1427
1428 return all_contents;
1429}
1430
Sam McNally145fb172017-05-10 00:13:231431void WebContentsImpl::NotifyManifestUrlChanged(
Yuzu Saijo0c263c702020-06-08 03:41:241432 RenderFrameHost* rfh,
Sam McNally145fb172017-05-10 00:13:231433 const base::Optional<GURL>& manifest_url) {
Alexander Timin90c20c32020-08-12 15:28:321434 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1435 observer->DidUpdateWebManifestURL(rfh, manifest_url);
1436 });
Sam McNally145fb172017-05-10 00:13:231437}
1438
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411439WebUI* WebContentsImpl::GetWebUI() {
Nasko Oskov2f7d2112019-10-29 03:26:571440 WebUI* committed_web_ui = GetCommittedWebUI();
1441 if (committed_web_ui)
1442 return committed_web_ui;
1443
1444 if (GetRenderManager()->speculative_frame_host())
1445 return GetRenderManager()->speculative_frame_host()->web_ui();
1446
1447 return nullptr;
[email protected]be1f56ab2011-12-22 06:55:311448}
1449
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411450WebUI* WebContentsImpl::GetCommittedWebUI() {
carlosk35f35af2015-12-01 10:55:401451 return frame_tree_.root()->current_frame_host()->web_ui();
[email protected]d5f942ba2008-09-26 19:30:341452}
1453
Maks Orlovich73f374d2020-04-02 12:46:131454void WebContentsImpl::SetUserAgentOverride(
1455 const blink::UserAgentOverride& ua_override,
1456 bool override_in_new_tabs) {
1457 DCHECK(!ua_override.ua_metadata_override.has_value() ||
1458 !ua_override.ua_string_override.empty());
1459
1460 if (GetUserAgentOverride() == ua_override)
[email protected]bf70edce2012-06-20 22:32:221461 return;
1462
Changwan Ryuc1134a82018-03-07 02:10:141463 should_override_user_agent_in_new_tabs_ = override_in_new_tabs;
1464
Maks Orlovich73f374d2020-04-02 12:46:131465 renderer_preferences_.user_agent_override = ua_override;
[email protected]bf70edce2012-06-20 22:32:221466
Bruce Long1e3e1f542019-10-16 17:56:281467 // Send the new override string to all renderers in the current page.
1468 SyncRendererPrefs();
[email protected]bf70edce2012-06-20 22:32:221469
1470 // Reload the page if a load is currently in progress to avoid having
1471 // different parts of the page loaded using different user agents.
Scott Violete1d58cc2020-04-28 23:07:171472 // No need to reload if the current entry matches that of the
1473 // NavigationRequest supplied to DidStartNavigation() as NavigationRequest
1474 // handles it.
[email protected]6286a372013-10-09 04:03:271475 NavigationEntry* entry = controller_.GetVisibleEntry();
Scott Violete1d58cc2020-04-28 23:07:171476 if (IsLoading() && entry != nullptr && entry->GetIsOverridingUserAgent() &&
1477 (!frame_tree_.root()->navigation_request() ||
1478 frame_tree_.root()->navigation_request()->ua_change_requires_reload())) {
toyoshim6142d96f2016-12-19 09:07:251479 controller_.Reload(ReloadType::BYPASSING_CACHE, true);
Scott Violete1d58cc2020-04-28 23:07:171480 }
[email protected]8d0f3312012-08-18 01:47:531481
Alexander Timin90c20c32020-08-12 15:28:321482 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1483 observer->UserAgentOverrideSet(ua_override);
1484 });
[email protected]86ef6a392012-05-11 22:03:111485}
1486
Scott Violet2a6c5bff2020-04-29 23:59:061487void WebContentsImpl::SetRendererInitiatedUserAgentOverrideOption(
1488 NavigationController::UserAgentOverrideOption option) {
1489 renderer_initiated_user_agent_override_option_ = option;
1490}
1491
Maks Orlovich73f374d2020-04-02 12:46:131492const blink::UserAgentOverride& WebContentsImpl::GetUserAgentOverride() {
[email protected]bf70edce2012-06-20 22:32:221493 return renderer_preferences_.user_agent_override;
[email protected]86ef6a392012-05-11 22:03:111494}
1495
Scott Violet2a6c5bff2020-04-29 23:59:061496bool WebContentsImpl::ShouldOverrideUserAgentForRendererInitiatedNavigation() {
1497 NavigationEntryImpl* current_entry = controller_.GetLastCommittedEntry();
1498 if (!current_entry)
1499 return should_override_user_agent_in_new_tabs_;
1500
1501 switch (renderer_initiated_user_agent_override_option_) {
1502 case NavigationController::UA_OVERRIDE_INHERIT:
1503 return current_entry->GetIsOverridingUserAgent();
1504 case NavigationController::UA_OVERRIDE_TRUE:
1505 return true;
1506 case NavigationController::UA_OVERRIDE_FALSE:
1507 return false;
1508 default:
1509 break;
1510 }
1511 return false;
Changwan Ryuc1134a82018-03-07 02:10:141512}
1513
dmazzonidd3d51a72016-12-14 18:41:011514void WebContentsImpl::EnableWebContentsOnlyAccessibilityMode() {
Dominic Mazzonid9fda172019-03-07 17:12:071515 // If accessibility is already enabled, we'll need to force a reset
1516 // in order to ensure new observers of accessibility events get the
1517 // full accessibility tree from scratch.
1518 bool need_reset = GetAccessibilityMode().has_mode(ui::AXMode::kWebContents);
1519
1520 ui::AXMode desired_mode =
1521 GetContentClient()->browser()->GetAXModeForBrowserContext(
1522 GetBrowserContext());
1523 desired_mode |= ui::kAXModeWebContentsOnly;
1524 AddAccessibilityMode(desired_mode);
1525
1526 if (need_reset) {
dchengafb53e22016-02-04 08:11:081527 for (RenderFrameHost* rfh : GetAllFrames())
1528 ResetAccessibility(rfh);
dchengafb53e22016-02-04 08:11:081529 }
[email protected]95640212014-07-26 18:14:301530}
1531
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411532bool WebContentsImpl::IsWebContentsOnlyAccessibilityModeForTesting() {
Doug Turner63f3c7b2017-07-29 05:10:011533 return accessibility_mode_ == ui::kAXModeWebContentsOnly;
[email protected]95640212014-07-26 18:14:301534}
1535
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411536bool WebContentsImpl::IsFullAccessibilityModeForTesting() {
Doug Turner63f3c7b2017-07-29 05:10:011537 return accessibility_mode_ == ui::kAXModeComplete;
[email protected]95640212014-07-26 18:14:301538}
1539
Becca Hughes6daf5662018-06-27 16:50:541540#if defined(OS_ANDROID)
1541
1542void WebContentsImpl::SetDisplayCutoutSafeArea(gfx::Insets insets) {
Becca Hughes86334622018-07-09 21:29:381543 if (display_cutout_host_impl_)
1544 display_cutout_host_impl_->SetDisplayCutoutSafeArea(insets);
Becca Hughes6daf5662018-06-27 16:50:541545}
1546
1547#endif
1548
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411549const base::string16& WebContentsImpl::GetTitle() {
Nasko Oskov2f7d2112019-10-29 03:26:571550 WebUI* our_web_ui =
1551 GetRenderManager()->speculative_frame_host()
1552 ? GetRenderManager()->speculative_frame_host()->web_ui()
1553 : GetRenderManager()->current_frame_host()->web_ui();
[email protected]7ade2732011-02-10 00:13:581554 if (our_web_ui) {
[email protected]96d185d2009-04-24 03:28:541555 // Don't override the title in view source mode.
Carlos IL4dea8902020-05-26 15:14:291556 NavigationEntry* entry = controller_.GetVisibleEntry();
[email protected]96d185d2009-04-24 03:28:541557 if (!(entry && entry->IsViewSourceMode())) {
[email protected]e0112912011-02-02 22:54:351558 // Give the Web UI the chance to override our title.
[email protected]fcf75d42013-12-03 20:11:261559 const base::string16& title = our_web_ui->GetOverriddenTitle();
[email protected]96d185d2009-04-24 03:28:541560 if (!title.empty())
1561 return title;
1562 }
1563 }
1564
1565 // We use the title for the last committed entry rather than a pending
1566 // navigation entry. For example, when the user types in a URL, we want to
1567 // keep the old page's title until the new load has committed and we get a new
1568 // title.
Carlos IL4dea8902020-05-26 15:14:291569 NavigationEntry* entry = controller_.GetLastCommittedEntry();
[email protected]59167c22013-06-03 18:07:321570
creis072b61f2015-09-28 20:52:241571 // We make an exception for initial navigations. We only want to use the title
1572 // from the visible entry if:
1573 // 1. The pending entry has been explicitly assigned a title to display.
1574 // 2. The user is doing a history navigation in a new tab (e.g., Ctrl+Back),
1575 // which case there is a pending entry index other than -1.
1576 //
1577 // Otherwise, we want to stick with the last committed entry's title during
1578 // new navigations, which have pending entries at index -1 with no title.
1579 if (controller_.IsInitialNavigation() &&
1580 ((controller_.GetVisibleEntry() &&
1581 !controller_.GetVisibleEntry()->GetTitle().empty()) ||
1582 controller_.GetPendingEntryIndex() != -1)) {
1583 entry = controller_.GetVisibleEntry();
[email protected]9eeafc012013-11-25 23:49:471584 }
[email protected]59167c22013-06-03 18:07:321585
[email protected]45d0ef7f2011-01-05 13:46:231586 if (entry) {
jshin1fb76462016-04-05 22:13:031587 return entry->GetTitleForDisplay();
[email protected]45d0ef7f2011-01-05 13:46:231588 }
[email protected]987fc3a2011-05-26 14:18:091589
1590 // |page_title_when_no_navigation_entry_| is finally used
1591 // if no title cannot be retrieved.
1592 return page_title_when_no_navigation_entry_;
[email protected]96d185d2009-04-24 03:28:541593}
1594
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411595SiteInstanceImpl* WebContentsImpl::GetSiteInstance() {
[email protected]fa944cb82013-11-15 17:51:211596 return GetRenderManager()->current_host()->GetSiteInstance();
[email protected]96d185d2009-04-24 03:28:541597}
1598
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411599bool WebContentsImpl::IsLoading() {
Carlos ILd51e7702020-05-07 18:51:391600 return frame_tree_.IsLoading();
[email protected]3c9e1872010-11-18 16:17:491601}
1602
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411603double WebContentsImpl::GetLoadProgress() {
Peter Boström18a40fa2018-10-31 19:03:501604 return frame_tree_.load_progress();
1605}
1606
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411607bool WebContentsImpl::IsLoadingToDifferentDocument() {
clamy44e84ce2016-02-22 15:38:251608 return IsLoading() && is_load_to_different_document_;
[email protected]6dfed692014-05-22 04:18:031609}
1610
Alexander Timindd0fa0c52019-11-06 13:03:371611bool WebContentsImpl::IsDocumentOnLoadCompletedInMainFrame() {
1612 return GetRenderViewHost()->IsDocumentOnLoadCompletedInMainFrame();
1613}
1614
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411615bool WebContentsImpl::IsWaitingForResponse() {
Peter Boströma9a27f6e2018-11-21 13:12:191616 NavigationRequest* ongoing_navigation_request =
1617 frame_tree_.root()->navigation_request();
1618
1619 // An ongoing navigation request means we're waiting for a response.
1620 return ongoing_navigation_request != nullptr;
[email protected]be1f56ab2011-12-22 06:55:311621}
1622
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411623const net::LoadStateWithParam& WebContentsImpl::GetLoadState() {
[email protected]be1f56ab2011-12-22 06:55:311624 return load_state_;
1625}
1626
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411627const base::string16& WebContentsImpl::GetLoadStateHost() {
[email protected]be1f56ab2011-12-22 06:55:311628 return load_state_host_;
1629}
1630
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411631uint64_t WebContentsImpl::GetUploadSize() {
[email protected]be1f56ab2011-12-22 06:55:311632 return upload_size_;
1633}
1634
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411635uint64_t WebContentsImpl::GetUploadPosition() {
[email protected]be1f56ab2011-12-22 06:55:311636 return upload_position_;
1637}
1638
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411639const std::string& WebContentsImpl::GetEncoding() {
Alexander Timine5f20e22019-10-09 23:22:351640 return GetMainFrame()->GetEncoding();
[email protected]be1f56ab2011-12-22 06:55:311641}
1642
Charles Zhaod72f99d2018-09-17 14:18:271643bool WebContentsImpl::WasDiscarded() {
1644 return GetFrameTree()->root()->was_discarded();
1645}
1646
Shubhie Panickerddf2a4e2018-03-06 00:09:061647void WebContentsImpl::SetWasDiscarded(bool was_discarded) {
1648 GetFrameTree()->root()->set_was_discarded();
1649}
1650
Collin Bakerc5259962019-11-14 17:51:581651void WebContentsImpl::IncrementCapturerCount(const gfx::Size& capture_size,
1652 bool stay_hidden) {
[email protected]5a652232013-02-12 06:15:251653 DCHECK(!is_being_destroyed_);
Collin Bakerc5259962019-11-14 17:51:581654 if (stay_hidden)
1655 ++hidden_capturer_count_;
1656 else
1657 ++visible_capturer_count_;
[email protected]222f5822014-02-05 23:40:491658
1659 // Note: This provides a hint to upstream code to size the views optimally
1660 // for quality (e.g., to avoid scaling).
1661 if (!capture_size.IsEmpty() && preferred_size_for_capture_.IsEmpty()) {
1662 preferred_size_for_capture_ = capture_size;
1663 OnPreferredSizeChanged(preferred_size_);
1664 }
ccameron8807c38f2015-01-17 00:29:191665
Collin Bakerc5259962019-11-14 17:51:581666 UpdateVisibilityAndNotifyPageAndView(GetVisibility());
[email protected]54597982013-02-06 01:59:551667}
1668
Collin Bakerc5259962019-11-14 17:51:581669void WebContentsImpl::DecrementCapturerCount(bool stay_hidden) {
1670 if (stay_hidden)
1671 --hidden_capturer_count_;
1672 else
1673 --visible_capturer_count_;
1674 DCHECK_GE(hidden_capturer_count_, 0);
1675 DCHECK_GE(visible_capturer_count_, 0);
[email protected]54597982013-02-06 01:59:551676
[email protected]5a652232013-02-12 06:15:251677 if (is_being_destroyed_)
1678 return;
1679
Francois Doray24fc62c2017-12-11 17:27:331680 if (!IsBeingCaptured()) {
[email protected]222f5822014-02-05 23:40:491681 const gfx::Size old_size = preferred_size_for_capture_;
1682 preferred_size_for_capture_ = gfx::Size();
1683 OnPreferredSizeChanged(old_size);
[email protected]54597982013-02-06 01:59:551684 }
Collin Bakerc5259962019-11-14 17:51:581685
1686 UpdateVisibilityAndNotifyPageAndView(GetVisibility());
[email protected]be1f56ab2011-12-22 06:55:311687}
1688
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411689bool WebContentsImpl::IsBeingCaptured() {
Collin Bakerc5259962019-11-14 17:51:581690 return visible_capturer_count_ + hidden_capturer_count_ > 0;
[email protected]f2bd40812013-07-20 04:30:441691}
1692
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411693bool WebContentsImpl::IsAudioMuted() {
Guido Urdanetaf8372942019-11-15 09:47:211694 return audio_stream_factory_ && audio_stream_factory_->IsMuted();
miu50f97892014-09-22 22:49:521695}
1696
1697void WebContentsImpl::SetAudioMuted(bool mute) {
1698 DVLOG(1) << "SetAudioMuted(mute=" << mute << "), was " << IsAudioMuted()
1699 << " for WebContentsImpl@" << this;
1700
1701 if (mute == IsAudioMuted())
1702 return;
1703
Guido Urdanetaf8372942019-11-15 09:47:211704 GetAudioStreamFactory()->SetMuted(mute);
miu50f97892014-09-22 22:49:521705
Alexander Timin90c20c32020-08-12 15:28:321706 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1707 observer->DidUpdateAudioMutingState(mute);
1708 });
Jan Rucka442c83f2017-08-08 13:27:541709 // Notification for UI updates in response to the changed muting state.
Collin Bakeraf540cf2019-09-20 20:54:161710 NotifyNavigationStateChanged(INVALIDATE_TYPE_AUDIO);
Jan Rucka442c83f2017-08-08 13:27:541711}
1712
1713bool WebContentsImpl::IsCurrentlyAudible() {
Chris Hamiltondf0d72cd2018-05-29 16:23:531714 return is_currently_audible_;
miu50f97892014-09-22 22:49:521715}
1716
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411717bool WebContentsImpl::IsConnectedToBluetoothDevice() {
ortunodf4d7982016-04-08 02:33:351718 return bluetooth_connected_device_count_ > 0;
ortuno32e7db3c2016-03-29 16:14:201719}
1720
Ovidio Henriquez76696f62020-07-08 03:06:591721bool WebContentsImpl::IsScanningForBluetoothDevices() {
1722 return bluetooth_scanning_sessions_count_ > 0;
1723}
1724
Lucas Furukawa Gadani4b4eed02019-06-04 23:12:041725bool WebContentsImpl::IsConnectedToSerialPort() {
Reilly Grant5e7c79b22019-04-09 17:26:201726 return serial_active_frame_count_ > 0;
1727}
1728
Matt Reynoldse8c6c1f2019-11-02 09:53:531729bool WebContentsImpl::IsConnectedToHidDevice() {
1730 return hid_active_frame_count_ > 0;
1731}
1732
Marijn Kruisselbrink29051042019-08-06 22:56:551733bool WebContentsImpl::HasNativeFileSystemHandles() {
1734 return native_file_system_handle_count_ > 0;
1735}
Marijn Kruisselbrinkf1714aa22019-07-02 03:45:331736
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411737bool WebContentsImpl::HasPictureInPictureVideo() {
sawtellea7333a82018-05-31 02:36:361738 return has_picture_in_picture_video_;
1739}
1740
1741void WebContentsImpl::SetHasPictureInPictureVideo(
1742 bool has_picture_in_picture_video) {
1743 // If status of |this| is already accurate, there is no need to update.
1744 if (has_picture_in_picture_video == has_picture_in_picture_video_)
1745 return;
1746 has_picture_in_picture_video_ = has_picture_in_picture_video;
1747 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
Alexander Timin90c20c32020-08-12 15:28:321748 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1749 observer->MediaPictureInPictureChanged(has_picture_in_picture_video_);
1750 });
sawtellea7333a82018-05-31 02:36:361751}
1752
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411753bool WebContentsImpl::IsCrashed() {
Dominic Mazzoni73a48322018-05-25 18:14:071754 switch (crashed_status_) {
1755 case base::TERMINATION_STATUS_PROCESS_CRASHED:
1756 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
1757 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED:
1758 case base::TERMINATION_STATUS_OOM:
1759 case base::TERMINATION_STATUS_LAUNCH_FAILED:
Darin Fisher6cf20e782020-08-07 22:25:361760#if defined(OS_CHROMEOS) || BUILDFLAG(IS_LACROS)
Dominic Mazzoni73a48322018-05-25 18:14:071761 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM:
oshima620225722015-06-04 19:45:271762#endif
Dominic Mazzoni73a48322018-05-25 18:14:071763#if defined(OS_ANDROID)
1764 case base::TERMINATION_STATUS_OOM_PROTECTED:
1765#endif
Will Harris07925d12019-10-31 03:03:051766#if defined(OS_WIN)
1767 case base::TERMINATION_STATUS_INTEGRITY_FAILURE:
1768#endif
Dominic Mazzoni73a48322018-05-25 18:14:071769 return true;
1770 case base::TERMINATION_STATUS_NORMAL_TERMINATION:
1771 case base::TERMINATION_STATUS_STILL_RUNNING:
1772 return false;
1773 case base::TERMINATION_STATUS_MAX_ENUM:
1774 NOTREACHED();
1775 return false;
1776 }
1777
1778 NOTREACHED();
1779 return false;
[email protected]3c9e1872010-11-18 16:17:491780}
1781
[email protected]b172aee2012-04-10 17:05:261782void WebContentsImpl::SetIsCrashed(base::TerminationStatus status,
1783 int error_code) {
[email protected]443b80e2010-12-14 00:42:231784 if (status == crashed_status_)
[email protected]d5f942ba2008-09-26 19:30:341785 return;
1786
[email protected]443b80e2010-12-14 00:42:231787 crashed_status_ = status;
1788 crashed_error_code_ = error_code;
[email protected]8ff00d72012-10-23 19:12:211789 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
[email protected]d5f942ba2008-09-26 19:30:341790}
1791
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411792base::TerminationStatus WebContentsImpl::GetCrashedStatus() {
[email protected]be1f56ab2011-12-22 06:55:311793 return crashed_status_;
1794}
1795
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411796int WebContentsImpl::GetCrashedErrorCode() {
afakhry98241832016-03-11 19:27:471797 return crashed_error_code_;
1798}
1799
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411800bool WebContentsImpl::IsBeingDestroyed() {
[email protected]be1f56ab2011-12-22 06:55:311801 return is_being_destroyed_;
1802}
1803
[email protected]7f924832014-08-09 05:57:221804void WebContentsImpl::NotifyNavigationStateChanged(
1805 InvalidateTypes changed_flags) {
dalecurtis88c240072015-12-09 02:11:181806 // Notify the media observer of potential audibility changes.
Collin Bakeraf540cf2019-09-20 20:54:161807 if (changed_flags & INVALIDATE_TYPE_AUDIO) {
mlamouri44e4ef42016-01-20 18:42:271808 media_web_contents_observer_->MaybeUpdateAudibleState();
dalecurtisbc6572e12014-09-12 19:22:301809 }
1810
[email protected]d5f942ba2008-09-26 19:30:341811 if (delegate_)
1812 delegate_->NavigationStateChanged(this, changed_flags);
wjmaclean1dabf3e32016-05-13 23:34:441813
1814 if (GetOuterWebContents())
1815 GetOuterWebContents()->NotifyNavigationStateChanged(changed_flags);
[email protected]d5f942ba2008-09-26 19:30:341816}
1817
W. James MacLean6f34b042019-07-12 19:25:301818RenderFrameHostImpl* WebContentsImpl::GetFocusedFrameFromFocusedDelegate() {
1819 FrameTreeNode* focused_node =
1820 GetFocusedWebContents()->frame_tree_.GetFocusedFrame();
1821 return focused_node ? focused_node->current_frame_host() : nullptr;
1822}
1823
David Black9cca3592019-11-06 23:02:221824void WebContentsImpl::OnVerticalScrollDirectionChanged(
1825 viz::VerticalScrollDirection scroll_direction) {
Alexander Timin90c20c32020-08-12 15:28:321826 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1827 observer->DidChangeVerticalScrollDirection(scroll_direction);
1828 });
David Black9cca3592019-11-06 23:02:221829}
1830
Chris Hamiltondf0d72cd2018-05-29 16:23:531831void WebContentsImpl::OnAudioStateChanged() {
1832 // This notification can come from any embedded contents or from this
1833 // WebContents' stream monitor. Aggregate these signals to get the actual
1834 // state.
Jeremy Roman03ce13ce2020-05-29 22:16:571835 //
1836 // Note that guests may not be attached as inner contents, and so may need to
1837 // be checked separately.
Chris Hamiltondf0d72cd2018-05-29 16:23:531838 bool is_currently_audible =
1839 audio_stream_monitor_.IsCurrentlyAudible() ||
1840 (browser_plugin_embedder_ &&
Jeremy Roman03ce13ce2020-05-29 22:16:571841 browser_plugin_embedder_->AreAnyGuestsCurrentlyAudible()) ||
1842 AnyInnerWebContents(this, [](WebContents* inner_contents) {
1843 return inner_contents->IsCurrentlyAudible();
1844 });
Chris Hamiltondf0d72cd2018-05-29 16:23:531845 if (is_currently_audible == is_currently_audible_)
1846 return;
1847
1848 // Update internal state.
1849 is_currently_audible_ = is_currently_audible;
1850 was_ever_audible_ = was_ever_audible_ || is_currently_audible_;
1851
Gyuyoung Kim877e86d2020-07-21 04:01:021852 ExecutePageBroadcastMethod(base::BindRepeating(
1853 [](bool is_currently_audible, RenderViewHostImpl* rvh) {
1854 if (auto& broadcast = rvh->GetAssociatedPageBroadcast())
1855 broadcast->AudioStateChanged(is_currently_audible);
1856 },
1857 is_currently_audible_));
altimind8bd26c2016-11-04 11:44:541858
altiminec87fd1f2016-11-17 20:22:491859 // Notification for UI updates in response to the changed audio state.
Collin Bakeraf540cf2019-09-20 20:54:161860 NotifyNavigationStateChanged(INVALIDATE_TYPE_AUDIO);
Jan Rucka442c83f2017-08-08 13:27:541861
Chris Hamiltondf0d72cd2018-05-29 16:23:531862 // Ensure that audio state changes propagate from innermost to outermost
1863 // WebContents.
1864 if (GetOuterWebContents())
1865 GetOuterWebContents()->OnAudioStateChanged();
Tommy Steimel18360512017-11-01 00:38:191866
Alexander Timin90c20c32020-08-12 15:28:321867 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1868 observer->OnAudioStateChanged(is_currently_audible_);
1869 });
altimind8bd26c2016-11-04 11:44:541870}
1871
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411872base::TimeTicks WebContentsImpl::GetLastActiveTime() {
[email protected]9a890452014-02-13 22:21:021873 return last_active_time_;
[email protected]3e324142012-06-25 18:26:331874}
1875
[email protected]9e2e4632012-07-27 16:38:411876void WebContentsImpl::WasShown() {
Collin Baker989e0882019-11-01 01:27:171877 UpdateVisibilityAndNotifyPageAndView(Visibility::VISIBLE);
[email protected]be1f56ab2011-12-22 06:55:311878}
1879
[email protected]b172aee2012-04-10 17:05:261880void WebContentsImpl::WasHidden() {
Collin Baker989e0882019-11-01 01:27:171881 UpdateVisibilityAndNotifyPageAndView(Visibility::HIDDEN);
[email protected]375fa1b2012-05-22 22:05:371882}
1883
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411884bool WebContentsImpl::HasRecentInteractiveInputEvent() {
Daniel Cheng90196c82018-04-25 21:49:141885 static constexpr base::TimeDelta kMaxInterval =
1886 base::TimeDelta::FromSeconds(5);
1887 base::TimeDelta delta =
1888 ui::EventTimeForNow() - last_interactive_input_event_time_;
1889 // Note: the expectation is that the caller is typically expecting an input
1890 // event, e.g. validating that a WebUI message that requires a gesture is
Daniel Chenge81030b32019-07-17 20:20:231891 // actually attached to a gesture.
Daniel Cheng90196c82018-04-25 21:49:141892 return delta <= kMaxInterval;
1893}
1894
Avi Drissman738ea192018-08-29 20:24:161895void WebContentsImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1896 ignore_input_events_ = ignore_input_events;
1897}
1898
Bo Liu168c8642017-08-28 18:26:021899#if defined(OS_ANDROID)
Bo Liu16dd7b8322018-05-02 21:19:501900void WebContentsImpl::SetMainFrameImportance(
1901 ChildProcessImportance importance) {
1902 GetMainFrame()->GetRenderWidgetHost()->SetImportance(importance);
Bo Liu7c6779e92017-08-16 02:02:281903}
Bo Liu168c8642017-08-28 18:26:021904#endif
Bo Liu7c6779e92017-08-16 02:02:281905
ccameron8807c38f2015-01-17 00:29:191906void WebContentsImpl::WasOccluded() {
Collin Baker989e0882019-11-01 01:27:171907 UpdateVisibilityAndNotifyPageAndView(Visibility::OCCLUDED);
ccameron8807c38f2015-01-17 00:29:191908}
1909
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411910Visibility WebContentsImpl::GetVisibility() {
Francois Doraye6161152018-03-27 22:05:371911 return visibility_;
Francois Dorayfe4a1772018-02-17 04:17:091912}
1913
Rakina Zata Amni26e8d8a2020-08-05 06:06:061914bool WebContentsImpl::NeedToFireBeforeUnloadOrUnloadEvents() {
Alexander Timinc7bee322020-05-19 17:54:341915 if (!notify_disconnection_)
Alex Moshchuk6fcaca752018-07-14 02:13:591916 return false;
1917
1918 // Don't fire if the main frame's RenderViewHost indicates that beforeunload
1919 // and unload have already executed (e.g., after receiving a ClosePage ACK)
1920 // or should be ignored.
1921 if (GetRenderViewHost()->SuddenTerminationAllowed())
1922 return false;
1923
Alex Moshchukc78dbc722019-10-31 20:00:501924 // Check whether any frame in the frame tree needs to run beforeunload or
Rakina Zata Amni26e8d8a2020-08-05 06:06:061925 // unload-time event handlers.
Alex Moshchukc78dbc722019-10-31 20:00:501926 for (FrameTreeNode* node : frame_tree_.Nodes()) {
1927 RenderFrameHostImpl* rfh = node->current_frame_host();
1928
Rakina Zata Amni26e8d8a2020-08-05 06:06:061929 // No need to run beforeunload/unload-time events if the RenderFrame isn't
1930 // live.
Alex Moshchukc78dbc722019-10-31 20:00:501931 if (!rfh->IsRenderFrameLive())
1932 continue;
Rakina Zata Amni26e8d8a2020-08-05 06:06:061933 bool should_run_before_unload_handler =
Dave Tapuska97d22ab2019-12-03 17:56:361934 rfh->GetSuddenTerminationDisablerState(
Rakina Zata Amni26e8d8a2020-08-05 06:06:061935 blink::mojom::SuddenTerminationDisablerType::kBeforeUnloadHandler);
1936 bool should_run_unload_handler = rfh->GetSuddenTerminationDisablerState(
1937 blink::mojom::SuddenTerminationDisablerType::kUnloadHandler);
1938 bool should_run_page_hide_handler = rfh->GetSuddenTerminationDisablerState(
1939 blink::mojom::SuddenTerminationDisablerType::kPageHideHandler);
1940 auto* rvh = static_cast<RenderViewHostImpl*>(rfh->GetRenderViewHost());
1941 // If the tab is already hidden, we should not run visibilitychange
1942 // handlers.
1943 bool is_page_visible = rvh->GetPageLifecycleStateManager()
1944 ->CalculatePageLifecycleState()
1945 ->visibility == PageVisibilityState::kVisible;
1946
1947 bool should_run_visibility_change_handler =
1948 is_page_visible && rfh->GetSuddenTerminationDisablerState(
1949 blink::mojom::SuddenTerminationDisablerType::
1950 kVisibilityChangeHandler);
1951 if (should_run_before_unload_handler || should_run_unload_handler ||
1952 should_run_page_hide_handler || should_run_visibility_change_handler) {
Alex Moshchukc78dbc722019-10-31 20:00:501953 return true;
1954 }
Aditya Keerthi34f37e62019-03-08 15:54:531955 }
Alex Moshchuk6fcaca752018-07-14 02:13:591956
Alex Moshchukc78dbc722019-10-31 20:00:501957 return false;
[email protected]be1f56ab2011-12-22 06:55:311958}
1959
Chris Hamilton3b3e315d2018-09-19 13:16:211960void WebContentsImpl::DispatchBeforeUnload(bool auto_cancel) {
1961 auto before_unload_type =
1962 auto_cancel ? RenderFrameHostImpl::BeforeUnloadType::DISCARD
1963 : RenderFrameHostImpl::BeforeUnloadType::TAB_CLOSE;
1964 GetMainFrame()->DispatchBeforeUnload(before_unload_type, false);
[email protected]1c3f80bd2014-04-08 23:02:061965}
1966
W. James MacLean2539adb32019-12-13 00:40:441967bool WebContentsImpl::IsInnerWebContentsForGuest() {
1968 return !!browser_plugin_guest_;
1969}
1970
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:501971void WebContentsImpl::AttachInnerWebContents(
1972 std::unique_ptr<WebContents> inner_web_contents,
W. James MacLean62883982019-11-12 20:39:001973 RenderFrameHost* render_frame_host,
1974 bool is_full_page) {
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:501975 WebContentsImpl* inner_web_contents_impl =
1976 static_cast<WebContentsImpl*>(inner_web_contents.get());
1977 DCHECK(!inner_web_contents_impl->node_.outer_web_contents());
1978 auto* render_frame_host_impl =
1979 static_cast<RenderFrameHostImpl*>(render_frame_host);
Fergal Daly445af932020-06-02 06:37:231980 DCHECK_EQ(&frame_tree_, render_frame_host_impl->frame_tree());
Lucas Furukawa Gadani105de1e812018-05-31 19:38:391981
Yuzu Saijo3f86fb22020-06-11 03:51:101982 // Mark |render_frame_host_impl| as outer delegate frame.
1983 render_frame_host_impl->SetIsOuterDelegateFrame(true);
1984
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:501985 RenderFrameHostManager* inner_render_manager =
1986 inner_web_contents_impl->GetRenderManager();
1987 RenderFrameHostImpl* inner_main_frame =
1988 inner_render_manager->current_frame_host();
1989 RenderViewHostImpl* inner_render_view_host =
1990 inner_render_manager->current_host();
1991 auto* outer_render_manager =
1992 render_frame_host_impl->frame_tree_node()->render_manager();
lfg91a79e12016-04-01 23:52:191993
Lucas Furukawa Gadani105de1e812018-05-31 19:38:391994 // When attaching a WebContents as an inner WebContents, we need to replace
1995 // the Webcontents' view with a WebContentsViewChildFrame.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:501996 inner_web_contents_impl->view_.reset(new WebContentsViewChildFrame(
1997 inner_web_contents_impl,
1998 GetContentClient()->browser()->GetWebContentsViewDelegate(
1999 inner_web_contents_impl),
2000 &inner_web_contents_impl->render_view_host_delegate_view_));
Lucas Furukawa Gadani105de1e812018-05-31 19:38:392001
lfg91a79e12016-04-01 23:52:192002 // When the WebContents being initialized has an opener, the browser side
2003 // Render{View,Frame}Host must be initialized and the RenderWidgetHostView
2004 // created. This is needed because the usual initialization happens during
2005 // the first navigation, but when attaching a new window we don't navigate
2006 // before attaching. If the browser side is already initialized, the calls
2007 // below will just early return.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502008 inner_render_manager->InitRenderView(inner_render_view_host, nullptr);
2009 inner_main_frame->Init();
2010 if (!inner_render_manager->GetRenderWidgetHostView()) {
2011 inner_web_contents_impl->CreateRenderWidgetHostViewForRenderManager(
2012 inner_render_view_host);
2013 }
lfg91a79e12016-04-01 23:52:192014
Adithya Srinivasane6e7f842019-12-16 18:41:362015 inner_web_contents_impl->RecursivelyUnregisterFrameSinkIds();
2016
lazyboy6ec48b2a2015-06-29 15:18:142017 // Create a link to our outer WebContents.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502018 node_.AttachInnerWebContents(std::move(inner_web_contents),
2019 render_frame_host_impl);
lazyboy6ec48b2a2015-06-29 15:18:142020
lazyboy6ec48b2a2015-06-29 15:18:142021 // Create a proxy in top-level RenderFrameHostManager, pointing to the
2022 // SiteInstance of the outer WebContents. The proxy will be used to send
2023 // postMessage to the inner WebContents.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502024 auto* proxy = inner_render_manager->CreateOuterDelegateProxy(
2025 render_frame_host_impl->GetSiteInstance());
lazyboy6ec48b2a2015-06-29 15:18:142026
Lucas Furukawa Gadani99125822019-01-03 15:41:492027 // When attaching a GuestView as an inner WebContents, there should already be
2028 // a live RenderFrame, which has to be swapped. When attaching a portal, there
2029 // will not be a live RenderFrame before creating the proxy.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502030 if (render_frame_host_impl->IsRenderFrameLive()) {
2031 inner_render_manager->SwapOuterDelegateFrame(render_frame_host_impl, proxy);
Lucas Furukawa Gadani99125822019-01-03 15:41:492032
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502033 inner_web_contents_impl->ReattachToOuterWebContentsFrame();
Lucas Furukawa Gadani99125822019-01-03 15:41:492034 }
ekaramadadd882292016-06-08 15:22:562035
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502036 if (frame_tree_.GetFocusedFrame() ==
2037 render_frame_host_impl->frame_tree_node()) {
2038 inner_web_contents_impl->SetFocusedFrame(
2039 inner_web_contents_impl->frame_tree_.root(),
2040 render_frame_host_impl->GetSiteInstance());
avallee7529b2a2017-04-26 11:37:512041 }
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502042 outer_render_manager->set_attach_complete();
W. James MacLean62883982019-11-12 20:39:002043
2044 // If the inner WebContents is full frame, give it focus.
2045 if (is_full_page) {
2046 // There should only ever be one inner WebContents when |is_full_page| is
2047 // true, and it is the one we just attached.
2048 DCHECK_EQ(1u, node_.GetInnerWebContents().size());
2049 inner_web_contents_impl->SetAsFocusedWebContentsIfNecessary();
2050 }
Chris Hamilton16b5d1d2020-06-04 00:08:122051
Alexander Timin90c20c32020-08-12 15:28:322052 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2053 observer->InnerWebContentsAttached(inner_web_contents_impl,
2054 render_frame_host, is_full_page);
2055 });
lazyboy6ec48b2a2015-06-29 15:18:142056}
2057
Lucas Furukawa Gadani99125822019-01-03 15:41:492058std::unique_ptr<WebContents> WebContentsImpl::DetachFromOuterWebContents() {
Chris Hamilton16b5d1d2020-06-04 00:08:122059 auto* outer_web_contents = GetOuterWebContents();
2060 DCHECK(outer_web_contents);
Yuzu Saijo3f86fb22020-06-11 03:51:102061 GetMainFrame()->ParentOrOuterDelegateFrame()->SetIsOuterDelegateFrame(false);
Chris Hamilton16b5d1d2020-06-04 00:08:122062
Adithya Srinivasane6e7f842019-12-16 18:41:362063 RecursivelyUnregisterFrameSinkIds();
Lucas Gadanid29952582020-06-09 21:24:002064
2065 // Each RenderViewHost has a RenderWidgetHost which can have a
2066 // RenderWidgetHostView, and it needs to be re-created with the appropriate
2067 // platform view. It is important to re-create all child views, not only the
2068 // current one, since the view can be swapped due to a cross-origin
2069 // navigation.
2070 std::set<RenderViewHostImpl*> render_view_hosts;
2071 for (auto& render_view_host : GetFrameTree()->render_view_hosts()) {
2072 if (render_view_host.second->GetWidget() &&
2073 render_view_host.second->GetWidget()->GetView()) {
2074 DCHECK(render_view_host.second->GetWidget()
2075 ->GetView()
2076 ->IsRenderWidgetHostViewChildFrame());
2077 render_view_hosts.insert(render_view_host.second);
Kevin McNee6471a702020-01-27 18:23:072078 }
2079 }
Lucas Gadanid29952582020-06-09 21:24:002080
2081 for (auto* render_view_host : render_view_hosts)
2082 render_view_host->GetWidget()->GetView()->Destroy();
2083
Lucas Furukawa Gadani99125822019-01-03 15:41:492084 GetRenderManager()->DeleteOuterDelegateProxy(
2085 node_.OuterContentsFrameTreeNode()
2086 ->current_frame_host()
2087 ->GetSiteInstance());
2088 view_.reset(CreateWebContentsView(
2089 this, GetContentClient()->browser()->GetWebContentsViewDelegate(this),
2090 &render_view_host_delegate_view_));
danakjfc5184932019-09-12 18:08:322091 view_->CreateView(nullptr);
Lucas Furukawa Gadani99125822019-01-03 15:41:492092 std::unique_ptr<WebContents> web_contents =
2093 node_.DisconnectFromOuterWebContents();
2094 DCHECK_EQ(web_contents.get(), this);
2095 node_.SetFocusedWebContents(this);
Lucas Gadanid29952582020-06-09 21:24:002096
2097 for (auto* render_view_host : render_view_hosts)
2098 CreateRenderWidgetHostViewForRenderManager(render_view_host);
2099
Adithya Srinivasane6e7f842019-12-16 18:41:362100 RecursivelyRegisterFrameSinkIds();
Adithya Srinivasan6f0f67b2019-12-19 01:26:462101 // TODO(adithyas): |browser_plugin_embedder_ax_tree_id| should either not be
2102 // used for portals, or it should get a different name.
2103 GetMainFrame()->set_browser_plugin_embedder_ax_tree_id(ui::AXTreeIDUnknown());
2104 GetMainFrame()->UpdateAXTreeData();
Chris Hamilton16b5d1d2020-06-04 00:08:122105
2106 // Invoke on the *outer* web contents observers for symmetry.
Alexander Timin90c20c32020-08-12 15:28:322107 outer_web_contents->observers_.ForEachObserver(
2108 [&](WebContentsObserver* observer) {
2109 observer->InnerWebContentsDetached(this);
2110 });
Chris Hamilton16b5d1d2020-06-04 00:08:122111
Lucas Furukawa Gadani99125822019-01-03 15:41:492112 return web_contents;
2113}
2114
W. James MacLean2dc75ed42019-03-06 14:31:092115void WebContentsImpl::RecursivelyRegisterFrameSinkIds() {
Adithya Srinivasane6e7f842019-12-16 18:41:362116 for (auto* view : GetRenderWidgetHostViewsInWebContentsTree()) {
2117 auto* rwhvb = static_cast<RenderWidgetHostViewBase*>(view);
2118 if (rwhvb->IsRenderWidgetHostViewChildFrame())
2119 static_cast<RenderWidgetHostViewChildFrame*>(view)->RegisterFrameSinkId();
2120 }
2121}
W. James MacLean2dc75ed42019-03-06 14:31:092122
Adithya Srinivasane6e7f842019-12-16 18:41:362123void WebContentsImpl::RecursivelyUnregisterFrameSinkIds() {
2124 for (auto* view : GetRenderWidgetHostViewsInWebContentsTree()) {
2125 auto* rwhvb = static_cast<RenderWidgetHostViewBase*>(view);
2126 if (rwhvb->IsRenderWidgetHostViewChildFrame()) {
2127 static_cast<RenderWidgetHostViewChildFrame*>(view)
2128 ->UnregisterFrameSinkId();
2129 }
W. James MacLean2dc75ed42019-03-06 14:31:092130 }
2131}
2132
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:142133void WebContentsImpl::ReattachToOuterWebContentsFrame() {
2134 DCHECK(node_.outer_web_contents());
2135 auto* render_manager = GetRenderManager();
2136 auto* parent_frame =
2137 node_.OuterContentsFrameTreeNode()->current_frame_host()->GetParent();
2138 render_manager->SetRWHViewForInnerContents(
2139 render_manager->GetRenderWidgetHostView());
2140
W. James MacLean2dc75ed42019-03-06 14:31:092141 RecursivelyRegisterFrameSinkIds();
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:142142
2143 // Set up the the guest's AX tree to point back at the embedder's AX tree.
2144 GetMainFrame()->set_browser_plugin_embedder_ax_tree_id(
2145 parent_frame->GetAXTreeID());
2146 GetMainFrame()->UpdateAXTreeData();
2147}
2148
Lucas Gadani972985622020-05-28 20:52:512149void WebContentsImpl::DidActivatePortal(
2150 WebContentsImpl* predecessor_web_contents,
2151 base::TimeTicks activation_time) {
2152 DCHECK(predecessor_web_contents);
Kevin McNeef8eb64c2020-04-21 21:36:062153 NotifyInsidePortal(false);
Alexander Timin90c20c32020-08-12 15:28:322154 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2155 observer->DidActivatePortal(predecessor_web_contents, activation_time);
2156 });
Lucas Gadani972985622020-05-28 20:52:512157 GetDelegate()->WebContentsBecamePortal(predecessor_web_contents);
Kevin McNeef8eb64c2020-04-21 21:36:062158}
2159
Adithya Srinivasan11af2c52019-12-16 22:52:552160void WebContentsImpl::NotifyInsidePortal(bool inside_portal) {
Gyuyoung Kim1c029712020-07-22 09:21:062161 ExecutePageBroadcastMethod(base::BindRepeating(
2162 [](bool inside_portal, RenderViewHostImpl* rvh) {
2163 if (auto& broadcast = rvh->GetAssociatedPageBroadcast())
2164 broadcast->SetInsidePortal(inside_portal);
2165 },
2166 inside_portal));
Adithya Srinivasan11af2c52019-12-16 22:52:552167}
2168
dalecurtis6c58ed02016-10-28 23:02:372169void WebContentsImpl::DidChangeVisibleSecurityState() {
Emily Starkc663b0242019-04-26 19:34:452170 if (delegate_)
dalecurtis6c58ed02016-10-28 23:02:372171 delegate_->VisibleSecurityStateChanged(this);
Alexander Timin90c20c32020-08-12 15:28:322172 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2173 observer->DidChangeVisibleSecurityState();
2174 });
dalecurtis6c58ed02016-10-28 23:02:372175}
2176
Rakina Zata Amni4029b6d2020-07-28 02:36:202177const WebPreferences WebContentsImpl::ComputeWebPreferences() {
2178 TRACE_EVENT0("browser", "WebContentsImpl::ComputeWebPreferences");
2179 WebPreferences prefs;
2180
2181 const base::CommandLine& command_line =
2182 *base::CommandLine::ForCurrentProcess();
2183
2184 SetSlowWebPreferences(command_line, &prefs);
2185
2186 prefs.web_security_enabled =
2187 !command_line.HasSwitch(switches::kDisableWebSecurity);
2188
2189 prefs.remote_fonts_enabled =
2190 !command_line.HasSwitch(switches::kDisableRemoteFonts);
2191 prefs.application_cache_enabled =
2192 base::FeatureList::IsEnabled(blink::features::kAppCache);
2193 prefs.local_storage_enabled =
2194 !command_line.HasSwitch(switches::kDisableLocalStorage);
2195 prefs.databases_enabled =
2196 !command_line.HasSwitch(switches::kDisableDatabases);
2197
2198 prefs.webgl1_enabled = !command_line.HasSwitch(switches::kDisable3DAPIs) &&
2199 !command_line.HasSwitch(switches::kDisableWebGL);
2200 prefs.webgl2_enabled = !command_line.HasSwitch(switches::kDisable3DAPIs) &&
2201 !command_line.HasSwitch(switches::kDisableWebGL) &&
2202 !command_line.HasSwitch(switches::kDisableWebGL2);
2203
2204 prefs.pepper_3d_enabled = !command_line.HasSwitch(switches::kDisablePepper3d);
2205
2206 prefs.flash_3d_enabled = !command_line.HasSwitch(switches::kDisableFlash3d);
2207 prefs.flash_stage3d_enabled =
2208 !command_line.HasSwitch(switches::kDisableFlashStage3d);
2209 prefs.flash_stage3d_baseline_enabled =
2210 !command_line.HasSwitch(switches::kDisableFlashStage3d);
2211
2212 prefs.allow_file_access_from_file_urls =
2213 command_line.HasSwitch(switches::kAllowFileAccessFromFiles);
2214
2215 prefs.accelerated_2d_canvas_enabled =
2216 !command_line.HasSwitch(switches::kDisableAccelerated2dCanvas);
2217 prefs.new_canvas_2d_api_enabled =
Rakina Zata Amniea8d0c22020-07-30 17:22:502218 command_line.HasSwitch(switches::kEnableNewCanvas2DAPI) ||
2219 base::FeatureList::IsEnabled(features::kEnableNewCanvas2DAPI);
Rakina Zata Amni4029b6d2020-07-28 02:36:202220 prefs.antialiased_2d_canvas_disabled =
2221 command_line.HasSwitch(switches::kDisable2dCanvasAntialiasing);
2222 prefs.antialiased_clips_2d_canvas_enabled =
2223 !command_line.HasSwitch(switches::kDisable2dCanvasClipAntialiasing);
2224
2225 prefs.disable_ipc_flooding_protection =
2226 command_line.HasSwitch(switches::kDisableIpcFloodingProtection) ||
2227 command_line.HasSwitch(switches::kDisablePushStateThrottle);
2228
2229 prefs.accelerated_video_decode_enabled =
2230 !command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode);
2231
2232 std::string autoplay_policy = media::GetEffectiveAutoplayPolicy(command_line);
2233 if (autoplay_policy == switches::autoplay::kNoUserGestureRequiredPolicy) {
2234 prefs.autoplay_policy = AutoplayPolicy::kNoUserGestureRequired;
2235 } else if (autoplay_policy ==
2236 switches::autoplay::kUserGestureRequiredPolicy) {
2237 prefs.autoplay_policy = AutoplayPolicy::kUserGestureRequired;
2238 } else if (autoplay_policy ==
2239 switches::autoplay::kDocumentUserActivationRequiredPolicy) {
2240 prefs.autoplay_policy = AutoplayPolicy::kDocumentUserActivationRequired;
2241 } else {
2242 NOTREACHED();
2243 }
2244
2245 prefs.dont_send_key_events_to_javascript =
2246 base::FeatureList::IsEnabled(features::kDontSendKeyEventsToJavascript);
2247
2248// TODO(dtapuska): Enable barrel button selection drag support on Android.
2249// crbug.com/758042
2250#if defined(OS_WIN)
2251 prefs.barrel_button_for_drag_enabled =
2252 base::FeatureList::IsEnabled(features::kDirectManipulationStylus);
2253#endif // defined(OS_WIN)
2254
2255 prefs.touch_adjustment_enabled =
2256 !command_line.HasSwitch(switches::kDisableTouchAdjustment);
2257
2258 prefs.enable_scroll_animator =
2259 command_line.HasSwitch(switches::kEnableSmoothScrolling) ||
2260 (!command_line.HasSwitch(switches::kDisableSmoothScrolling) &&
2261 gfx::Animation::ScrollAnimationsEnabledBySystem());
2262
2263 prefs.prefers_reduced_motion = gfx::Animation::PrefersReducedMotion();
2264
2265 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
2266 GetRenderViewHost()->GetProcess()->GetID())) {
2267 prefs.loads_images_automatically = true;
2268 prefs.javascript_enabled = true;
2269 }
2270
2271 prefs.viewport_enabled = command_line.HasSwitch(switches::kEnableViewport);
2272
2273 if (IsOverridingUserAgent())
2274 prefs.viewport_meta_enabled = false;
2275
2276 prefs.main_frame_resizes_are_orientation_changes =
2277 command_line.HasSwitch(switches::kMainFrameResizesAreOrientationChanges);
2278
2279 prefs.spatial_navigation_enabled =
2280 command_line.HasSwitch(switches::kEnableSpatialNavigation);
2281
2282 if (IsSpatialNavigationDisabled())
2283 prefs.spatial_navigation_enabled = false;
2284
Rakina Zata Amni4029b6d2020-07-28 02:36:202285 prefs.disable_reading_from_canvas =
2286 command_line.HasSwitch(switches::kDisableReadingFromCanvas);
2287
2288 prefs.strict_mixed_content_checking =
2289 command_line.HasSwitch(switches::kEnableStrictMixedContentChecking);
2290
2291 prefs.strict_powerful_feature_restrictions = command_line.HasSwitch(
2292 switches::kEnableStrictPowerfulFeatureRestrictions);
2293
2294 const std::string blockable_mixed_content_group =
2295 base::FieldTrialList::FindFullName("BlockableMixedContent");
2296 prefs.strictly_block_blockable_mixed_content =
2297 blockable_mixed_content_group == "StrictlyBlockBlockableMixedContent";
2298
2299 const std::string plugin_mixed_content_status =
2300 base::FieldTrialList::FindFullName("PluginMixedContentStatus");
2301 prefs.block_mixed_plugin_content =
2302 plugin_mixed_content_status == "BlockableMixedContent";
2303
2304 prefs.v8_cache_options = GetV8CacheOptions();
2305
2306 prefs.user_gesture_required_for_presentation = !command_line.HasSwitch(
2307 switches::kDisableGestureRequirementForPresentation);
2308
2309 if (HideDownloadUI())
2310 prefs.hide_download_ui = true;
2311
2312 // `media_controls_enabled` is `true` by default.
2313 if (HasPersistentVideo())
2314 prefs.media_controls_enabled = false;
2315
2316#if defined(OS_ANDROID)
2317 display::Display display = display::Screen::GetScreen()->GetPrimaryDisplay();
2318 gfx::Size size = display.GetSizeInPixel();
2319 int min_width = size.width() < size.height() ? size.width() : size.height();
2320 prefs.device_scale_adjustment = GetDeviceScaleAdjustment(
2321 static_cast<int>(min_width / display.device_scale_factor()));
2322#endif // OS_ANDROID
2323
2324 GetContentClient()->browser()->OverrideWebkitPrefs(GetRenderViewHost(),
2325 &prefs);
2326 return prefs;
2327}
2328
2329void WebContentsImpl::SetSlowWebPreferences(
2330 const base::CommandLine& command_line,
2331 WebPreferences* prefs) {
2332 if (web_preferences_.get()) {
2333#define SET_FROM_CACHE(prefs, field) prefs->field = web_preferences_->field
2334
2335 SET_FROM_CACHE(prefs, touch_event_feature_detection_enabled);
2336 SET_FROM_CACHE(prefs, available_pointer_types);
2337 SET_FROM_CACHE(prefs, available_hover_types);
2338 SET_FROM_CACHE(prefs, primary_pointer_type);
2339 SET_FROM_CACHE(prefs, primary_hover_type);
2340 SET_FROM_CACHE(prefs, pointer_events_max_touch_points);
2341 SET_FROM_CACHE(prefs, number_of_cpu_cores);
2342
2343#if defined(OS_ANDROID)
2344 SET_FROM_CACHE(prefs, video_fullscreen_orientation_lock_enabled);
2345 SET_FROM_CACHE(prefs, video_rotate_to_fullscreen_enabled);
2346#endif
2347
2348#undef SET_FROM_CACHE
2349 } else {
2350 // Every prefs->field modified below should have a SET_FROM_CACHE entry
2351 // above.
2352
2353 // On Android, Touch event feature detection is enabled by default,
2354 // Otherwise default is disabled.
2355 std::string touch_enabled_default_switch =
2356 switches::kTouchEventFeatureDetectionDisabled;
2357#if defined(OS_ANDROID)
2358 touch_enabled_default_switch = switches::kTouchEventFeatureDetectionEnabled;
2359#endif // defined(OS_ANDROID)
2360 const std::string touch_enabled_switch =
2361 command_line.HasSwitch(switches::kTouchEventFeatureDetection)
2362 ? command_line.GetSwitchValueASCII(
2363 switches::kTouchEventFeatureDetection)
2364 : touch_enabled_default_switch;
2365
2366 prefs->touch_event_feature_detection_enabled =
2367 (touch_enabled_switch == switches::kTouchEventFeatureDetectionAuto)
2368 ? (ui::GetTouchScreensAvailability() ==
2369 ui::TouchScreensAvailability::ENABLED)
2370 : (touch_enabled_switch.empty() ||
2371 touch_enabled_switch ==
2372 switches::kTouchEventFeatureDetectionEnabled);
2373
2374 std::tie(prefs->available_pointer_types, prefs->available_hover_types) =
2375 ui::GetAvailablePointerAndHoverTypes();
2376 prefs->primary_pointer_type =
2377 ui::GetPrimaryPointerType(prefs->available_pointer_types);
2378 prefs->primary_hover_type =
2379 ui::GetPrimaryHoverType(prefs->available_hover_types);
2380
2381 prefs->pointer_events_max_touch_points = ui::MaxTouchPoints();
2382
2383 prefs->number_of_cpu_cores = base::SysInfo::NumberOfProcessors();
2384
2385#if defined(OS_ANDROID)
2386 const bool device_is_phone =
2387 ui::GetDeviceFormFactor() == ui::DEVICE_FORM_FACTOR_PHONE;
2388 prefs->video_fullscreen_orientation_lock_enabled = device_is_phone;
2389 prefs->video_rotate_to_fullscreen_enabled = device_is_phone;
2390#endif
2391 }
2392}
2393
2394void WebContentsImpl::OnWebPreferencesChanged() {
2395 // This is defensive code to avoid infinite loops due to code run inside
2396 // SetWebPreferences() accidentally updating more preferences and thus
2397 // calling back into this code. See crbug.com/398751 for one past example.
2398 if (updating_web_preferences_)
2399 return;
2400 updating_web_preferences_ = true;
2401 SetWebPreferences(ComputeWebPreferences());
2402#if defined(OS_ANDROID)
2403 for (FrameTreeNode* node : frame_tree_.Nodes()) {
2404 RenderFrameHostImpl* rfh = node->current_frame_host();
2405 if (rfh->is_local_root()) {
2406 if (auto* rwh = rfh->GetRenderWidgetHost())
2407 rwh->SetForceEnableZoom(web_preferences_->force_enable_zoom);
2408 }
2409 }
2410#endif
2411 updating_web_preferences_ = false;
2412}
2413
Ahmed Fakhryd70bf37b2018-04-04 17:07:242414void WebContentsImpl::NotifyPreferencesChanged() {
Rakina Zata Amni347b70902020-07-22 10:49:042415 // Recompute the WebPreferences based on the current state of the WebContents,
Rakina Zata Amni4029b6d2020-07-28 02:36:202416 // etc. Note that OnWebPreferencesChanged will also call SetWebPreferences and
2417 // send the updated WebPreferences to all RenderViews for this WebContents.
2418 OnWebPreferencesChanged();
Ahmed Fakhryd70bf37b2018-04-04 17:07:242419}
2420
Bruce Long1e3e1f542019-10-16 17:56:282421void WebContentsImpl::SyncRendererPrefs() {
Peter Marshall2dc74e92020-07-29 20:02:302422 blink::mojom::RendererPreferences renderer_preferences = GetRendererPrefs();
Bruce Long1e3e1f542019-10-16 17:56:282423 RenderViewHostImpl::GetPlatformSpecificPrefs(&renderer_preferences);
2424 SendPageMessage(
2425 new PageMsg_SetRendererPrefs(MSG_ROUTING_NONE, renderer_preferences));
2426}
2427
Alexander Timin1cc31f42020-05-12 16:26:012428void WebContentsImpl::OnCookiesAccessed(NavigationHandle* navigation,
2429 const CookieAccessDetails& details) {
Alexander Timin90c20c32020-08-12 15:28:322430 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2431 observer->OnCookiesAccessed(navigation, details);
2432 });
Alexander Timin1cc31f42020-05-12 16:26:012433}
2434
2435void WebContentsImpl::OnCookiesAccessed(RenderFrameHostImpl* rfh,
2436 const CookieAccessDetails& details) {
Alexander Timin90c20c32020-08-12 15:28:322437 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2438 observer->OnCookiesAccessed(rfh, details);
2439 });
Josh Karlindaba39322019-07-17 23:24:332440}
2441
[email protected]b172aee2012-04-10 17:05:262442void WebContentsImpl::Stop() {
dcheng57e39e22016-01-21 00:25:382443 for (FrameTreeNode* node : frame_tree_.Nodes())
2444 node->StopLoading();
Alexander Timin90c20c32020-08-12 15:28:322445 observers_.ForEachObserver(
2446 [&](WebContentsObserver* observer) { observer->NavigationStopped(); });
[email protected]0bfbf882011-12-22 18:19:272447}
2448
Francois Doray47f759d2018-06-11 18:13:512449void WebContentsImpl::SetPageFrozen(bool frozen) {
2450 // A visible page is never frozen.
2451 DCHECK_NE(Visibility::VISIBLE, GetVisibility());
2452
Yuzu Saijo4fa1e9a2020-05-20 02:53:262453 for (auto& entry : frame_tree_.render_view_hosts()) {
2454 entry.second->SetIsFrozen(frozen);
2455 }
Fadi Meawada6573e02018-03-10 00:52:112456}
2457
erikchen6c7df7f7a2018-05-03 18:13:592458std::unique_ptr<WebContents> WebContentsImpl::Clone() {
[email protected]14392a52012-05-02 20:28:442459 // We use our current SiteInstance since the cloned entry will use it anyway.
alexmose201c7cd2015-06-10 17:14:212460 // We pass our own opener so that the cloned page can access it if it was set
[email protected]ed245db2012-12-18 08:00:452461 // before.
[email protected]54944cde2012-12-09 09:24:592462 CreateParams create_params(GetBrowserContext(), GetSiteInstance());
Ian Clelland5cbaaf82017-11-27 22:00:032463 FrameTreeNode* opener = frame_tree_.root()->opener();
2464 RenderFrameHostImpl* opener_rfh = nullptr;
2465 if (opener)
2466 opener_rfh = opener->current_frame_host();
erikchen6c7df7f7a2018-05-03 18:13:592467 std::unique_ptr<WebContentsImpl> tc =
erikchen50735fd2018-05-05 15:08:332468 CreateWithOpener(create_params, opener_rfh);
Lucas Furukawa Gadani5553a152019-01-08 18:55:572469 tc->GetController().CopyStateFrom(&controller_, true);
Alexander Timin90c20c32020-08-12 15:28:322470 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2471 observer->DidCloneToNewWebContents(this, tc.get());
2472 });
[email protected]0bfbf882011-12-22 18:19:272473 return tc;
2474}
2475
[email protected]14392a52012-05-02 20:28:442476void WebContentsImpl::Observe(int type,
[email protected]8ff00d72012-10-23 19:12:212477 const NotificationSource& source,
2478 const NotificationDetails& details) {
[email protected]14392a52012-05-02 20:28:442479 switch (type) {
[email protected]8ff00d72012-10-23 19:12:212480 case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: {
2481 RenderWidgetHost* host = Source<RenderWidgetHost>(source).ptr();
[email protected]0b431992014-06-24 00:08:032482 RenderWidgetHostView* view = host->GetView();
2483 if (view == GetFullscreenRenderWidgetHostView()) {
2484 // We cannot just call view_->RestoreFocus() here. On some platforms,
2485 // attempting to focus the currently-invisible WebContentsView will be
2486 // flat-out ignored. Therefore, this boolean is used to track whether
2487 // we will request focus after the fullscreen widget has been
2488 // destroyed.
2489 fullscreen_widget_had_focus_at_shutdown_ = (view && view->HasFocus());
2490 } else {
alexmosc2a8cec2016-05-23 22:19:532491 for (auto i = pending_widget_views_.begin();
[email protected]0b431992014-06-24 00:08:032492 i != pending_widget_views_.end(); ++i) {
2493 if (host->GetView() == i->second) {
2494 pending_widget_views_.erase(i);
2495 break;
2496 }
[email protected]bafe6cd2012-05-23 23:09:502497 }
2498 }
2499 break;
2500 }
[email protected]14392a52012-05-02 20:28:442501 default:
2502 NOTREACHED();
2503 }
2504}
2505
[email protected]ec6c05f2013-10-23 18:41:572506WebContents* WebContentsImpl::GetWebContents() {
2507 return this;
2508}
2509
[email protected]54944cde2012-12-09 09:24:592510void WebContentsImpl::Init(const WebContents::CreateParams& params) {
[email protected]fa944cb82013-11-15 17:51:212511 // This is set before initializing the render manager since
[email protected]b0936d22013-11-28 06:47:362512 // RenderFrameHostManager::Init calls back into us via its delegate to ask if
[email protected]fa944cb82013-11-15 17:51:212513 // it should be hidden.
Francois Doraye6161152018-03-27 22:05:372514 visibility_ =
2515 params.initially_hidden ? Visibility::HIDDEN : Visibility::VISIBLE;
[email protected]d6fa88f2013-10-18 16:00:432516
Sebastien Marchand28cf23182018-06-20 02:39:352517 if (!params.last_active_time.is_null())
2518 last_active_time_ = params.last_active_time;
2519
dcheng3ce04b62015-10-26 23:30:552520 scoped_refptr<SiteInstance> site_instance = params.site_instance;
2521 if (!site_instance)
2522 site_instance = SiteInstance::Create(params.browser_context);
Lukasz Anforowicz3caa8372018-06-05 17:22:072523 if (params.desired_renderer_state == CreateParams::kNoRendererProcess) {
2524 static_cast<SiteInstanceImpl*>(site_instance.get())
2525 ->PreventAssociationWithSpareProcess();
2526 }
dcheng3ce04b62015-10-26 23:30:552527
Fergal Dalycb0c1fdf2020-03-16 07:13:492528 GetRenderManager()->InitRoot(site_instance.get(),
2529 params.renderer_initiated_creation);
lukasza464d8692016-02-22 19:26:322530
lukasza5140a412016-09-15 21:12:302531 // blink::FrameTree::setName always keeps |unique_name| empty in case of a
2532 // main frame - let's do the same thing here.
2533 std::string unique_name;
lukasza464d8692016-02-22 19:26:322534 frame_tree_.root()->SetFrameName(params.main_frame_name, unique_name);
[email protected]d1198fd2012-08-13 22:50:192535
[email protected]fc2b46b2014-05-03 16:33:452536 WebContentsViewDelegate* delegate =
2537 GetContentClient()->browser()->GetWebContentsViewDelegate(this);
2538
W. James MacLean2539adb32019-12-13 00:40:442539 if (browser_plugin_guest_) {
sky52a39e342016-12-17 17:23:222540 view_.reset(new WebContentsViewChildFrame(
2541 this, delegate, &render_view_host_delegate_view_));
2542 } else {
2543 view_.reset(CreateWebContentsView(this, delegate,
2544 &render_view_host_delegate_view_));
[email protected]d1198fd2012-08-13 22:50:192545 }
[email protected]fc2b46b2014-05-03 16:33:452546 CHECK(render_view_host_delegate_view_);
[email protected]d1198fd2012-08-13 22:50:192547 CHECK(view_.get());
2548
danakjfc5184932019-09-12 18:08:322549 view_->CreateView(params.context);
[email protected]d1198fd2012-08-13 22:50:192550
brettw4b461082016-11-19 18:55:162551#if BUILDFLAG(ENABLE_PLUGINS)
Yuzu Saijoa11069a2020-04-22 10:56:552552 plugin_content_origin_allowlist_.reset(
2553 new PluginContentOriginAllowlist(this));
tommyclieb25b2a2014-11-03 19:45:092554#endif
2555
[email protected]d1198fd2012-08-13 22:50:192556 registrar_.Add(this,
[email protected]8ff00d72012-10-23 19:12:212557 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
2558 NotificationService::AllBrowserContextsAndSources());
[email protected]f28ef9a32014-05-12 16:36:102559
leon.hane4db177a2017-02-07 14:19:162560 screen_orientation_provider_.reset(new ScreenOrientationProvider(this));
[email protected]01f83f92014-06-17 14:41:542561
mfomitchev2b8b066a2016-01-28 19:23:152562#if defined(OS_ANDROID)
Oksana Zhuravlova0b634332019-10-28 23:04:222563 DateTimeChooserAndroid::CreateForWebContents(this);
[email protected]583418cc2013-01-17 14:01:102564#endif
fsamuel7310a4262014-12-05 05:06:442565
2566 // BrowserPluginGuest::Init needs to be called after this WebContents has
W. James MacLean6e78da342019-12-13 15:13:232567 // a RenderWidgetHostViewChildFrame. That is, |view_->CreateView| above.
fsamuel7310a4262014-12-05 05:06:442568 if (browser_plugin_guest_)
2569 browser_plugin_guest_->Init();
nickf9acfbe2014-12-23 19:12:372570
2571 for (size_t i = 0; i < g_created_callbacks.Get().size(); i++)
2572 g_created_callbacks.Get().at(i).Run(this);
naskob21fe4872015-02-24 14:15:562573
2574 // If the WebContents creation was renderer-initiated, it means that the
2575 // corresponding RenderView and main RenderFrame have already been created.
2576 // Ensure observers are notified about this.
2577 if (params.renderer_initiated_creation) {
Fergal Dalybb2d6592020-06-02 05:02:332578 GetRenderViewHost()->GetWidget()->set_renderer_initialized(true);
Alex Moshchuk27caae82017-09-11 23:11:182579 GetRenderViewHost()->DispatchRenderViewCreated();
naskob21fe4872015-02-24 14:15:562580 GetRenderManager()->current_frame_host()->SetRenderFrameCreated(true);
2581 }
naskof5940b9f2015-03-02 23:04:052582
lof84501da082016-05-23 21:22:542583 // Create the renderer process in advance if requested.
Lukasz Anforowicz3caa8372018-06-05 17:22:072584 if (params.desired_renderer_state ==
2585 CreateParams::kInitializeAndWarmupRendererProcess) {
lof84501da082016-05-23 21:22:542586 if (!GetRenderManager()->current_frame_host()->IsRenderFrameLive()) {
2587 GetRenderManager()->InitRenderView(GetRenderViewHost(), nullptr);
2588 }
2589 }
2590
naskof5940b9f2015-03-02 23:04:052591 // Ensure that observers are notified of the creation of this WebContents's
2592 // main RenderFrameHost. It must be done here for main frames, since the
2593 // NotifySwappedFromRenderManager expects view_ to already be created and that
2594 // happens after RenderFrameHostManager::Init.
2595 NotifySwappedFromRenderManager(
2596 nullptr, GetRenderManager()->current_frame_host(), true);
Albert J. Wonge76bf0b82019-09-27 07:47:062597
2598 // For WebContents that are never shown, do critical initialization here which
2599 // would normally only happen when the WebContents is shown.
2600 if (params.is_never_visible) {
2601 // This has just been created so there can only be one frame. Thus it is
2602 // safe to initialize the root.
2603 GetMainFrame()->Init();
2604 }
[email protected]d1198fd2012-08-13 22:50:192605}
2606
[email protected]7fff43e2013-05-21 20:21:102607void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl* web_contents) {
2608 RemoveDestructionObserver(web_contents);
2609
[email protected]ceee8cd2013-03-08 04:59:512610 // Clear a pending contents that has been closed before being shown.
alexmosc2a8cec2016-05-23 22:19:532611 for (auto iter = pending_contents_.begin(); iter != pending_contents_.end();
[email protected]ceee8cd2013-03-08 04:59:512612 ++iter) {
Joel Hockey8c2011b22020-04-30 05:07:192613 if (iter->second.contents.get() != web_contents)
[email protected]ceee8cd2013-03-08 04:59:512614 continue;
erikchenbee5c9622018-04-27 19:30:252615
2616 // Someone else has deleted the WebContents. That should never happen!
2617 // TODO(erikchen): Fix semantics here. https://crbug.com/832879.
Joel Hockey8c2011b22020-04-30 05:07:192618 iter->second.contents.release();
[email protected]ceee8cd2013-03-08 04:59:512619 pending_contents_.erase(iter);
[email protected]ceee8cd2013-03-08 04:59:512620 return;
2621 }
2622 NOTREACHED();
[email protected]14392a52012-05-02 20:28:442623}
2624
[email protected]7fff43e2013-05-21 20:21:102625void WebContentsImpl::AddDestructionObserver(WebContentsImpl* web_contents) {
Jan Wilken Dörrie73c901e2019-06-12 09:02:322626 if (!base::Contains(destruction_observers_, web_contents)) {
[email protected]7fff43e2013-05-21 20:21:102627 destruction_observers_[web_contents] =
Jeremy Roman04f27c372017-10-27 15:20:552628 std::make_unique<DestructionObserver>(this, web_contents);
[email protected]7fff43e2013-05-21 20:21:102629 }
2630}
2631
2632void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl* web_contents) {
avia8cf81982016-08-12 20:28:462633 destruction_observers_.erase(web_contents);
[email protected]7fff43e2013-05-21 20:21:102634}
2635
[email protected]b172aee2012-04-10 17:05:262636void WebContentsImpl::AddObserver(WebContentsObserver* observer) {
[email protected]be1f56ab2011-12-22 06:55:312637 observers_.AddObserver(observer);
2638}
2639
[email protected]b172aee2012-04-10 17:05:262640void WebContentsImpl::RemoveObserver(WebContentsObserver* observer) {
[email protected]be1f56ab2011-12-22 06:55:312641 observers_.RemoveObserver(observer);
2642}
2643
[email protected]948481d2014-06-11 18:32:222644std::set<RenderWidgetHostView*>
2645WebContentsImpl::GetRenderWidgetHostViewsInTree() {
2646 std::set<RenderWidgetHostView*> set;
Carlos IL07f282f2020-05-15 22:58:292647 for (RenderFrameHost* rfh : GetAllFrames()) {
2648 if (RenderWidgetHostView* rwhv = static_cast<RenderFrameHostImpl*>(rfh)
2649 ->frame_tree_node()
2650 ->render_manager()
2651 ->GetRenderWidgetHostView()) {
lfgf949e0e2017-05-10 22:18:112652 set.insert(rwhv);
dchengafb53e22016-02-04 08:11:082653 }
[email protected]948481d2014-06-11 18:32:222654 }
[email protected]de3c5d82014-05-28 22:12:592655 return set;
2656}
2657
Adithya Srinivasane6e7f842019-12-16 18:41:362658std::set<RenderWidgetHostView*>
2659WebContentsImpl::GetRenderWidgetHostViewsInWebContentsTree() {
2660 std::set<RenderWidgetHostView*> result;
2661 GetRenderWidgetHostViewsInWebContentsTree(result);
2662 return result;
2663}
2664
2665void WebContentsImpl::GetRenderWidgetHostViewsInWebContentsTree(
2666 std::set<RenderWidgetHostView*>& result) {
2667 std::set<RenderWidgetHostView*> views = GetRenderWidgetHostViewsInTree();
2668 result.insert(views.begin(), views.end());
2669 for (auto* inner_web_contents : GetInnerWebContents()) {
2670 static_cast<WebContentsImpl*>(inner_web_contents)
2671 ->GetRenderWidgetHostViewsInWebContentsTree(result);
2672 }
2673}
2674
[email protected]b172aee2012-04-10 17:05:262675void WebContentsImpl::Activate() {
[email protected]d5f942ba2008-09-26 19:30:342676 if (delegate_)
2677 delegate_->ActivateContents(this);
2678}
2679
avi3e4b8512015-11-11 01:55:492680void WebContentsImpl::LostCapture(RenderWidgetHostImpl* render_widget_host) {
2681 if (!RenderViewHostImpl::From(render_widget_host))
2682 return;
2683
[email protected]63954792011-07-11 04:17:482684 if (delegate_)
2685 delegate_->LostCapture();
2686}
2687
Yue Ru Sun979c4b162019-11-06 16:11:042688ukm::SourceId
2689WebContentsImpl::GetUkmSourceIdForLastCommittedSourceIncludingSameDocument()
2690 const {
2691 return last_committed_source_id_including_same_document_;
2692}
2693
Ahmed Fakhryfaa32d22018-10-05 15:56:162694void WebContentsImpl::SetTopControlsShownRatio(
2695 RenderWidgetHostImpl* render_widget_host,
2696 float ratio) {
2697 if (!delegate_)
2698 return;
2699
2700 RenderFrameHostImpl* rfh = GetMainFrame();
2701 if (!rfh || render_widget_host != rfh->GetRenderWidgetHost())
2702 return;
2703
2704 delegate_->SetTopControlsShownRatio(this, ratio);
Ahmed Fakhry58e6ef542018-09-04 18:05:382705}
2706
Ahmed Fakhry58e6ef542018-09-04 18:05:382707void WebContentsImpl::SetTopControlsGestureScrollInProgress(bool in_progress) {
2708 if (delegate_)
2709 delegate_->SetTopControlsGestureScrollInProgress(in_progress);
2710}
2711
lazyboy63f5b312015-11-23 20:19:522712void WebContentsImpl::RenderWidgetCreated(
2713 RenderWidgetHostImpl* render_widget_host) {
2714 created_widgets_.insert(render_widget_host);
2715}
2716
[email protected]b24b68a2012-09-24 21:57:262717void WebContentsImpl::RenderWidgetDeleted(
2718 RenderWidgetHostImpl* render_widget_host) {
lazyboy63f5b312015-11-23 20:19:522719 // Note that |is_being_destroyed_| can be true at this point as
2720 // ~WebContentsImpl() calls RFHM::ClearRFHsPendingShutdown(), which might lead
2721 // us here.
2722 created_widgets_.erase(render_widget_host);
[email protected]b24b68a2012-09-24 21:57:262723
lazyboy63f5b312015-11-23 20:19:522724 if (is_being_destroyed_)
2725 return;
[email protected]44470a22013-01-24 01:21:542726
2727 if (render_widget_host &&
alexmosc9e76ec2016-05-16 22:59:372728 render_widget_host->GetRoutingID() == fullscreen_widget_routing_id_ &&
2729 render_widget_host->GetProcess()->GetID() ==
2730 fullscreen_widget_process_id_) {
[email protected]4aebbca2013-09-17 22:26:492731 if (delegate_ && delegate_->EmbedsFullscreenWidget())
mlamouri7a78d6fd2015-01-17 13:23:532732 delegate_->ExitFullscreenModeForTab(this);
Alexander Timin90c20c32020-08-12 15:28:322733 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2734 observer->DidDestroyFullscreenWidget();
2735 });
alexmosc9e76ec2016-05-16 22:59:372736 fullscreen_widget_process_id_ = ChildProcessHost::kInvalidUniqueID;
[email protected]44470a22013-01-24 01:21:542737 fullscreen_widget_routing_id_ = MSG_ROUTING_NONE;
[email protected]0b431992014-06-24 00:08:032738 if (fullscreen_widget_had_focus_at_shutdown_)
2739 view_->RestoreFocus();
[email protected]44470a22013-01-24 01:21:542740 }
lfgbee1e0a2016-06-08 21:24:212741
lfg7d4caad2017-03-22 09:01:452742 if (render_widget_host == mouse_lock_widget_)
lfgff8dfc8d2016-10-21 17:42:322743 LostMouseLock(mouse_lock_widget_);
Joe Downing192998b22018-03-22 15:51:362744
Joe Downingc1a57efe2018-05-09 18:23:542745 CancelKeyboardLock(render_widget_host);
[email protected]b24b68a2012-09-24 21:57:262746}
2747
miu9e14e492014-10-25 02:39:042748void WebContentsImpl::RenderWidgetGotFocus(
2749 RenderWidgetHostImpl* render_widget_host) {
calamity7fe55ce2015-04-10 03:59:372750 // Notify the observers if an embedded fullscreen widget was focused.
2751 if (delegate_ && render_widget_host && delegate_->EmbedsFullscreenWidget() &&
2752 render_widget_host->GetView() == GetFullscreenRenderWidgetHostView()) {
Michael Thiessen896405db2017-07-20 17:52:322753 NotifyWebContentsFocused(render_widget_host);
calamity7fe55ce2015-04-10 03:59:372754 }
miu9e14e492014-10-25 02:39:042755}
2756
zijiehe3bee08e22017-05-17 04:14:462757void WebContentsImpl::RenderWidgetLostFocus(
2758 RenderWidgetHostImpl* render_widget_host) {
Michael Thiessen896405db2017-07-20 17:52:322759 // Notify the observers if an embedded fullscreen widget lost focus.
2760 if (delegate_ && render_widget_host && delegate_->EmbedsFullscreenWidget() &&
2761 render_widget_host->GetView() == GetFullscreenRenderWidgetHostView()) {
2762 NotifyWebContentsLostFocus(render_widget_host);
2763 }
zijiehe3bee08e22017-05-17 04:14:462764}
2765
estaded0a0c992015-01-21 14:12:062766void WebContentsImpl::RenderWidgetWasResized(
rouslan2f5993f2015-01-29 00:18:312767 RenderWidgetHostImpl* render_widget_host,
2768 bool width_changed) {
creisc014b402015-04-23 16:41:452769 RenderFrameHostImpl* rfh = GetMainFrame();
estadece344ec2015-01-23 00:12:292770 if (!rfh || render_widget_host != rfh->GetRenderWidgetHost())
estaded0a0c992015-01-21 14:12:062771 return;
estaded0a0c992015-01-21 14:12:062772
Alexander Timin90c20c32020-08-12 15:28:322773 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2774 observer->MainFrameWasResized(width_changed);
2775 });
estaded0a0c992015-01-21 14:12:062776}
2777
skyf65d9bb2017-03-24 02:26:392778KeyboardEventProcessingResult WebContentsImpl::PreHandleKeyboardEvent(
2779 const NativeWebKeyboardEvent& event) {
W. James MacLeane1187272019-11-12 03:42:482780 auto* outermost_contents = GetOutermostWebContents();
2781 // TODO(wjmaclean): Generalize this to forward all key events to the outermost
2782 // delegate's handler.
Avi Drissman97aef042020-06-30 21:04:482783 if (outermost_contents != this && IsFullscreen() &&
W. James MacLeane1187272019-11-12 03:42:482784 event.windows_key_code == ui::VKEY_ESCAPE) {
2785 // When an inner WebContents has focus and is fullscreen, redirect <esc>
2786 // key events to the outermost WebContents so it can be handled by that
2787 // WebContents' delegate.
2788 if (outermost_contents->PreHandleKeyboardEvent(event) ==
2789 KeyboardEventProcessingResult::HANDLED) {
2790 return KeyboardEventProcessingResult::HANDLED;
2791 }
2792 }
skyf65d9bb2017-03-24 02:26:392793 return delegate_ ? delegate_->PreHandleKeyboardEvent(this, event)
2794 : KeyboardEventProcessingResult::NOT_HANDLED;
[email protected]63954792011-07-11 04:17:482795}
2796
Dave Tapuska344399e2019-09-09 15:18:262797bool WebContentsImpl::HandleMouseEvent(const blink::WebMouseEvent& event) {
2798 // Handle mouse button back/forward in the browser process after the render
2799 // process is done with the event. This ensures all renderer-initiated history
2800 // navigations can be treated consistently.
2801 if (event.GetType() == blink::WebInputEvent::Type::kMouseUp) {
2802 WebContentsImpl* outermost = GetOutermostWebContents();
2803 if (event.button == blink::WebPointerProperties::Button::kBack &&
2804 outermost->controller_.CanGoBack()) {
2805 outermost->controller_.GoBack();
2806 return true;
2807 } else if (event.button == blink::WebPointerProperties::Button::kForward &&
2808 outermost->controller_.CanGoForward()) {
2809 outermost->controller_.GoForward();
2810 return true;
2811 }
2812 }
2813 return false;
2814}
2815
Scott Violetd5caa872018-10-16 22:00:512816bool WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
[email protected]0b094002014-08-20 18:28:102817 if (browser_plugin_embedder_ &&
2818 browser_plugin_embedder_->HandleKeyboardEvent(event)) {
Scott Violetd5caa872018-10-16 22:00:512819 return true;
[email protected]0b094002014-08-20 18:28:102820 }
Scott Violetd5caa872018-10-16 22:00:512821 return delegate_ && delegate_->HandleKeyboardEvent(this, event);
[email protected]63954792011-07-11 04:17:482822}
2823
[email protected]d92026ef2014-03-03 21:04:132824bool WebContentsImpl::HandleWheelEvent(
[email protected]180ef242013-11-07 06:50:462825 const blink::WebMouseWheelEvent& event) {
Avi Drissman7c57be72020-07-29 20:09:462826#if !defined(OS_MAC)
lanweia93644f2015-01-21 22:00:332827 // On platforms other than Mac, control+mousewheel may change zoom. On Mac,
2828 // this isn't done for two reasons:
[email protected]bccc4472013-04-18 16:37:192829 // -the OS already has a gesture to do this through pinch-zoom
2830 // -if a user starts an inertial scroll, let's go, and presses control
2831 // (i.e. control+tab) then the OS's buffered scroll events will come in
2832 // with control key set which isn't what the user wants
Blink Reformat1c4d759e2017-04-09 16:34:542833 if (delegate_ && event.wheel_ticks_y &&
Ehsan Karamad0f83cb112018-09-06 22:07:362834 event.event_action == blink::WebMouseWheelEvent::EventAction::kPageZoom) {
w.shackleton49bcd392016-01-06 17:38:222835 // Count only integer cumulative scrolls as zoom events; this handles
2836 // smooth scroll and regular scroll device behavior.
Blink Reformat1c4d759e2017-04-09 16:34:542837 zoom_scroll_remainder_ += event.wheel_ticks_y;
w.shackleton49bcd392016-01-06 17:38:222838 int whole_zoom_scroll_remainder_ = std::lround(zoom_scroll_remainder_);
2839 zoom_scroll_remainder_ -= whole_zoom_scroll_remainder_;
2840 if (whole_zoom_scroll_remainder_ != 0) {
2841 delegate_->ContentsZoomChange(whole_zoom_scroll_remainder_ > 0);
2842 }
[email protected]fb3f066e2013-02-12 19:12:522843 return true;
2844 }
[email protected]bccc4472013-04-18 16:37:192845#endif
[email protected]fb3f066e2013-02-12 19:12:522846 return false;
2847}
2848
[email protected]04bce562014-01-30 05:34:542849bool WebContentsImpl::PreHandleGestureEvent(
2850 const blink::WebGestureEvent& event) {
[email protected]28042d32014-02-03 14:10:032851 return delegate_ && delegate_->PreHandleGestureEvent(this, event);
[email protected]04bce562014-01-30 05:34:542852}
2853
kenrb2a565f82015-09-02 20:24:592854RenderWidgetHostInputEventRouter* WebContentsImpl::GetInputEventRouter() {
wjmacleane31234f2015-12-14 17:20:452855 if (!is_being_destroyed_ && GetOuterWebContents())
2856 return GetOuterWebContents()->GetInputEventRouter();
2857
2858 if (!rwh_input_event_router_.get() && !is_being_destroyed_)
kenrb2a565f82015-09-02 20:24:592859 rwh_input_event_router_.reset(new RenderWidgetHostInputEventRouter);
2860 return rwh_input_event_router_.get();
2861}
2862
alexmos3fcd0ca2015-10-23 18:18:332863void WebContentsImpl::ReplicatePageFocus(bool is_focused) {
2864 // Focus loss may occur while this WebContents is being destroyed. Don't
2865 // send the message in this case, as the main frame's RenderFrameHost and
2866 // other state has already been cleared.
2867 if (is_being_destroyed_)
2868 return;
2869
2870 frame_tree_.ReplicatePageFocus(is_focused);
2871}
2872
alexmosc4cbacb2015-11-21 01:29:222873RenderWidgetHostImpl* WebContentsImpl::GetFocusedRenderWidgetHost(
2874 RenderWidgetHostImpl* receiving_widget) {
alexmosc4cbacb2015-11-21 01:29:222875 // Events for widgets other than the main frame (e.g., popup menus) should be
2876 // forwarded directly to the widget they arrived on.
2877 if (receiving_widget != GetMainFrame()->GetRenderWidgetHost())
2878 return receiving_widget;
alexmosc4d183e2015-11-06 00:46:522879
paulmeyerfeafc2d2017-04-25 21:46:402880 // If the focused WebContents is a guest WebContents, then get the focused
2881 // frame in the embedder WebContents instead.
W. James MacLean13d834d2019-12-04 16:06:452882 FrameTreeNode* focused_frame =
2883 GetFocusedWebContents()->frame_tree_.GetFocusedFrame();
lfg1453e412017-04-11 00:48:502884
alexmosc4d183e2015-11-06 00:46:522885 if (!focused_frame)
alexmosc4cbacb2015-11-21 01:29:222886 return receiving_widget;
alexmosc4d183e2015-11-06 00:46:522887
alexmos732ca3a2015-12-08 02:01:022888 // The view may be null if a subframe's renderer process has crashed while
2889 // the subframe has focus. Drop the event in that case. Do not give
2890 // it to the main frame, so that the user doesn't unexpectedly type into the
2891 // wrong frame if a focused subframe renderer crashes while they type.
2892 RenderWidgetHostView* view = focused_frame->current_frame_host()->GetView();
2893 if (!view)
2894 return nullptr;
2895
2896 return RenderWidgetHostImpl::From(view->GetRenderWidgetHost());
alexmosc4d183e2015-11-06 00:46:522897}
2898
avallee9993fca2016-11-17 06:16:502899RenderWidgetHostImpl* WebContentsImpl::GetRenderWidgetHostWithPageFocus() {
lfg1453e412017-04-11 00:48:502900 WebContentsImpl* focused_web_contents = GetFocusedWebContents();
2901
lfg1453e412017-04-11 00:48:502902 return focused_web_contents->GetMainFrame()->GetRenderWidgetHost();
avallee9993fca2016-11-17 06:16:502903}
2904
Avi Drissmand1d25652020-03-06 21:28:582905bool WebContentsImpl::CanEnterFullscreenMode() {
Avi Drissman33972942020-06-19 14:16:012906 // It's possible that this WebContents was spawned while blocking UI was on
2907 // the screen, or that it was downstream from a WebContents when UI was
2908 // blocked. Therefore, disqualify it from fullscreen if it or any upstream
2909 // WebContents has an active blocker.
2910 auto openers = GetAllOpeningWebContents(this);
2911 return std::all_of(openers.begin(), openers.end(), [](auto* opener) {
2912 return opener->fullscreen_blocker_count_ == 0;
2913 });
Avi Drissmand1d25652020-03-06 21:28:582914}
2915
Dave Tapuska3ed44192018-05-01 18:53:302916void WebContentsImpl::EnterFullscreenMode(
Mike Wasserman4ca09792020-05-29 17:44:432917 RenderFrameHost* requesting_frame,
Dave Tapuskaa4189512019-10-15 20:27:342918 const blink::mojom::FullscreenOptions& options) {
Avi Drissmand1d25652020-03-06 21:28:582919 DCHECK(CanEnterFullscreenMode());
2920
mlamouri7a78d6fd2015-01-17 13:23:532921 // This method is being called to enter renderer-initiated fullscreen mode.
2922 // Make sure any existing fullscreen widget is shut down first.
[email protected]4aebbca2013-09-17 22:26:492923 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
avi85a4cef2015-12-18 20:13:372924 if (widget_view) {
2925 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())
2926 ->ShutdownAndDestroyWidget(true);
2927 }
[email protected]4aebbca2013-09-17 22:26:492928
Joe Downing13dd76b2018-04-09 18:32:152929 if (delegate_) {
Mike Wasserman4ca09792020-05-29 17:44:432930 delegate_->EnterFullscreenModeForTab(requesting_frame, options);
mlamouri7a78d6fd2015-01-17 13:23:532931
Joe Downing13dd76b2018-04-09 18:32:152932 if (keyboard_lock_widget_)
2933 delegate_->RequestKeyboardLock(this, esc_key_locked_);
2934 }
2935
Alexander Timin90c20c32020-08-12 15:28:322936 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2937 observer->DidToggleFullscreenModeForTab(IsFullscreen(), false);
2938 });
Avi Drissman33972942020-06-19 14:16:012939 FullscreenContentsSet(GetBrowserContext())->insert(this);
mlamouri7a78d6fd2015-01-17 13:23:532940}
2941
bokanece34a82016-01-28 19:49:462942void WebContentsImpl::ExitFullscreenMode(bool will_cause_resize) {
mlamouri7a78d6fd2015-01-17 13:23:532943 // This method is being called to leave renderer-initiated fullscreen mode.
2944 // Make sure any existing fullscreen widget is shut down first.
2945 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
avi85a4cef2015-12-18 20:13:372946 if (widget_view) {
2947 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())
2948 ->ShutdownAndDestroyWidget(true);
2949 }
mlamouri7a78d6fd2015-01-17 13:23:532950
Joe Downing13dd76b2018-04-09 18:32:152951 if (delegate_) {
mlamouri7a78d6fd2015-01-17 13:23:532952 delegate_->ExitFullscreenModeForTab(this);
[email protected]657c8e02014-03-19 19:18:372953
Joe Downing13dd76b2018-04-09 18:32:152954 if (keyboard_lock_widget_)
2955 delegate_->CancelKeyboardLockRequest(this);
2956 }
2957
bokanece34a82016-01-28 19:49:462958 // The fullscreen state is communicated to the renderer through a resize
2959 // message. If the change in fullscreen state doesn't cause a view resize
2960 // then we must ensure web contents exit the fullscreen state by explicitly
2961 // sending a resize message. This is required for the situation of the browser
2962 // moving the view into a "browser fullscreen" state and then the contents
2963 // entering "tab fullscreen". Exiting the contents "tab fullscreen" then won't
2964 // have the side effect of the view resizing, hence the explicit call here is
2965 // required.
2966 if (!will_cause_resize) {
2967 if (RenderWidgetHostView* rwhv = GetRenderWidgetHostView()) {
2968 if (RenderWidgetHost* render_widget_host = rwhv->GetRenderWidgetHost())
Fady Samuel0b911822018-04-25 13:22:162969 render_widget_host->SynchronizeVisualProperties();
bokanece34a82016-01-28 19:49:462970 }
scheib3dcb6c932015-02-23 10:55:582971 }
2972
Arthur Sonzogni929d29f2018-09-17 14:19:442973 current_fullscreen_frame_ = nullptr;
Becca Hughese9e27952018-06-25 17:08:272974
Alexander Timin90c20c32020-08-12 15:28:322975 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2976 observer->DidToggleFullscreenModeForTab(IsFullscreen(), will_cause_resize);
2977 });
Becca Hughesd11d6502018-07-31 17:01:282978
2979 if (display_cutout_host_impl_)
2980 display_cutout_host_impl_->DidExitFullscreen();
Avi Drissman33972942020-06-19 14:16:012981
2982 FullscreenContentsSet(GetBrowserContext())->erase(this);
[email protected]8a5e0ca2011-08-25 06:30:472983}
2984
Becca Hughesfd5d8f892018-06-14 18:23:362985void WebContentsImpl::FullscreenStateChanged(RenderFrameHost* rfh,
2986 bool is_fullscreen) {
Arthur Sonzogni929d29f2018-09-17 14:19:442987 RenderFrameHostImpl* frame = static_cast<RenderFrameHostImpl*>(rfh);
Becca Hughesfd5d8f892018-06-14 18:23:362988
2989 if (is_fullscreen) {
Jan Wilken Dörrie531be7ca2019-06-07 10:05:572990 if (!base::Contains(fullscreen_frames_, frame)) {
Arthur Sonzogni929d29f2018-09-17 14:19:442991 fullscreen_frames_.insert(frame);
2992 FullscreenFrameSetUpdated();
Becca Hughesfd5d8f892018-06-14 18:23:362993 }
Arthur Sonzogni929d29f2018-09-17 14:19:442994 return;
2995 }
Becca Hughesfd5d8f892018-06-14 18:23:362996
Arthur Sonzogni929d29f2018-09-17 14:19:442997 // If |frame| is no longer in fullscreen, remove it and any descendants.
2998 // See https://fullscreen.spec.whatwg.org.
Arthur Sonzogni969a794e2018-10-11 08:56:092999 size_t size_before_deletion = fullscreen_frames_.size();
3000 base::EraseIf(fullscreen_frames_, [&](RenderFrameHostImpl* current) {
3001 return (current == frame || current->IsDescendantOf(frame));
Arthur Sonzogni929d29f2018-09-17 14:19:443002 });
3003
Arthur Sonzogni969a794e2018-10-11 08:56:093004 if (size_before_deletion != fullscreen_frames_.size())
Arthur Sonzogni929d29f2018-09-17 14:19:443005 FullscreenFrameSetUpdated();
3006}
3007
3008void WebContentsImpl::FullscreenFrameSetUpdated() {
3009 if (fullscreen_frames_.empty()) {
3010 current_fullscreen_frame_ = nullptr;
3011 return;
Becca Hughesfd5d8f892018-06-14 18:23:363012 }
3013
Arthur Sonzogni929d29f2018-09-17 14:19:443014 // Find the current fullscreen frame and call the observers.
3015 // If frame A is fullscreen, then frame B goes into inner fullscreen, then B
3016 // exits fullscreen - that will result in A being fullscreen.
3017 RenderFrameHostImpl* new_fullscreen_frame = *std::max_element(
3018 fullscreen_frames_.begin(), fullscreen_frames_.end(), FrameCompareDepth);
Becca Hughesfd5d8f892018-06-14 18:23:363019
Arthur Sonzogni929d29f2018-09-17 14:19:443020 // If we have already notified observers about this frame then we should not
3021 // fire the observers again.
3022 if (new_fullscreen_frame == current_fullscreen_frame_)
3023 return;
3024 current_fullscreen_frame_ = new_fullscreen_frame;
Becca Hughesfd5d8f892018-06-14 18:23:363025
Alexander Timin90c20c32020-08-12 15:28:323026 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3027 observer->DidAcquireFullscreen(new_fullscreen_frame);
3028 });
Arthur Sonzogni929d29f2018-09-17 14:19:443029 if (display_cutout_host_impl_)
3030 display_cutout_host_impl_->DidAcquireFullscreen(new_fullscreen_frame);
Becca Hughesfd5d8f892018-06-14 18:23:363031}
3032
Collin Baker989e0882019-11-01 01:27:173033void WebContentsImpl::UpdateVisibilityAndNotifyPageAndView(
3034 Visibility new_visibility) {
Collin Baker989e0882019-11-01 01:27:173035 // Only hide the page if there are no entities capturing screenshots
Collin Bakerc5259962019-11-14 17:51:583036 // or video (e.g. mirroring). If there are, apply the correct state of
3037 // kHidden or kHiddenButPainting.
3038 PageVisibilityState page_visibility;
3039 if (new_visibility == Visibility::VISIBLE || visible_capturer_count_ > 0)
3040 page_visibility = PageVisibilityState::kVisible;
3041 else if (hidden_capturer_count_ > 0)
3042 page_visibility = PageVisibilityState::kHiddenButPainting;
3043 else
3044 page_visibility = PageVisibilityState::kHidden;
Collin Baker989e0882019-11-01 01:27:173045 // If there are entities in Picture-in-Picture mode, don't activate
3046 // the "disable rendering" optimization.
Collin Bakerc5259962019-11-14 17:51:583047 const bool view_is_visible =
3048 page_visibility != PageVisibilityState::kHidden ||
3049 HasPictureInPictureVideo();
Collin Baker989e0882019-11-01 01:27:173050
Collin Bakerc5259962019-11-14 17:51:583051 if (page_visibility != PageVisibilityState::kHidden) {
Dana Friedcf3bc8e2019-11-13 20:00:243052 // We cannot show a page or capture video unless there is a valid renderer
3053 // associated with this web contents. The navigation controller for this
3054 // page must be set to active (allowing navigation to complete, a renderer
3055 // and its associated views to be created, etc.) if any of these conditions
3056 // holds.
3057 //
3058 // Previously, it was possible for browser-side code to try to capture video
3059 // from a restored tab (for a variety of reasons, including the browser
3060 // creating preview thumbnails) and the tab would never actually load. By
Collin Bakerc5259962019-11-14 17:51:583061 // keying this behavior off of |page_visibility| instead of just
Dana Friedcf3bc8e2019-11-13 20:00:243062 // |new_visibility| we avoid this case. See crbug.com/1020782 for more
3063 // context.
3064 controller_.SetActive(true);
3065
3066 // This shows the Page before showing the individual RenderWidgets, as
3067 // RenderWidgets will work to produce compositor frames and handle input
3068 // as soon as they are shown. But the Page and other classes do not expect
3069 // to be producing frames when the Page is hidden. So we make sure the Page
3070 // is shown first.
Yuzu Saijo232076f2020-05-29 07:14:023071 for (auto* rvh : GetRenderViewHostsIncludingBackForwardCached()) {
3072 rvh->SetVisibility(page_visibility);
Yuzu Saijobe024af02020-05-11 07:35:563073 }
Collin Baker98457b52019-11-06 21:34:293074 }
Collin Baker989e0882019-11-01 01:27:173075
3076 // |GetRenderWidgetHostView()| can be null if the user middle clicks a link to
3077 // open a tab in the background, then closes the tab before selecting it.
3078 // This is because closing the tab calls WebContentsImpl::Destroy(), which
3079 // removes the |GetRenderViewHost()|; then when we actually destroy the
3080 // window, OnWindowPosChanged() notices and calls WasHidden() (which
3081 // calls us).
3082 if (auto* view = GetRenderWidgetHostView()) {
3083 if (view_is_visible) {
3084 view->Show();
Collin Baker989e0882019-11-01 01:27:173085 } else if (new_visibility == Visibility::HIDDEN) {
3086 view->Hide();
3087 } else {
3088 view->WasOccluded();
3089 }
3090 }
3091
Carlos IL07f282f2020-05-15 22:58:293092 SetVisibilityForChildViews(view_is_visible);
Collin Baker989e0882019-11-01 01:27:173093
3094 // Make sure to call SetVisibilityAndNotifyObservers(VISIBLE) before notifying
3095 // the CrossProcessFrameConnector.
3096 if (new_visibility == Visibility::VISIBLE) {
3097 last_active_time_ = base::TimeTicks::Now();
3098 SetVisibilityAndNotifyObservers(new_visibility);
3099 }
3100
Collin Bakerc5259962019-11-14 17:51:583101 if (page_visibility == PageVisibilityState::kHidden) {
Collin Baker989e0882019-11-01 01:27:173102 // Similar to when showing the page, we only hide the page after
3103 // hiding the individual RenderWidgets.
Yuzu Saijo232076f2020-05-29 07:14:023104 for (auto* rvh : GetRenderViewHostsIncludingBackForwardCached()) {
3105 rvh->SetVisibility(page_visibility);
Yuzu Saijobe024af02020-05-11 07:35:563106 }
3107
Collin Baker989e0882019-11-01 01:27:173108 } else {
3109 for (FrameTreeNode* node : frame_tree_.Nodes()) {
3110 RenderFrameProxyHost* parent = node->render_manager()->GetProxyToParent();
3111 if (!parent)
3112 continue;
3113
3114 parent->cross_process_frame_connector()->DelegateWasShown();
3115 }
3116 }
3117
3118 if (new_visibility != Visibility::VISIBLE)
3119 SetVisibilityAndNotifyObservers(new_visibility);
3120}
3121
Clark DuValla0e42992018-09-17 17:00:113122#if defined(OS_ANDROID)
3123void WebContentsImpl::UpdateUserGestureCarryoverInfo() {
3124 if (delegate_)
3125 delegate_->UpdateUserGestureCarryoverInfo(this);
3126}
3127#endif
3128
Avi Drissman97aef042020-06-30 21:04:483129bool WebContentsImpl::IsFullscreen() {
[email protected]199bba6e2012-04-04 16:19:383130 return delegate_ ? delegate_->IsFullscreenForTabOrPending(this) : false;
[email protected]5d5f7af2011-10-01 01:38:123131}
3132
Malay Keshav87c42c02019-01-15 08:37:473133bool WebContentsImpl::ShouldShowStaleContentOnEviction() {
3134 return GetDelegate() && GetDelegate()->ShouldShowStaleContentOnEviction(this);
3135}
3136
danakj45d42452020-04-08 17:24:183137blink::mojom::DisplayMode WebContentsImpl::GetDisplayMode() const {
mikhail.pozdnyakovc0e251b2015-04-15 06:51:123138 return delegate_ ? delegate_->GetDisplayMode(this)
Eric Willigers052f0432019-10-04 04:06:573139 : blink::mojom::DisplayMode::kBrowser;
mikhail.pozdnyakovc0e251b2015-04-15 06:51:123140}
3141
avic3aa8422015-11-09 20:57:223142void WebContentsImpl::RequestToLockMouse(
3143 RenderWidgetHostImpl* render_widget_host,
3144 bool user_gesture,
lfgad8244352016-07-13 16:55:513145 bool last_unlocked_by_target,
3146 bool privileged) {
lfgf0cd46e2017-01-04 00:05:233147 for (WebContentsImpl* current = this; current;
3148 current = current->GetOuterWebContents()) {
3149 if (current->mouse_lock_widget_) {
James Hollyerd5c9de462020-03-10 19:02:453150 render_widget_host->GotResponseToLockMouseRequest(
3151 blink::mojom::PointerLockResult::kAlreadyLocked);
lfgf0cd46e2017-01-04 00:05:233152 return;
3153 }
[email protected]e9621112011-10-17 05:38:373154 }
avic3aa8422015-11-09 20:57:223155
lfgad8244352016-07-13 16:55:513156 if (privileged) {
lfgf0cd46e2017-01-04 00:05:233157 DCHECK(!GetOuterWebContents());
lfgad8244352016-07-13 16:55:513158 mouse_lock_widget_ = render_widget_host;
James Hollyerd5c9de462020-03-10 19:02:453159 render_widget_host->GotResponseToLockMouseRequest(
3160 blink::mojom::PointerLockResult::kSuccess);
lfgad8244352016-07-13 16:55:513161 return;
3162 }
3163
lfgbee1e0a2016-06-08 21:24:213164 bool widget_in_frame_tree = false;
3165 for (FrameTreeNode* node : frame_tree_.Nodes()) {
3166 if (node->current_frame_host()->GetRenderWidgetHost() ==
3167 render_widget_host) {
3168 widget_in_frame_tree = true;
3169 break;
3170 }
3171 }
3172
3173 if (widget_in_frame_tree && delegate_) {
lfgf0cd46e2017-01-04 00:05:233174 for (WebContentsImpl* current = this; current;
3175 current = current->GetOuterWebContents()) {
3176 current->mouse_lock_widget_ = render_widget_host;
3177 }
3178
avic3aa8422015-11-09 20:57:223179 delegate_->RequestToLockMouse(this, user_gesture, last_unlocked_by_target);
lfgbee1e0a2016-06-08 21:24:213180 } else {
James Hollyerd5c9de462020-03-10 19:02:453181 render_widget_host->GotResponseToLockMouseRequest(
3182 blink::mojom::PointerLockResult::kWrongDocument);
lfgbee1e0a2016-06-08 21:24:213183 }
[email protected]e9621112011-10-17 05:38:373184}
3185
avi3e4b8512015-11-11 01:55:493186void WebContentsImpl::LostMouseLock(RenderWidgetHostImpl* render_widget_host) {
lfgbee1e0a2016-06-08 21:24:213187 CHECK(mouse_lock_widget_);
lfgf0cd46e2017-01-04 00:05:233188
3189 if (mouse_lock_widget_->delegate()->GetAsWebContents() != this)
3190 return mouse_lock_widget_->delegate()->LostMouseLock(render_widget_host);
3191
lfgbee1e0a2016-06-08 21:24:213192 mouse_lock_widget_->SendMouseLockLost();
lfgf0cd46e2017-01-04 00:05:233193 for (WebContentsImpl* current = this; current;
3194 current = current->GetOuterWebContents()) {
3195 current->mouse_lock_widget_ = nullptr;
3196 }
avi3e4b8512015-11-11 01:55:493197
[email protected]e9621112011-10-17 05:38:373198 if (delegate_)
3199 delegate_->LostMouseLock();
3200}
3201
lfgad8244352016-07-13 16:55:513202bool WebContentsImpl::HasMouseLock(RenderWidgetHostImpl* render_widget_host) {
3203 // To verify if the mouse is locked, the mouse_lock_widget_ needs to be
3204 // assigned to the widget that requested the mouse lock, and the top-level
3205 // platform RenderWidgetHostView needs to hold the mouse lock from the OS.
Lucas Gadania0ea0172018-09-20 18:31:373206 auto* widget_host = GetTopLevelRenderWidgetHostView();
3207 return mouse_lock_widget_ == render_widget_host && widget_host &&
3208 widget_host->IsMouseLocked();
lfgad8244352016-07-13 16:55:513209}
3210
lfg84763c92017-02-16 18:55:153211RenderWidgetHostImpl* WebContentsImpl::GetMouseLockWidget() {
Lucas Gadania0ea0172018-09-20 18:31:373212 auto* widget_host = GetTopLevelRenderWidgetHostView();
3213 if ((widget_host && widget_host->IsMouseLocked()) ||
lfge2176fb2017-03-26 00:45:473214 (GetFullscreenRenderWidgetHostView() &&
Lucas Gadania0ea0172018-09-20 18:31:373215 GetFullscreenRenderWidgetHostView()->IsMouseLocked())) {
lfg84763c92017-02-16 18:55:153216 return mouse_lock_widget_;
Lucas Gadania0ea0172018-09-20 18:31:373217 }
lfg84763c92017-02-16 18:55:153218
3219 return nullptr;
3220}
3221
Joe Downing192998b22018-03-22 15:51:363222bool WebContentsImpl::RequestKeyboardLock(
Joe Downing13dd76b2018-04-09 18:32:153223 RenderWidgetHostImpl* render_widget_host,
3224 bool esc_key_locked) {
Joe Downing192998b22018-03-22 15:51:363225 DCHECK(render_widget_host);
Joe Downing192998b22018-03-22 15:51:363226 if (render_widget_host->delegate()->GetAsWebContents() != this) {
3227 NOTREACHED();
3228 return false;
3229 }
3230
3231 // KeyboardLock is only supported when called by the top-level browsing
3232 // context and is not supported in embedded content scenarios.
3233 if (GetOuterWebContents())
3234 return false;
3235
Joe Downing13dd76b2018-04-09 18:32:153236 esc_key_locked_ = esc_key_locked;
Joe Downing192998b22018-03-22 15:51:363237 keyboard_lock_widget_ = render_widget_host;
3238
Joe Downing13dd76b2018-04-09 18:32:153239 if (delegate_)
3240 delegate_->RequestKeyboardLock(this, esc_key_locked_);
Joe Downing192998b22018-03-22 15:51:363241 return true;
3242}
3243
3244void WebContentsImpl::CancelKeyboardLock(
3245 RenderWidgetHostImpl* render_widget_host) {
3246 if (!keyboard_lock_widget_ || render_widget_host != keyboard_lock_widget_)
3247 return;
3248
3249 RenderWidgetHostImpl* old_keyboard_lock_widget = keyboard_lock_widget_;
3250 keyboard_lock_widget_ = nullptr;
3251
Joe Downing13dd76b2018-04-09 18:32:153252 if (delegate_)
3253 delegate_->CancelKeyboardLockRequest(this);
3254
Joe Downing192998b22018-03-22 15:51:363255 old_keyboard_lock_widget->CancelKeyboardLock();
3256}
3257
3258RenderWidgetHostImpl* WebContentsImpl::GetKeyboardLockWidget() {
3259 return keyboard_lock_widget_;
3260}
3261
Dave Tapuskac3344362019-02-20 17:54:283262void WebContentsImpl::OnRenderFrameProxyVisibilityChanged(
3263 blink::mojom::FrameVisibility visibility) {
3264 switch (visibility) {
3265 case blink::mojom::FrameVisibility::kRenderedInViewport:
3266 WasShown();
3267 break;
3268 case blink::mojom::FrameVisibility::kNotRendered:
3269 WasHidden();
3270 break;
3271 case blink::mojom::FrameVisibility::kRenderedOutOfViewport:
3272 WasOccluded();
3273 break;
3274 }
ekaramada4f42692016-02-11 19:48:373275}
3276
Albert J. Wong65fe64d2019-09-20 02:48:143277RenderFrameHostDelegate* WebContentsImpl::CreateNewWindow(
csharrison95f01e922017-04-24 18:52:353278 RenderFrameHost* opener,
rockot5c478a72016-09-28 23:14:183279 const mojom::CreateNewWindowParams& params,
Albert J. Wong65fe64d2019-09-20 02:48:143280 bool is_new_browsing_instance,
Sergey Kuznetsov32257a22019-02-11 20:26:503281 bool has_user_gesture,
[email protected]97714c82012-06-06 10:15:133282 SessionStorageNamespace* session_storage_namespace) {
csharrison95f01e922017-04-24 18:52:353283 DCHECK(opener);
nick5ae4d2d2017-01-06 01:18:353284
csharrison95f01e922017-04-24 18:52:353285 int render_process_id = opener->GetProcess()->GetID();
csharrison95f01e922017-04-24 18:52:353286
Albert J. Wong65fe64d2019-09-20 02:48:143287 SiteInstance* source_site_instance = opener->GetSiteInstance();
nick5ae4d2d2017-01-06 01:18:353288
Aaron Colwelleb219982020-01-16 02:17:273289 const GURL source_site_url = source_site_instance->GetSiteURL();
[email protected]fdac6ade2013-07-20 01:06:303290 const std::string& partition_id =
Aaron Colwelleb219982020-01-16 02:17:273291 GetContentClient()->browser()->GetStoragePartitionIdForSite(
3292 GetBrowserContext(), source_site_url);
3293 {
3294 StoragePartition* partition = BrowserContext::GetStoragePartitionForSite(
3295 GetBrowserContext(), source_site_url);
3296 DOMStorageContextWrapper* dom_storage_context =
3297 static_cast<DOMStorageContextWrapper*>(
3298 partition->GetDOMStorageContext());
3299 SessionStorageNamespaceImpl* session_storage_namespace_impl =
3300 static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace);
3301 CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context));
3302 }
[email protected]dd6730412013-08-14 15:03:373303
Albert J. Wong1ceccef92019-10-08 08:25:203304 if (delegate_ && delegate_->IsWebContentsCreationOverridden(
3305 source_site_instance, params.window_container_type,
3306 opener->GetLastCommittedURL(), params.frame_name,
3307 params.target_url)) {
3308 return static_cast<WebContentsImpl*>(delegate_->CreateCustomWebContents(
3309 opener, source_site_instance, is_new_browsing_instance,
3310 opener->GetLastCommittedURL(), params.frame_name, params.target_url,
3311 partition_id, session_storage_namespace));
[email protected]dd6730412013-08-14 15:03:373312 }
3313
danakj22b4e8b2019-08-01 23:14:393314 bool renderer_started_hidden =
3315 params.disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB;
3316
Aaron Colwelleb219982020-01-16 02:17:273317 // We usually create the new window in the same BrowsingInstance (group of
3318 // script-related windows), by passing in the current SiteInstance. However,
3319 // if the opener is being suppressed (in a non-guest), we do not provide
3320 // a SiteInstance which causes a new one to get created in its own
3321 // BrowsingInstance.
3322 bool is_guest = BrowserPluginGuest::IsGuest(this);
3323 scoped_refptr<SiteInstance> site_instance =
3324 params.opener_suppressed && !is_guest ? nullptr : source_site_instance;
3325
[email protected]dd6730412013-08-14 15:03:373326 // Create the new web contents. This will automatically create the new
3327 // WebContentsView. In the future, we may want to create the view separately.
[email protected]fc72bb12013-06-02 21:13:463328 CreateParams create_params(GetBrowserContext(), site_instance.get());
nasko48321ca32015-07-02 20:44:123329 create_params.main_frame_name = params.frame_name;
alexmos4cf2aa32015-07-15 23:40:433330 create_params.opener_render_process_id = render_process_id;
csharrison95f01e922017-04-24 18:52:353331 create_params.opener_render_frame_id = opener->GetRoutingID();
[email protected]50d326e2014-05-20 17:59:063332 create_params.opener_suppressed = params.opener_suppressed;
danakj22b4e8b2019-08-01 23:14:393333 create_params.initially_hidden = renderer_started_hidden;
[email protected]50d326e2014-05-20 17:59:063334
Albert J. Wong65fe64d2019-09-20 02:48:143335 // Even though all codepaths leading here are in response to a renderer
3336 // tryng to open a new window, if the new window ends up in a different
3337 // browsing instance, then the RenderViewHost, RenderWidgetHost,
3338 // RenderFrameHost constellation is effectively browser initiated
3339 // the opener's process will not given the routing IDs for the new
3340 // objects.
3341 create_params.renderer_initiated_creation = !is_new_browsing_instance;
Albert J. Wong1ceccef92019-10-08 08:25:203342
Albert J. Wong65fe64d2019-09-20 02:48:143343 std::unique_ptr<WebContentsImpl> new_contents;
[email protected]c4538072013-03-18 02:17:553344 if (!is_guest) {
3345 create_params.context = view_->GetNativeView();
Albert J. Wong65fe64d2019-09-20 02:48:143346 new_contents = WebContentsImpl::Create(create_params);
3347 } else {
3348 new_contents = base::WrapUnique(static_cast<WebContentsImpl*>(
3349 GetBrowserPluginGuest()->CreateNewGuestWindow(create_params)));
[email protected]c4538072013-03-18 02:17:553350 }
Albert J. Wong65fe64d2019-09-20 02:48:143351 auto* new_contents_impl = new_contents.get();
danakje6c01622018-10-05 19:39:263352
3353 new_contents_impl->GetController().SetSessionStorageNamespace(
erikchenbee5c9622018-04-27 19:30:253354 partition_id, session_storage_namespace);
[email protected]d1198fd2012-08-13 22:50:193355
alexmos646fec02015-07-25 00:11:493356 // If the new frame has a name, make sure any SiteInstances that can find
3357 // this named frame have proxies for it. Must be called after
3358 // SetSessionStorageNamespace, since this calls CreateRenderView, which uses
3359 // GetSessionStorageNamespace.
3360 if (!params.frame_name.empty())
danakje6c01622018-10-05 19:39:263361 new_contents_impl->GetRenderManager()->CreateProxiesForNewNamedFrame();
alexmos646fec02015-07-25 00:11:493362
[email protected]c4538072013-03-18 02:17:553363 // Save the window for later if we're not suppressing the opener (since it
[email protected]d70bea92013-04-05 04:23:343364 // will be shown immediately).
3365 if (!params.opener_suppressed) {
3366 if (!is_guest) {
danakje6c01622018-10-05 19:39:263367 WebContentsView* new_view = new_contents_impl->view_.get();
[email protected]bafe6cd2012-05-23 23:09:503368
[email protected]d70bea92013-04-05 04:23:343369 // TODO(brettw): It seems bogus that we have to call this function on the
3370 // newly created object and give it one of its own member variables.
danakj22b4e8b2019-08-01 23:14:393371 RenderWidgetHostView* widget_view = new_view->CreateViewForWidget(
W. James MacLean13d834d2019-12-04 16:06:453372 new_contents_impl->GetRenderViewHost()->GetWidget());
danakj22b4e8b2019-08-01 23:14:393373 if (!renderer_started_hidden) {
3374 // RenderWidgets for frames always initialize as hidden. If the renderer
3375 // created this window as visible, then we show it here.
3376 widget_view->Show();
3377 }
[email protected]d70bea92013-04-05 04:23:343378 }
[email protected]bafe6cd2012-05-23 23:09:503379 // Save the created window associated with the route so we can show it
3380 // later.
Albert J. Wongcb004632018-07-10 22:58:253381 //
3382 // TODO(ajwong): This should be keyed off the RenderFrame routing id or the
3383 // FrameTreeNode id instead of the routing id of the Widget for the main
3384 // frame. https://crbug.com/545684
Fergal Daly052873a82020-03-11 14:45:493385 int32_t main_frame_routing_id = new_contents_impl->GetMainFrame()
3386 ->GetRenderWidgetHost()
3387 ->GetRoutingID();
3388 GlobalRoutingID id(render_process_id, main_frame_routing_id);
Joel Hockey8c2011b22020-04-30 05:07:193389 pending_contents_[id] =
3390 CreatedWindow(std::move(new_contents), params.target_url);
danakje6c01622018-10-05 19:39:263391 AddDestructionObserver(new_contents_impl);
[email protected]bafe6cd2012-05-23 23:09:503392 }
3393
3394 if (delegate_) {
Bryan McQuaded2b93c02017-07-14 22:26:313395 delegate_->WebContentsCreated(this, render_process_id,
3396 opener->GetRoutingID(), params.frame_name,
danakje6c01622018-10-05 19:39:263397 params.target_url, new_contents_impl);
[email protected]bafe6cd2012-05-23 23:09:503398 }
3399
Alexander Timin90c20c32020-08-12 15:28:323400 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3401 observer->DidOpenRequestedURL(new_contents_impl, opener, params.target_url,
3402 params.referrer.To<Referrer>(),
3403 params.disposition, ui::PAGE_TRANSITION_LINK,
3404 false, // started_from_context_menu
3405 true); // renderer_initiated
3406 });
pnolandaae574e2017-03-06 21:04:213407
Avi Drissmanba3b1b342017-08-29 18:16:133408 // Any new WebContents opened while this WebContents is in fullscreen can be
3409 // used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:453410 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
3411 // The new contents will be independent of this contents, so release the
3412 // fullscreen block.
3413 fullscreen_block.RunAndReset();
Avi Drissmanba3b1b342017-08-29 18:16:133414
[email protected]bafe6cd2012-05-23 23:09:503415 if (params.opener_suppressed) {
3416 // When the opener is suppressed, the original renderer cannot access the
3417 // new window. As a result, we need to show and navigate the window here.
[email protected]eda238a12012-09-07 23:44:003418 bool was_blocked = false;
erikchenbee5c9622018-04-27 19:30:253419
[email protected]eda238a12012-09-07 23:44:003420 if (delegate_) {
danakje6c01622018-10-05 19:39:263421 base::WeakPtr<WebContentsImpl> weak_new_contents =
3422 new_contents_impl->weak_factory_.GetWeakPtr();
nick0d558482017-02-13 22:27:223423
danakje6c01622018-10-05 19:39:263424 gfx::Rect initial_rect; // Report an empty initial rect.
Albert J. Wong65fe64d2019-09-20 02:48:143425 delegate_->AddNewContents(this, std::move(new_contents),
Joel Hockey891e88062020-04-30 05:38:443426 params.target_url, params.disposition,
3427 initial_rect, has_user_gesture, &was_blocked);
danakje6c01622018-10-05 19:39:263428 // The delegate may delete |new_contents_impl| during AddNewContents().
nick0d558482017-02-13 22:27:223429 if (!weak_new_contents)
Albert J. Wong65fe64d2019-09-20 02:48:143430 return nullptr;
[email protected]eda238a12012-09-07 23:44:003431 }
erikchenbee5c9622018-04-27 19:30:253432
[email protected]eda238a12012-09-07 23:44:003433 if (!was_blocked) {
Nasko Oskov83a8cf92018-10-19 14:58:563434 std::unique_ptr<NavigationController::LoadURLParams> load_params =
3435 std::make_unique<NavigationController::LoadURLParams>(
3436 params.target_url);
Nasko Oskov93e7c55c2018-12-19 01:59:293437 load_params->initiator_origin = opener->GetLastCommittedOrigin();
Lukasz Anforowiczd2629b42020-08-11 16:07:313438 // Avoiding setting |load_params->source_site_instance| when
3439 // |opener_suppressed| is true, because in that case we do not want to use
3440 // the old SiteInstance and/or BrowsingInstance. See also the test here:
3441 // NewPopupCOOP_SameOriginPolicyAndCrossOriginIframeSetsNoopener.
Leon Han963dc182018-11-06 05:41:483442 load_params->referrer = params.referrer.To<Referrer>();
Nasko Oskov83a8cf92018-10-19 14:58:563443 load_params->transition_type = ui::PAGE_TRANSITION_LINK;
3444 load_params->is_renderer_initiated = true;
Sergey Kuznetsov32257a22019-02-11 20:26:503445 load_params->has_user_gesture = has_user_gesture;
mariakhomenkoa4971c12015-07-21 19:04:373446
3447 if (delegate_ && !is_guest &&
3448 !delegate_->ShouldResumeRequestsForCreatedWindow()) {
Nasko Oskov83a8cf92018-10-19 14:58:563449 // We are in asynchronous add new contents path, delay navigation.
3450 DCHECK(!new_contents_impl->delayed_open_url_params_);
3451 new_contents_impl->delayed_load_url_params_ = std::move(load_params);
mariakhomenkoa4971c12015-07-21 19:04:373452 } else {
Nasko Oskov83a8cf92018-10-19 14:58:563453 new_contents_impl->controller_.LoadURLWithParams(*load_params.get());
Nasko Oskov28ebd5b2018-12-07 22:29:333454 if (!is_guest)
3455 new_contents_impl->Focus();
mariakhomenkoa4971c12015-07-21 19:04:373456 }
[email protected]eda238a12012-09-07 23:44:003457 }
[email protected]bafe6cd2012-05-23 23:09:503458 }
Albert J. Wong65fe64d2019-09-20 02:48:143459 return new_contents_impl;
[email protected]bafe6cd2012-05-23 23:09:503460}
3461
Dave Tapuskad9835622020-03-10 17:32:313462void WebContentsImpl::CreateNewWidget(
3463 int32_t render_process_id,
3464 int32_t widget_route_id,
Dave Tapuska8499eec2020-03-16 17:54:303465 mojo::PendingAssociatedReceiver<blink::mojom::WidgetHost> blink_widget_host,
3466 mojo::PendingAssociatedRemote<blink::mojom::Widget> blink_widget) {
Albert J. Wongf6e13ed2018-09-18 15:25:473467 CreateNewWidget(render_process_id, widget_route_id, /*is_fullscreen=*/false,
Dave Tapuskab686c1b2020-06-09 00:40:233468 std::move(blink_widget_host), std::move(blink_widget));
[email protected]bafe6cd2012-05-23 23:09:503469}
3470
Julie Jeongeun Kimcaacf9102019-09-12 02:13:053471void WebContentsImpl::CreateNewFullscreenWidget(
3472 int32_t render_process_id,
3473 int32_t widget_route_id,
Dave Tapuska8499eec2020-03-16 17:54:303474 mojo::PendingAssociatedReceiver<blink::mojom::WidgetHost> blink_widget_host,
3475 mojo::PendingAssociatedRemote<blink::mojom::Widget> blink_widget) {
Albert J. Wongf6e13ed2018-09-18 15:25:473476 CreateNewWidget(render_process_id, widget_route_id, /*is_fullscreen=*/true,
Dave Tapuskab686c1b2020-06-09 00:40:233477 std::move(blink_widget_host), std::move(blink_widget));
[email protected]bafe6cd2012-05-23 23:09:503478}
3479
Dave Tapuskad9835622020-03-10 17:32:313480void WebContentsImpl::CreateNewWidget(
3481 int32_t render_process_id,
3482 int32_t route_id,
3483 bool is_fullscreen,
Dave Tapuska8499eec2020-03-16 17:54:303484 mojo::PendingAssociatedReceiver<blink::mojom::WidgetHost> blink_widget_host,
3485 mojo::PendingAssociatedRemote<blink::mojom::Widget> blink_widget) {
kenrba26d15092016-02-10 22:00:253486 RenderProcessHost* process = RenderProcessHost::FromID(render_process_id);
kenrbb46f86a2015-12-07 07:53:233487 // A message to create a new widget can only come from an active process for
[email protected]a8504022013-12-04 20:23:513488 // this WebContentsImpl instance. If any other process sends the request,
3489 // it is invalid and the process must be terminated.
dcheng57e39e22016-01-21 00:25:383490 if (!HasMatchingProcess(&frame_tree_, render_process_id)) {
Lukasz Anforowicz6f746282018-01-04 23:24:513491 ReceivedBadMessage(process, bad_message::WCI_NEW_WIDGET_PROCESS_MISMATCH);
[email protected]a8504022013-12-04 20:23:513492 return;
3493 }
3494
Dave Tapuskab686c1b2020-06-09 00:40:233495 RenderWidgetHostImpl* widget_host =
3496 new RenderWidgetHostImpl(this, process, route_id, IsHidden(),
3497 std::make_unique<FrameTokenMessageQueue>());
Dave Tapuska8499eec2020-03-16 17:54:303498
3499 widget_host->BindWidgetInterfaces(std::move(blink_widget_host),
3500 std::move(blink_widget));
[email protected]cfd80b02014-05-01 17:46:483501 RenderWidgetHostViewBase* widget_view =
3502 static_cast<RenderWidgetHostViewBase*>(
danakj0b246942018-09-17 21:30:273503 view_->CreateViewForChildWidget(widget_host));
[email protected]83918ec2013-01-10 15:37:193504 if (!widget_view)
3505 return;
danakj0b246942018-09-17 21:30:273506 // Fullscreen child widgets are frames, other child widgets are popups, and
3507 // popups should not get activated.
3508 if (!is_fullscreen)
3509 widget_view->SetWidgetType(WidgetType::kPopup);
[email protected]bafe6cd2012-05-23 23:09:503510 // Save the created widget associated with the route so we can show it later.
Lukasz Anforowicz09060bdf72018-08-23 15:53:173511 pending_widget_views_[GlobalRoutingID(render_process_id, route_id)] =
alexmosc2a8cec2016-05-23 22:19:533512 widget_view;
[email protected]bafe6cd2012-05-23 23:09:503513}
3514
alexmosc2a8cec2016-05-23 22:19:533515void WebContentsImpl::ShowCreatedWindow(int process_id,
nick5ae4d2d2017-01-06 01:18:353516 int main_frame_widget_route_id,
[email protected]bafe6cd2012-05-23 23:09:503517 WindowOpenDisposition disposition,
bokan107a47f2015-02-03 23:23:393518 const gfx::Rect& initial_rect,
[email protected]bafe6cd2012-05-23 23:09:503519 bool user_gesture) {
danakje6c01622018-10-05 19:39:263520 // This method is the renderer requesting an existing top level window to
3521 // show a new top level window that the renderer created. Each top level
3522 // window is associated with a WebContents. In this case it was created
3523 // earlier but showing it was deferred until the renderer requested for it
3524 // to be shown. We find that previously created WebContents here.
3525 // TODO(danakj): Why do we defer this show step until the renderer asks for it
3526 // when it will always do so. What needs to happen in the renderer before we
3527 // reach here?
Joel Hockey8c2011b22020-04-30 05:07:193528 base::Optional<CreatedWindow> owned_created =
nick5ae4d2d2017-01-06 01:18:353529 GetCreatedWindow(process_id, main_frame_widget_route_id);
Joel Hockey8c2011b22020-04-30 05:07:193530
danakje6c01622018-10-05 19:39:263531 // The browser may have rejected the request to make a new window, or the
3532 // renderer could be sending an invalid route id. Ignore the request then.
Joel Hockey8c2011b22020-04-30 05:07:193533 if (!owned_created || !owned_created->contents)
danakje6c01622018-10-05 19:39:263534 return;
mariakhomenko44bdc4732015-04-29 01:55:383535
Joel Hockey8c2011b22020-04-30 05:07:193536 WebContentsImpl* created = owned_created->contents.get();
3537
danakje6c01622018-10-05 19:39:263538 // This uses the delegate for the WebContents where the window was created
3539 // from, to control how to show the newly created window.
3540 WebContentsDelegate* delegate = GetDelegate();
nick5ae4d2d2017-01-06 01:18:353541
danakje6c01622018-10-05 19:39:263542 // The delegate can be null in tests, so we must check for it :(.
3543 if (delegate) {
3544 // Mark the web contents as pending resume, then immediately do
3545 // the resume if the delegate wants it.
3546 created->is_resume_pending_ = true;
3547 if (delegate->ShouldResumeRequestsForCreatedWindow())
3548 created->ResumeLoadingCreatedWebContents();
3549
3550 base::WeakPtr<WebContentsImpl> weak_created =
3551 created->weak_factory_.GetWeakPtr();
Joel Hockey8c2011b22020-04-30 05:07:193552 delegate->AddNewContents(this, std::move(owned_created->contents),
Joel Hockey891e88062020-04-30 05:38:443553 std::move(owned_created->target_url), disposition,
3554 initial_rect, user_gesture, nullptr);
danakje6c01622018-10-05 19:39:263555 // The delegate may delete |created| during AddNewContents().
3556 if (!weak_created)
3557 return;
[email protected]eda238a12012-09-07 23:44:003558 }
danakje6c01622018-10-05 19:39:263559
3560 RenderWidgetHostImpl* rwh = created->GetMainFrame()->GetRenderWidgetHost();
3561 DCHECK_EQ(main_frame_widget_route_id, rwh->GetRoutingID());
3562 rwh->Send(new WidgetMsg_SetBounds_ACK(rwh->GetRoutingID()));
[email protected]bafe6cd2012-05-23 23:09:503563}
3564
alexmosc2a8cec2016-05-23 22:19:533565void WebContentsImpl::ShowCreatedWidget(int process_id,
Albert J. Wongf6e13ed2018-09-18 15:25:473566 int widget_route_id,
bokan107a47f2015-02-03 23:23:393567 const gfx::Rect& initial_rect) {
Albert J. Wongf6e13ed2018-09-18 15:25:473568 ShowCreatedWidget(process_id, widget_route_id, false, initial_rect);
[email protected]bafe6cd2012-05-23 23:09:503569}
3570
alexmosc2a8cec2016-05-23 22:19:533571void WebContentsImpl::ShowCreatedFullscreenWidget(int process_id,
Albert J. Wongf6e13ed2018-09-18 15:25:473572 int widget_route_id) {
3573 ShowCreatedWidget(process_id, widget_route_id, true, gfx::Rect());
[email protected]bafe6cd2012-05-23 23:09:503574}
3575
alexmosc2a8cec2016-05-23 22:19:533576void WebContentsImpl::ShowCreatedWidget(int process_id,
3577 int route_id,
[email protected]bafe6cd2012-05-23 23:09:503578 bool is_fullscreen,
bokan107a47f2015-02-03 23:23:393579 const gfx::Rect& initial_rect) {
[email protected]cfd80b02014-05-01 17:46:483580 RenderWidgetHostViewBase* widget_host_view =
alexmosc2a8cec2016-05-23 22:19:533581 static_cast<RenderWidgetHostViewBase*>(
3582 GetCreatedWidget(process_id, route_id));
[email protected]bafe6cd2012-05-23 23:09:503583 if (!widget_host_view)
3584 return;
[email protected]cfd80b02014-05-01 17:46:483585
W. James MacLeanec4125c2019-09-27 18:56:003586 // GetOutermostWebContents() returns |this| if there are no outer WebContents.
W. James MacLean3c5f50462019-10-28 16:24:213587 auto* outer_web_contents = GetOuterWebContents();
3588 auto* outermost_web_contents = GetOutermostWebContents();
W. James MacLeanec4125c2019-09-27 18:56:003589 RenderWidgetHostView* view =
W. James MacLean3c5f50462019-10-28 16:24:213590 outermost_web_contents->GetRenderWidgetHostView();
3591 // It's not entirely obvious why we need the transform only in the case where
3592 // the outer webcontents is not the same as the outermost webcontents. It may
3593 // be due to the fact that oopifs that are children of the mainframe get
3594 // correct values for their screenrects, but deeper cross-process frames do
3595 // not. Hopefully this can be resolved with https://crbug.com/928825.
3596 // Handling these cases separately is needed for http://crbug.com/1015298.
3597 bool needs_transform = this != outermost_web_contents &&
3598 outermost_web_contents != outer_web_contents;
W. James MacLeanec4125c2019-09-27 18:56:003599
3600 gfx::Rect transformed_rect(initial_rect);
3601 RenderWidgetHostView* this_view = GetRenderWidgetHostView();
W. James MacLean3c5f50462019-10-28 16:24:213602 if (needs_transform) {
W. James MacLeanec4125c2019-09-27 18:56:003603 // We need to transform the coordinates of initial_rect.
3604 gfx::Point origin =
3605 this_view->TransformPointToRootCoordSpace(initial_rect.origin());
3606 gfx::Point bottom_right =
3607 this_view->TransformPointToRootCoordSpace(initial_rect.bottom_right());
3608 transformed_rect =
3609 gfx::Rect(origin.x(), origin.y(), bottom_right.x() - origin.x(),
3610 bottom_right.y() - origin.y());
[email protected]cfd80b02014-05-01 17:46:483611 }
3612
danakj0b246942018-09-17 21:30:273613 // Fullscreen child widgets are frames, other child widgets are popups.
[email protected]4aebbca2013-09-17 22:26:493614 if (is_fullscreen) {
[email protected]d7f80ba2013-10-12 07:42:313615 DCHECK_EQ(MSG_ROUTING_NONE, fullscreen_widget_routing_id_);
[email protected]0b431992014-06-24 00:08:033616 view_->StoreFocus();
alexmosc9e76ec2016-05-16 22:59:373617 fullscreen_widget_process_id_ =
3618 widget_host_view->GetRenderWidgetHost()->GetProcess()->GetID();
[email protected]d7f80ba2013-10-12 07:42:313619 fullscreen_widget_routing_id_ = route_id;
[email protected]4aebbca2013-09-17 22:26:493620 if (delegate_ && delegate_->EmbedsFullscreenWidget()) {
3621 widget_host_view->InitAsChild(GetRenderWidgetHostView()->GetNativeView());
Mike Wasserman4ca09792020-05-29 17:44:433622 delegate_->EnterFullscreenModeForTab(GetMainFrame(),
Dave Tapuskaa4189512019-10-15 20:27:343623 blink::mojom::FullscreenOptions());
[email protected]4aebbca2013-09-17 22:26:493624 } else {
[email protected]cfd80b02014-05-01 17:46:483625 widget_host_view->InitAsFullscreen(view);
[email protected]4aebbca2013-09-17 22:26:493626 }
Alexander Timin90c20c32020-08-12 15:28:323627 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3628 observer->DidShowFullscreenWidget();
3629 });
[email protected]4aebbca2013-09-17 22:26:493630 if (!widget_host_view->HasFocus())
3631 widget_host_view->Focus();
3632 } else {
W. James MacLeanec4125c2019-09-27 18:56:003633 widget_host_view->InitAsPopup(view, transformed_rect);
[email protected]4aebbca2013-09-17 22:26:493634 }
[email protected]89054502012-06-03 10:29:243635
yiyixcb1fbc4f2018-03-16 19:54:083636 RenderWidgetHostImpl* render_widget_host_impl = widget_host_view->host();
[email protected]89054502012-06-03 10:29:243637 render_widget_host_impl->Init();
[email protected]d7f80ba2013-10-12 07:42:313638 // Only allow privileged mouse lock for fullscreen render widget, which is
3639 // used to implement Pepper Flash fullscreen.
3640 render_widget_host_impl->set_allow_privileged_mouse_lock(is_fullscreen);
[email protected]bafe6cd2012-05-23 23:09:503641}
3642
Joel Hockey8c2011b22020-04-30 05:07:193643base::Optional<CreatedWindow> WebContentsImpl::GetCreatedWindow(
nick5ae4d2d2017-01-06 01:18:353644 int process_id,
3645 int main_frame_widget_route_id) {
Lukasz Anforowicz09060bdf72018-08-23 15:53:173646 auto key = GlobalRoutingID(process_id, main_frame_widget_route_id);
nick5ae4d2d2017-01-06 01:18:353647 auto iter = pending_contents_.find(key);
[email protected]bafe6cd2012-05-23 23:09:503648
3649 // Certain systems can block the creation of new windows. If we didn't succeed
3650 // in creating one, just return NULL.
alexmosc2a8cec2016-05-23 22:19:533651 if (iter == pending_contents_.end())
Joel Hockey8c2011b22020-04-30 05:07:193652 return base::nullopt;
[email protected]bafe6cd2012-05-23 23:09:503653
Joel Hockey8c2011b22020-04-30 05:07:193654 CreatedWindow result = std::move(iter->second);
3655 WebContentsImpl* new_contents = result.contents.get();
nick5ae4d2d2017-01-06 01:18:353656 pending_contents_.erase(key);
Joel Hockey8c2011b22020-04-30 05:07:193657 RemoveDestructionObserver(new_contents);
[email protected]bafe6cd2012-05-23 23:09:503658
[email protected]d70bea92013-04-05 04:23:343659 // Don't initialize the guest WebContents immediately.
Joel Hockey8c2011b22020-04-30 05:07:193660 if (BrowserPluginGuest::IsGuest(new_contents))
3661 return result;
[email protected]d70bea92013-04-05 04:23:343662
Lukasz Anforowicz5510ed652018-06-06 16:16:193663 if (!new_contents->GetMainFrame()->GetProcess()->IsInitializedAndNotDead() ||
nick5ae4d2d2017-01-06 01:18:353664 !new_contents->GetMainFrame()->GetView()) {
Joel Hockey8c2011b22020-04-30 05:07:193665 return base::nullopt;
nick5ae4d2d2017-01-06 01:18:353666 }
[email protected]bafe6cd2012-05-23 23:09:503667
Joel Hockey8c2011b22020-04-30 05:07:193668 return result;
[email protected]bafe6cd2012-05-23 23:09:503669}
3670
alexmosc2a8cec2016-05-23 22:19:533671RenderWidgetHostView* WebContentsImpl::GetCreatedWidget(int process_id,
3672 int route_id) {
Lukasz Anforowicz09060bdf72018-08-23 15:53:173673 auto iter = pending_widget_views_.find(GlobalRoutingID(process_id, route_id));
[email protected]bafe6cd2012-05-23 23:09:503674 if (iter == pending_widget_views_.end()) {
3675 DCHECK(false);
alexmosc2a8cec2016-05-23 22:19:533676 return nullptr;
[email protected]bafe6cd2012-05-23 23:09:503677 }
3678
3679 RenderWidgetHostView* widget_host_view = iter->second;
Lukasz Anforowicz09060bdf72018-08-23 15:53:173680 pending_widget_views_.erase(GlobalRoutingID(process_id, route_id));
[email protected]bafe6cd2012-05-23 23:09:503681
3682 RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
Lukasz Anforowicz5510ed652018-06-06 16:16:193683 if (!widget_host->GetProcess()->IsInitializedAndNotDead()) {
[email protected]bafe6cd2012-05-23 23:09:503684 // The view has gone away or the renderer crashed. Nothing to do.
alexmosc2a8cec2016-05-23 22:19:533685 return nullptr;
[email protected]bafe6cd2012-05-23 23:09:503686 }
3687
3688 return widget_host_view;
3689}
3690
[email protected]f13b4202012-06-12 23:53:233691void WebContentsImpl::RequestMediaAccessPermission(
[email protected]33662e52013-01-07 21:31:093692 const MediaStreamRequest& request,
Mark Pilgrim57499082018-06-12 12:38:303693 MediaResponseCallback callback) {
[email protected]d19b84b2014-03-14 11:52:373694 if (delegate_) {
Mark Pilgrim57499082018-06-12 12:38:303695 delegate_->RequestMediaAccessPermission(this, request, std::move(callback));
[email protected]d19b84b2014-03-14 11:52:373696 } else {
Antonio Gomes0d42960a2019-06-05 12:35:513697 std::move(callback).Run(
3698 blink::MediaStreamDevices(),
3699 blink::mojom::MediaStreamRequestResult::FAILED_DUE_TO_SHUTDOWN,
3700 std::unique_ptr<MediaStreamUI>());
[email protected]d19b84b2014-03-14 11:52:373701 }
[email protected]f13b4202012-06-12 23:53:233702}
3703
Chandan Padhia4b8bcb72017-09-12 16:41:043704bool WebContentsImpl::CheckMediaAccessPermission(
Raymes Khouryad7c24a12018-03-05 23:22:583705 RenderFrameHost* render_frame_host,
Chandan Padhia4b8bcb72017-09-12 16:41:043706 const url::Origin& security_origin,
Antonio Gomesc8b734b2019-06-05 18:22:163707 blink::mojom::MediaStreamType type) {
3708 DCHECK(type == blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE ||
3709 type == blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE);
Chandan Padhia4b8bcb72017-09-12 16:41:043710 return delegate_ && delegate_->CheckMediaAccessPermission(
Raymes Khouryad7c24a12018-03-05 23:22:583711 render_frame_host, security_origin.GetURL(), type);
grunell657d4d82014-09-18 00:09:433712}
3713
Guido Urdaneta73fa6632019-01-14 18:46:263714std::string WebContentsImpl::GetDefaultMediaDeviceID(
Antonio Gomesc8b734b2019-06-05 18:22:163715 blink::mojom::MediaStreamType type) {
guidou8a440b842017-01-30 13:58:433716 if (!delegate_)
3717 return std::string();
3718 return delegate_->GetDefaultMediaDeviceID(this, type);
3719}
3720
[email protected]cc9200432013-07-23 23:02:403721SessionStorageNamespace* WebContentsImpl::GetSessionStorageNamespace(
3722 SiteInstance* instance) {
3723 return controller_.GetSessionStorageNamespace(instance);
3724}
3725
[email protected]6de7fc482014-06-06 10:46:443726SessionStorageNamespaceMap WebContentsImpl::GetSessionStorageNamespaceMap() {
3727 return controller_.GetSessionStorageNamespaceMap();
3728}
3729
[email protected]9b159a52013-10-03 17:24:553730FrameTree* WebContentsImpl::GetFrameTree() {
3731 return &frame_tree_;
3732}
3733
aelias5252baa2016-04-10 01:18:023734bool WebContentsImpl::IsOverridingUserAgent() {
3735 return GetController().GetVisibleEntry() &&
3736 GetController().GetVisibleEntry()->GetIsOverridingUserAgent();
3737}
3738
avi85ee8362016-10-08 02:09:083739bool WebContentsImpl::IsJavaScriptDialogShowing() const {
3740 return is_showing_javascript_dialog_;
3741}
3742
avic031d392017-03-03 03:09:423743bool WebContentsImpl::ShouldIgnoreUnresponsiveRenderer() {
Dominique Fauteux-Chapleau99244382020-07-08 20:37:003744 if (suppress_unresponsive_renderer_count_ > 0)
3745 return true;
3746
avic031d392017-03-03 03:09:423747 // Ignore unresponsive renderers if the debugger is attached to them since the
3748 // unresponsiveness might be a result of the renderer sitting on a breakpoint.
3749 //
David Bienvenu525f8a02019-02-15 02:02:423750#ifdef OS_WIN
3751 // Check if a windows debugger is attached to the renderer process.
3752 base::ProcessHandle process_handle =
3753 GetMainFrame()->GetProcess()->GetProcess().Handle();
3754 BOOL debugger_present = FALSE;
3755 if (CheckRemoteDebuggerPresent(process_handle, &debugger_present) &&
3756 debugger_present)
3757 return true;
3758#endif // OS_WIN
3759
avic031d392017-03-03 03:09:423760 // TODO(pfeldman): Fix this to only return true if the renderer is *actually*
3761 // sitting on a breakpoint. https://crbug.com/684202
3762 return DevToolsAgentHost::IsDebuggerAttached(this);
3763}
3764
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:413765ui::AXMode WebContentsImpl::GetAccessibilityMode() {
[email protected]95640212014-07-26 18:14:303766 return accessibility_mode_;
3767}
3768
Mario Sanchez Prada5d7f1ac2020-07-16 17:18:403769void WebContentsImpl::AXTreeIDForMainFrameHasChanged() {
3770 RenderWidgetHostViewBase* rwhv =
3771 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
3772 if (rwhv)
3773 rwhv->SetMainFrameAXTreeID(GetMainFrame()->GetAXTreeID());
3774
Alexander Timin90c20c32020-08-12 15:28:323775 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3776 observer->AXTreeIDForMainFrameHasChanged();
3777 });
Mario Sanchez Prada5d7f1ac2020-07-16 17:18:403778}
3779
Dominic Mazzonia7b0edb22017-08-09 16:32:513780void WebContentsImpl::AccessibilityEventReceived(
Dominic Mazzoniccbaa9b2018-06-06 07:44:233781 const AXEventNotificationDetails& details) {
Alexander Timin90c20c32020-08-12 15:28:323782 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3783 observer->AccessibilityEventReceived(details);
3784 });
[email protected]31a71eaf2014-03-13 01:47:363785}
3786
dmazzoni2400c462016-08-23 15:07:133787void WebContentsImpl::AccessibilityLocationChangesReceived(
3788 const std::vector<AXLocationChangeNotificationDetails>& details) {
Alexander Timin90c20c32020-08-12 15:28:323789 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3790 observer->AccessibilityLocationChangesReceived(details);
3791 });
dmazzoni2400c462016-08-23 15:07:133792}
3793
Abigail Kleinabb428332019-09-13 18:26:213794base::string16 WebContentsImpl::DumpAccessibilityTree(
3795 bool internal,
3796 std::vector<AccessibilityTreeFormatter::PropertyFilter> property_filters) {
James Wallace-Leeeafc94cb92018-07-23 21:35:093797 auto* ax_mgr = GetOrCreateRootBrowserAccessibilityManager();
3798 DCHECK(ax_mgr);
Lei Zhangc98caa3822019-11-07 19:17:273799 return AccessibilityTreeFormatterBase::DumpAccessibilityTreeFromManager(
Abigail Kleinabb428332019-09-13 18:26:213800 ax_mgr, internal, property_filters);
James Wallace-Leeeafc94cb92018-07-23 21:35:093801}
3802
Abigail Kleinaa898742019-11-01 02:31:253803void WebContentsImpl::RecordAccessibilityEvents(
Abigail Kleinbb8304bd2020-05-18 21:44:183804 bool start_recording,
3805 base::Optional<AccessibilityEventCallback> callback) {
3806 // Only pass a callback to RecordAccessibilityEvents when starting to record.
3807 DCHECK_EQ(start_recording, callback.has_value());
3808 if (start_recording) {
Abigail Kleinaa898742019-11-01 02:31:253809 SetAccessibilityMode(ui::AXMode::kWebContents);
3810 auto* ax_mgr = GetOrCreateRootBrowserAccessibilityManager();
3811 DCHECK(ax_mgr);
3812 base::ProcessId pid = base::Process::Current().Pid();
3813 event_recorder_ = content::AccessibilityEventRecorder::Create(
3814 ax_mgr, pid, base::StringPiece{});
Abigail Kleinbb8304bd2020-05-18 21:44:183815 event_recorder_->ListenToEvents(*callback);
Abigail Kleinaa898742019-11-01 02:31:253816 } else {
Abigail Kleinbb8304bd2020-05-18 21:44:183817 if (event_recorder_) {
3818 event_recorder_->FlushAsyncEvents();
3819 event_recorder_.reset(nullptr);
3820 }
Abigail Kleinaa898742019-11-01 02:31:253821 }
3822}
3823
dmazzonia656928e2014-09-15 20:28:543824RenderFrameHost* WebContentsImpl::GetGuestByInstanceID(
fsamuel833ee7c2015-02-13 23:40:403825 RenderFrameHost* render_frame_host,
dmazzonia656928e2014-09-15 20:28:543826 int browser_plugin_instance_id) {
3827 BrowserPluginGuestManager* guest_manager =
3828 GetBrowserContext()->GetGuestManager();
fsamuel9cbc00a2015-04-17 20:30:203829 if (!guest_manager)
3830 return nullptr;
3831
dmazzonia656928e2014-09-15 20:28:543832 WebContents* guest = guest_manager->GetGuestByInstanceID(
fsamuel2e9413d2015-02-25 01:25:443833 render_frame_host->GetProcess()->GetID(), browser_plugin_instance_id);
dmazzonia656928e2014-09-15 20:28:543834 if (!guest)
fsamuel9cbc00a2015-04-17 20:30:203835 return nullptr;
3836
dmazzonia656928e2014-09-15 20:28:543837 return guest->GetMainFrame();
3838}
3839
Ke He7319dbe2017-11-09 05:54:443840device::mojom::GeolocationContext* WebContentsImpl::GetGeolocationContext() {
Ella Ge3e375b702020-06-05 15:57:163841 if (delegate_) {
3842 auto* installed_webapp_context =
3843 delegate_->GetInstalledWebappGeolocationContext();
3844 if (installed_webapp_context)
3845 return installed_webapp_context;
3846 }
3847
Ken Rockotce010f02019-12-12 23:32:323848 if (!geolocation_context_) {
3849 GetDeviceService().BindGeolocationContext(
3850 geolocation_context_.BindNewPipeAndPassReceiver());
3851 }
Conley Owens6894c4f2017-07-10 19:29:133852 return geolocation_context_.get();
blundellc57b93f2014-10-29 13:19:573853}
3854
ke.he98b761e2017-05-09 05:59:173855device::mojom::WakeLockContext* WebContentsImpl::GetWakeLockContext() {
blundelld8cd72b2017-03-28 07:18:383856 if (!wake_lock_context_host_)
3857 wake_lock_context_host_.reset(new WakeLockContextHost(this));
blundelle75a8f92017-03-27 08:11:173858 return wake_lock_context_host_->GetWakeLockContext();
alogvinovf50445a2015-10-30 13:00:123859}
3860
blundellf5316fc2017-05-15 11:49:033861#if defined(OS_ANDROID)
Miyoung Shin59f39ff2019-09-17 07:23:203862void WebContentsImpl::GetNFC(
Reilly Grantafbe2242020-02-20 21:14:553863 RenderFrameHost* render_frame_host,
Miyoung Shin59f39ff2019-09-17 07:23:203864 mojo::PendingReceiver<device::mojom::NFC> receiver) {
Reilly Grantafbe2242020-02-20 21:14:553865 if (!nfc_host_)
3866 nfc_host_ = std::make_unique<NFCHost>(this);
3867 nfc_host_->GetNFC(render_frame_host, std::move(receiver));
blundellf5316fc2017-05-15 11:49:033868}
3869#endif
3870
Evan Stade5e750ad02017-08-07 21:59:273871void WebContentsImpl::SetNotWaitingForResponse() {
3872 if (waiting_for_response_ == false)
3873 return;
3874
3875 waiting_for_response_ = false;
3876 if (delegate_)
3877 delegate_->LoadingStateChanged(this, is_load_to_different_document_);
Alexander Timin90c20c32020-08-12 15:28:323878 observers_.ForEachObserver(
3879 [&](WebContentsObserver* observer) { observer->DidReceiveResponse(); });
Evan Stade5e750ad02017-08-07 21:59:273880}
3881
lfgbb9c28a2016-03-01 03:19:493882void WebContentsImpl::SendScreenRects() {
kenrbc52e1b4e2016-03-20 01:03:373883 for (FrameTreeNode* node : frame_tree_.Nodes()) {
kenrb0e8dc202016-05-30 19:51:403884 if (node->current_frame_host()->is_local_root())
kenrbc52e1b4e2016-03-20 01:03:373885 node->current_frame_host()->GetRenderWidgetHost()->SendScreenRects();
3886 }
[email protected]32deec62013-05-15 23:55:043887}
3888
ekaramadadd882292016-06-08 15:22:563889TextInputManager* WebContentsImpl::GetTextInputManager() {
3890 if (GetOuterWebContents())
3891 return GetOuterWebContents()->GetTextInputManager();
3892
Ehsan Karamadc179dc02018-12-15 03:09:293893 if (!text_input_manager_ && !browser_plugin_guest_) {
Darren Shenca53d5f2018-05-15 04:56:013894 text_input_manager_.reset(new TextInputManager(
3895 GetBrowserContext() &&
3896 !GetBrowserContext()->IsOffTheRecord()) /* should_do_learning */);
3897 }
ekaramadadd882292016-06-08 15:22:563898
3899 return text_input_manager_.get();
3900}
3901
paulmeyer7f6f1d4f2016-11-15 00:00:273902bool WebContentsImpl::OnUpdateDragCursor() {
Lei Zhang6410ec1a2019-01-31 21:38:583903 return browser_plugin_embedder_ &&
3904 browser_plugin_embedder_->OnUpdateDragCursor();
paulmeyer7f6f1d4f2016-11-15 00:00:273905}
3906
kenrb11f213a2017-03-24 18:12:063907bool WebContentsImpl::IsWidgetForMainFrame(
3908 RenderWidgetHostImpl* render_widget_host) {
3909 return render_widget_host == GetMainFrame()->GetRenderWidgetHost();
3910}
3911
[email protected]95640212014-07-26 18:14:303912BrowserAccessibilityManager*
3913 WebContentsImpl::GetRootBrowserAccessibilityManager() {
Carlos ILd51e7702020-05-07 18:51:393914 RenderFrameHostImpl* rfh = static_cast<RenderFrameHostImpl*>(GetMainFrame());
creisc014b402015-04-23 16:41:453915 return rfh ? rfh->browser_accessibility_manager() : nullptr;
[email protected]95640212014-07-26 18:14:303916}
3917
3918BrowserAccessibilityManager*
3919 WebContentsImpl::GetOrCreateRootBrowserAccessibilityManager() {
Carlos ILd51e7702020-05-07 18:51:393920 RenderFrameHostImpl* rfh = static_cast<RenderFrameHostImpl*>(GetMainFrame());
creisc014b402015-04-23 16:41:453921 return rfh ? rfh->GetOrCreateBrowserAccessibilityManager() : nullptr;
[email protected]95640212014-07-26 18:14:303922}
3923
Dave Tapuskab336b922017-07-06 19:24:053924void WebContentsImpl::ExecuteEditCommand(
3925 const std::string& command,
3926 const base::Optional<base::string16>& value) {
Dave Tapuska58a099e2020-06-08 21:48:403927 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:513928 if (!input_handler)
Dave Tapuskab336b922017-07-06 19:24:053929 return;
3930
Dave Tapuskae782bea2019-07-09 16:21:513931 input_handler->ExecuteEditCommand(command, value);
Dave Tapuskab336b922017-07-06 19:24:053932}
3933
mohsen7ab1ec16ec2015-07-02 18:26:233934void WebContentsImpl::MoveRangeSelectionExtent(const gfx::Point& extent) {
Dave Tapuska58a099e2020-06-08 21:48:403935 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:513936 if (!input_handler)
mohsen7ab1ec16ec2015-07-02 18:26:233937 return;
3938
Dave Tapuskae782bea2019-07-09 16:21:513939 input_handler->MoveRangeSelectionExtent(extent);
mohsen7ab1ec16ec2015-07-02 18:26:233940}
3941
3942void WebContentsImpl::SelectRange(const gfx::Point& base,
3943 const gfx::Point& extent) {
Dave Tapuska58a099e2020-06-08 21:48:403944 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:513945 if (!input_handler)
mohsen7ab1ec16ec2015-07-02 18:26:233946 return;
3947
Dave Tapuskae782bea2019-07-09 16:21:513948 input_handler->SelectRange(base, extent);
mohsen7ab1ec16ec2015-07-02 18:26:233949}
3950
Dave Tapuskab336b922017-07-06 19:24:053951void WebContentsImpl::MoveCaret(const gfx::Point& extent) {
Dave Tapuska58a099e2020-06-08 21:48:403952 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:513953 if (!input_handler)
Dave Tapuskab336b922017-07-06 19:24:053954 return;
3955
Dave Tapuskae782bea2019-07-09 16:21:513956 input_handler->MoveCaret(extent);
Dave Tapuskab336b922017-07-06 19:24:053957}
3958
Shimi Zhang37deeb22017-09-28 00:59:013959void WebContentsImpl::AdjustSelectionByCharacterOffset(
3960 int start_adjust,
3961 int end_adjust,
3962 bool show_selection_menu) {
Dave Tapuska58a099e2020-06-08 21:48:403963 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:513964 if (!input_handler)
aurimasab0319022015-07-10 21:57:383965 return;
3966
Shimi Zhang37deeb22017-09-28 00:59:013967 using blink::mojom::SelectionMenuBehavior;
Dave Tapuskae782bea2019-07-09 16:21:513968 input_handler->AdjustSelectionByCharacterOffset(
Shimi Zhang37deeb22017-09-28 00:59:013969 start_adjust, end_adjust,
3970 show_selection_menu ? SelectionMenuBehavior::kShow
3971 : SelectionMenuBehavior::kHide);
aurimasab0319022015-07-10 21:57:383972}
3973
[email protected]b172aee2012-04-10 17:05:263974void WebContentsImpl::UpdatePreferredSize(const gfx::Size& pref_size) {
[email protected]222f5822014-02-05 23:40:493975 const gfx::Size old_size = GetPreferredSize();
[email protected]bcd2815602012-01-14 18:17:233976 preferred_size_ = pref_size;
[email protected]222f5822014-02-05 23:40:493977 OnPreferredSizeChanged(old_size);
[email protected]0548c5352011-09-07 00:33:333978}
3979
avic3aa8422015-11-09 20:57:223980void WebContentsImpl::ResizeDueToAutoResize(
3981 RenderWidgetHostImpl* render_widget_host,
Fady Samuel97947112018-05-05 16:24:543982 const gfx::Size& new_size) {
avic3aa8422015-11-09 20:57:223983 if (render_widget_host != GetRenderViewHost()->GetWidget())
3984 return;
3985
[email protected]61e2b3cc2012-03-02 16:13:343986 if (delegate_)
3987 delegate_->ResizeDueToAutoResize(this, new_size);
3988}
3989
[email protected]b172aee2012-04-10 17:05:263990WebContents* WebContentsImpl::OpenURL(const OpenURLParams& params) {
Aaron Colwell9dab1652019-12-09 18:29:493991#if DCHECK_IS_ON()
3992 DCHECK(params.Valid());
3993#endif
3994
Bo Liu300c6052018-06-12 04:46:073995 if (!delegate_) {
3996 // Embedder can delay setting a delegate on new WebContents with
3997 // WebContentsDelegate::ShouldResumeRequestsForCreatedWindow. In the mean
3998 // time, navigations, including the initial one, that goes through OpenURL
3999 // should be delayed until embedder is ready to resume loading.
4000 delayed_open_url_params_ = std::make_unique<OpenURLParams>(params);
Nasko Oskov83a8cf92018-10-19 14:58:564001
4002 // If there was a navigation deferred when creating the window through
4003 // CreateNewWindow, drop it in favor of this navigation.
4004 delayed_load_url_params_.reset();
4005
Ivan Kotenkov2c0d2bb32017-11-01 15:41:284006 return nullptr;
Bo Liu300c6052018-06-12 04:46:074007 }
[email protected]00c37fc2011-08-02 00:22:504008
[email protected]e5d549d2011-12-28 01:29:204009 WebContents* new_contents = delegate_->OpenURLFromTab(this, params);
pnoland488944652017-02-22 18:58:544010
4011 RenderFrameHost* source_render_frame_host = RenderFrameHost::FromID(
4012 params.source_render_process_id, params.source_render_frame_id);
4013
4014 if (source_render_frame_host && params.source_site_instance) {
4015 CHECK_EQ(source_render_frame_host->GetSiteInstance(),
4016 params.source_site_instance.get());
4017 }
4018
4019 if (new_contents && source_render_frame_host && new_contents != this) {
Alexander Timin90c20c32020-08-12 15:28:324020 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4021 observer->DidOpenRequestedURL(
Lukasz Anforowicz48c9f872018-08-01 00:58:414022 new_contents, source_render_frame_host, params.url, params.referrer,
4023 params.disposition, params.transition,
4024 params.started_from_context_menu, params.is_renderer_initiated);
Alexander Timin90c20c32020-08-12 15:28:324025 });
pnoland488944652017-02-22 18:58:544026 }
4027
[email protected]e5d549d2011-12-28 01:29:204028 return new_contents;
[email protected]d5f942ba2008-09-26 19:30:344029}
4030
avi2b177592014-12-10 02:08:024031void WebContentsImpl::SetHistoryOffsetAndLength(int history_offset,
4032 int history_length) {
alexmos136fd6e62016-08-15 20:58:414033 SendPageMessage(new PageMsg_SetHistoryOffsetAndLength(
4034 MSG_ROUTING_NONE, history_offset, history_length));
avi2b177592014-12-10 02:08:024035}
4036
4037void WebContentsImpl::SetHistoryOffsetAndLengthForView(
4038 RenderViewHost* render_view_host,
4039 int history_offset,
4040 int history_length) {
alexmos136fd6e62016-08-15 20:58:414041 render_view_host->Send(new PageMsg_SetHistoryOffsetAndLength(
avi2b177592014-12-10 02:08:024042 render_view_host->GetRoutingID(), history_offset, history_length));
[email protected]796931a92011-08-10 01:32:144043}
4044
arthursonzogni818c2642019-09-27 12:18:104045void WebContentsImpl::ReloadFocusedFrame() {
[email protected]1f3fc1d2014-04-03 14:50:174046 RenderFrameHost* focused_frame = GetFocusedFrame();
4047 if (!focused_frame)
4048 return;
4049
yilkal921048bd2019-10-09 23:51:044050 focused_frame->Reload();
[email protected]959be4c2014-04-08 15:01:334051}
4052
4053void WebContentsImpl::Undo() {
Dave Tapuska58a099e2020-06-08 21:48:404054 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514055 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334056 return;
4057
Dave Tapuskae782bea2019-07-09 16:21:514058 input_handler->Undo();
[email protected]959be4c2014-04-08 15:01:334059 RecordAction(base::UserMetricsAction("Undo"));
4060}
4061
4062void WebContentsImpl::Redo() {
Dave Tapuska58a099e2020-06-08 21:48:404063 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514064 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334065 return;
Dave Tapuskae782bea2019-07-09 16:21:514066
4067 input_handler->Redo();
[email protected]959be4c2014-04-08 15:01:334068 RecordAction(base::UserMetricsAction("Redo"));
4069}
4070
4071void WebContentsImpl::Cut() {
Dave Tapuska58a099e2020-06-08 21:48:404072 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514073 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334074 return;
4075
Dave Tapuskae782bea2019-07-09 16:21:514076 input_handler->Cut();
[email protected]959be4c2014-04-08 15:01:334077 RecordAction(base::UserMetricsAction("Cut"));
4078}
4079
4080void WebContentsImpl::Copy() {
Dave Tapuska58a099e2020-06-08 21:48:404081 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514082 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334083 return;
4084
Dave Tapuskae782bea2019-07-09 16:21:514085 input_handler->Copy();
[email protected]959be4c2014-04-08 15:01:334086 RecordAction(base::UserMetricsAction("Copy"));
4087}
4088
4089void WebContentsImpl::CopyToFindPboard() {
Avi Drissman7c57be72020-07-29 20:09:464090#if defined(OS_MAC)
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
4095 // Windows/Linux don't have the concept of a find pasteboard.
Dave Tapuskae782bea2019-07-09 16:21:514096 input_handler->CopyToFindPboard();
[email protected]959be4c2014-04-08 15:01:334097 RecordAction(base::UserMetricsAction("CopyToFindPboard"));
4098#endif
4099}
4100
4101void WebContentsImpl::Paste() {
Dave Tapuska58a099e2020-06-08 21:48:404102 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514103 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334104 return;
4105
Dave Tapuskae782bea2019-07-09 16:21:514106 input_handler->Paste();
Alexander Timin90c20c32020-08-12 15:28:324107 observers_.ForEachObserver(
4108 [&](WebContentsObserver* observer) { observer->OnPaste(); });
[email protected]959be4c2014-04-08 15:01:334109 RecordAction(base::UserMetricsAction("Paste"));
4110}
4111
4112void WebContentsImpl::PasteAndMatchStyle() {
Dave Tapuska58a099e2020-06-08 21:48:404113 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514114 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334115 return;
4116
Dave Tapuskae782bea2019-07-09 16:21:514117 input_handler->PasteAndMatchStyle();
Alexander Timin90c20c32020-08-12 15:28:324118 observers_.ForEachObserver(
4119 [&](WebContentsObserver* observer) { observer->OnPaste(); });
[email protected]959be4c2014-04-08 15:01:334120 RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
4121}
4122
4123void WebContentsImpl::Delete() {
Dave Tapuska58a099e2020-06-08 21:48:404124 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514125 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334126 return;
4127
Dave Tapuskae782bea2019-07-09 16:21:514128 input_handler->Delete();
[email protected]959be4c2014-04-08 15:01:334129 RecordAction(base::UserMetricsAction("DeleteSelection"));
4130}
4131
4132void WebContentsImpl::SelectAll() {
Dave Tapuska58a099e2020-06-08 21:48:404133 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514134 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334135 return;
4136
Dave Tapuskae782bea2019-07-09 16:21:514137 input_handler->SelectAll();
[email protected]959be4c2014-04-08 15:01:334138 RecordAction(base::UserMetricsAction("SelectAll"));
4139}
4140
yabinh351e7ec2017-03-10 02:43:244141void WebContentsImpl::CollapseSelection() {
Dave Tapuska58a099e2020-06-08 21:48:404142 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514143 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334144 return;
4145
Dave Tapuskae782bea2019-07-09 16:21:514146 input_handler->CollapseSelection();
[email protected]1f3fc1d2014-04-03 14:50:174147}
4148
4149void WebContentsImpl::Replace(const base::string16& word) {
Dave Tapuska58a099e2020-06-08 21:48:404150 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514151 if (!input_handler)
[email protected]1f3fc1d2014-04-03 14:50:174152 return;
4153
Dave Tapuskae782bea2019-07-09 16:21:514154 input_handler->Replace(word);
[email protected]1f3fc1d2014-04-03 14:50:174155}
4156
4157void WebContentsImpl::ReplaceMisspelling(const base::string16& word) {
Dave Tapuska58a099e2020-06-08 21:48:404158 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514159 if (!input_handler)
[email protected]1f3fc1d2014-04-03 14:50:174160 return;
4161
Dave Tapuskae782bea2019-07-09 16:21:514162 input_handler->ReplaceMisspelling(word);
[email protected]959be4c2014-04-08 15:01:334163}
4164
4165void WebContentsImpl::NotifyContextMenuClosed(
4166 const CustomContextMenuContext& context) {
4167 RenderFrameHost* focused_frame = GetFocusedFrame();
4168 if (!focused_frame)
4169 return;
4170
4171 focused_frame->Send(new FrameMsg_ContextMenuClosed(
4172 focused_frame->GetRoutingID(), context));
4173}
4174
4175void WebContentsImpl::ExecuteCustomContextMenuCommand(
4176 int action, const CustomContextMenuContext& context) {
4177 RenderFrameHost* focused_frame = GetFocusedFrame();
4178 if (!focused_frame)
4179 return;
4180
4181 focused_frame->Send(new FrameMsg_CustomContextMenuAction(
4182 focused_frame->GetRoutingID(), context, action));
[email protected]4fed3702014-04-01 09:08:004183}
4184
[email protected]fc2b46b2014-05-03 16:33:454185gfx::NativeView WebContentsImpl::GetNativeView() {
4186 return view_->GetNativeView();
4187}
4188
4189gfx::NativeView WebContentsImpl::GetContentNativeView() {
4190 return view_->GetContentNativeView();
4191}
4192
4193gfx::NativeWindow WebContentsImpl::GetTopLevelNativeWindow() {
4194 return view_->GetTopLevelNativeWindow();
4195}
4196
4197gfx::Rect WebContentsImpl::GetViewBounds() {
4198 return view_->GetViewBounds();
4199}
4200
4201gfx::Rect WebContentsImpl::GetContainerBounds() {
Jeremy Roman352239c2020-05-21 16:31:324202 return view_->GetContainerBounds();
[email protected]fc2b46b2014-05-03 16:33:454203}
4204
4205DropData* WebContentsImpl::GetDropData() {
4206 return view_->GetDropData();
4207}
4208
4209void WebContentsImpl::Focus() {
miu9e14e492014-10-25 02:39:044210 view_->Focus();
[email protected]fc2b46b2014-05-03 16:33:454211}
4212
4213void WebContentsImpl::SetInitialFocus() {
miu9e14e492014-10-25 02:39:044214 view_->SetInitialFocus();
[email protected]fc2b46b2014-05-03 16:33:454215}
4216
4217void WebContentsImpl::StoreFocus() {
miu9e14e492014-10-25 02:39:044218 view_->StoreFocus();
[email protected]fc2b46b2014-05-03 16:33:454219}
4220
4221void WebContentsImpl::RestoreFocus() {
miu9e14e492014-10-25 02:39:044222 view_->RestoreFocus();
[email protected]fc2b46b2014-05-03 16:33:454223}
4224
[email protected]b172aee2012-04-10 17:05:264225void WebContentsImpl::FocusThroughTabTraversal(bool reverse) {
Maxim Podgorodskiya926c4ff2017-11-20 02:06:394226 view_->FocusThroughTabTraversal(reverse);
[email protected]96d185d2009-04-24 03:28:544227}
4228
[email protected]b172aee2012-04-10 17:05:264229bool WebContentsImpl::IsSavable() {
[email protected]a53209b2012-01-20 16:48:164230 // WebKit creates Document object when MIME type is application/xhtml+xml,
4231 // so we also support this MIME type.
Yuzu Saijoc23e9b72020-06-25 07:21:274232 std::string mime_type = GetContentsMimeType();
4233 return mime_type == "text/html" || mime_type == "text/xml" ||
4234 mime_type == "application/xhtml+xml" || mime_type == "text/plain" ||
4235 mime_type == "text/css" ||
4236 blink::IsSupportedJavascriptMimeType(mime_type);
[email protected]a53209b2012-01-20 16:48:164237}
4238
[email protected]b172aee2012-04-10 17:05:264239void WebContentsImpl::OnSavePage() {
[email protected]c7dd2f62011-07-18 15:57:594240 // If we can not save the page, try to download it.
[email protected]a53209b2012-01-20 16:48:164241 if (!IsSavable()) {
Min Qinda0ed2062018-02-23 22:00:534242 download::RecordSavePackageEvent(
4243 download::SAVE_PACKAGE_DOWNLOAD_ON_NON_HTML);
nasko89ad7742015-03-05 22:14:194244 SaveFrame(GetLastCommittedURL(), Referrer());
[email protected]27678b2a2012-02-04 22:09:144245 return;
[email protected]c7dd2f62011-07-18 15:57:594246 }
4247
4248 Stop();
4249
4250 // Create the save package and possibly prompt the user for the name to save
4251 // the page as. The user prompt is an asynchronous operation that runs on
4252 // another thread.
4253 save_package_ = new SavePackage(this);
4254 save_package_->GetSaveInfo();
4255}
4256
4257// Used in automated testing to bypass prompting the user for file names.
4258// Instead, the names and paths are hard coded rather than running them through
4259// file name sanitation and extension / mime checking.
[email protected]2dec8ec2013-02-07 19:20:344260bool WebContentsImpl::SavePage(const base::FilePath& main_file,
4261 const base::FilePath& dir_path,
[email protected]8ff00d72012-10-23 19:12:214262 SavePageType save_type) {
[email protected]c7dd2f62011-07-18 15:57:594263 // Stop the page from navigating.
4264 Stop();
4265
4266 save_package_ = new SavePackage(this, save_type, main_file, dir_path);
[email protected]8ff00d72012-10-23 19:12:214267 return save_package_->Init(SavePackageDownloadCreatedCallback());
[email protected]c7dd2f62011-07-18 15:57:594268}
4269
[email protected]3c71576ce2013-07-23 02:00:014270void WebContentsImpl::SaveFrame(const GURL& url,
4271 const Referrer& referrer) {
Xing Liu10329bf2018-03-20 19:22:144272 SaveFrameWithHeaders(url, referrer, std::string(), base::string16());
kundaji6c7f9692015-03-09 18:00:374273}
4274
Xing Liu10329bf2018-03-20 19:22:144275void WebContentsImpl::SaveFrameWithHeaders(
4276 const GURL& url,
4277 const Referrer& referrer,
4278 const std::string& headers,
4279 const base::string16& suggested_filename) {
Lei Zhang13a42e42019-02-19 23:28:114280 // Check and see if the guest can handle this.
4281 if (delegate_) {
4282 WebContents* guest_web_contents = nullptr;
4283 if (browser_plugin_embedder_) {
4284 BrowserPluginGuest* guest = browser_plugin_embedder_->GetFullPageGuest();
4285 if (guest)
4286 guest_web_contents = guest->GetWebContents();
4287 } else if (browser_plugin_guest_) {
4288 guest_web_contents = this;
4289 }
4290
4291 if (guest_web_contents && delegate_->GuestSaveFrame(guest_web_contents))
4292 return;
4293 }
4294
nasko89ad7742015-03-05 22:14:194295 if (!GetLastCommittedURL().is_valid())
[email protected]3c71576ce2013-07-23 02:00:014296 return;
sammc92af61552014-11-19 23:27:404297 if (delegate_ && delegate_->SaveFrame(url, referrer))
4298 return;
4299
nasko89ad7742015-03-05 22:14:194300 // TODO(nasko): This check for main frame is incorrect and should be fixed
brettw760f7442016-05-23 21:19:224301 // by explicitly passing in which frame this method should target. This would
4302 // indicate whether it's the main frame, and also tell us the frame pointer
4303 // to use for routing.
nasko89ad7742015-03-05 22:14:194304 bool is_main_frame = (url == GetLastCommittedURL());
brettw760f7442016-05-23 21:19:224305 RenderFrameHost* frame_host = GetMainFrame();
[email protected]3c71576ce2013-07-23 02:00:014306
avib7348942015-12-25 20:57:104307 int64_t post_id = -1;
[email protected]3c71576ce2013-07-23 02:00:014308 if (is_main_frame) {
Lucas Furukawa Gadani5553a152019-01-08 18:55:574309 NavigationEntry* entry = controller_.GetLastCommittedEntry();
[email protected]3c71576ce2013-07-23 02:00:014310 if (entry)
4311 post_id = entry->GetPostID();
4312 }
Ramin Halavati24e21012017-07-10 12:56:064313 net::NetworkTrafficAnnotationTag traffic_annotation =
4314 net::DefineNetworkTrafficAnnotation("download_web_contents_frame", R"(
4315 semantics {
4316 sender: "Save Page Action"
4317 description:
4318 "Saves the given frame's URL to the local file system."
4319 trigger:
4320 "The user has triggered a save operation on the frame through a "
4321 "context menu or other mechanism."
4322 data: "None."
4323 destination: WEBSITE
4324 }
4325 policy {
Ramin Halavati3b979782017-07-21 11:40:264326 cookies_allowed: YES
Ramin Halavati24e21012017-07-10 12:56:064327 cookies_store: "user"
4328 setting:
4329 "This feature cannot be disabled by settings, but it's is only "
4330 "triggered by user request."
4331 policy_exception_justification: "Not implemented."
4332 })");
Min Qina904f3302018-02-13 23:33:344333 auto params = std::make_unique<download::DownloadUrlParameters>(
brettw760f7442016-05-23 21:19:224334 url, frame_host->GetProcess()->GetID(),
4335 frame_host->GetRenderViewHost()->GetRoutingID(),
Matt Menke0dcaebc32020-03-06 17:00:104336 frame_host->GetRoutingID(), traffic_annotation);
Min Qina904f3302018-02-13 23:33:344337 params->set_referrer(referrer.url);
4338 params->set_referrer_policy(
4339 Referrer::ReferrerPolicyForUrlRequest(referrer.policy));
[email protected]3c71576ce2013-07-23 02:00:014340 params->set_post_id(post_id);
[email protected]3c71576ce2013-07-23 02:00:014341 if (post_id >= 0)
4342 params->set_method("POST");
4343 params->set_prompt(true);
kundaji6c7f9692015-03-09 18:00:374344
4345 if (headers.empty()) {
4346 params->set_prefer_cache(true);
4347 } else {
Min Qina904f3302018-02-13 23:33:344348 for (download::DownloadUrlParameters::RequestHeadersNameValuePair
4349 key_value : ParseDownloadHeaders(headers)) {
Megan Jablonski2f6a4c52017-07-10 23:01:254350 params->add_request_header(key_value.first, key_value.second);
kundaji6c7f9692015-03-09 18:00:374351 }
4352 }
Xing Liu10329bf2018-03-20 19:22:144353 params->set_suggested_name(suggested_filename);
Min Qin0ca8e1ee2018-01-31 00:49:354354 params->set_download_source(download::DownloadSource::WEB_CONTENTS_API);
thestig859c78892017-05-15 21:17:064355 BrowserContext::GetDownloadManager(GetBrowserContext())
Ramin Halavati03efa732017-06-12 09:28:204356 ->DownloadUrl(std::move(params));
[email protected]3c71576ce2013-07-23 02:00:014357}
4358
[email protected]b172aee2012-04-10 17:05:264359void WebContentsImpl::GenerateMHTML(
dewittj6dc5747a2016-05-17 01:48:474360 const MHTMLGenerationParams& params,
Avi Drissman149b7832018-03-23 14:31:494361 base::OnceCallback<void(int64_t)> callback) {
Angel Alvarez902496682019-08-27 22:58:424362 base::OnceCallback<void(const MHTMLGenerationResult&)> wrapper_callback =
4363 base::BindOnce(
4364 [](base::OnceCallback<void(int64_t)> size_callback,
4365 const MHTMLGenerationResult& result) {
4366 std::move(size_callback).Run(result.file_size);
4367 },
4368 std::move(callback));
4369 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, params,
4370 std::move(wrapper_callback));
4371}
4372
4373void WebContentsImpl::GenerateMHTMLWithResult(
4374 const MHTMLGenerationParams& params,
4375 MHTMLGenerationResult::GenerateMHTMLCallback callback) {
Avi Drissman149b7832018-03-23 14:31:494376 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, params,
4377 std::move(callback));
[email protected]aa4f3972012-03-01 18:12:124378}
4379
Tsuyoshi Horob0d8d902020-03-12 00:09:394380void WebContentsImpl::GenerateWebBundle(
4381 const base::FilePath& file_path,
4382 base::OnceCallback<void(uint64_t /* file_size */,
4383 data_decoder::mojom::WebBundlerError)> callback) {
4384 SaveAsWebBundleJob::Start(this, file_path, std::move(callback));
4385}
4386
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414387const std::string& WebContentsImpl::GetContentsMimeType() {
Yuzu Saijoc23e9b72020-06-25 07:21:274388 return GetRenderViewHost()->contents_mime_type();
[email protected]0bfbf882011-12-22 18:19:274389}
4390
Leon Hanc819dc62019-01-28 04:30:194391blink::mojom::RendererPreferences* WebContentsImpl::GetMutableRendererPrefs() {
[email protected]0bfbf882011-12-22 18:19:274392 return &renderer_preferences_;
4393}
4394
[email protected]e35ccd52012-05-23 16:22:474395void WebContentsImpl::Close() {
4396 Close(GetRenderViewHost());
4397}
4398
Ella Ge80a52dce2017-11-15 18:01:524399void WebContentsImpl::DragSourceEndedAt(float client_x,
4400 float client_y,
4401 float screen_x,
4402 float screen_y,
Paul Meyer0c58c3712016-11-17 22:59:514403 blink::WebDragOperation operation,
4404 RenderWidgetHost* source_rwh) {
Lei Zhang6410ec1a2019-01-31 21:38:584405 if (browser_plugin_embedder_) {
W. James MacLean9437b5bf2019-12-06 17:33:444406 browser_plugin_embedder_->DragSourceEndedAt(client_x, client_y, screen_x,
4407 screen_y, operation);
Lei Zhang6410ec1a2019-01-31 21:38:584408 }
Paul Meyer0c58c3712016-11-17 22:59:514409 if (source_rwh) {
Ella Ge80a52dce2017-11-15 18:01:524410 source_rwh->DragSourceEndedAt(gfx::PointF(client_x, client_y),
4411 gfx::PointF(screen_x, screen_y), operation);
Paul Meyer0c58c3712016-11-17 22:59:514412 }
[email protected]cf200a562013-05-03 16:24:294413}
4414
jam73f892642016-09-11 06:04:064415void WebContentsImpl::LoadStateChanged(
Charles Harrison911fa062018-03-06 21:01:464416 const std::string& host,
jam73f892642016-09-11 06:04:064417 const net::LoadStateWithParam& load_state,
4418 uint64_t upload_position,
4419 uint64_t upload_size) {
Charles Harrison911fa062018-03-06 21:01:464420 base::string16 host16 = url_formatter::IDNToUnicode(host);
Elly Fong-Jonescad9c3d12018-01-31 17:26:104421 // Drop no-op updates.
4422 if (load_state_.state == load_state.state &&
4423 load_state_.param == load_state.param &&
4424 upload_position_ == upload_position && upload_size_ == upload_size &&
Charles Harrison911fa062018-03-06 21:01:464425 load_state_host_ == host16) {
Elly Fong-Jonescad9c3d12018-01-31 17:26:104426 return;
4427 }
jam73f892642016-09-11 06:04:064428 load_state_ = load_state;
4429 upload_position_ = upload_position;
4430 upload_size_ = upload_size;
Charles Harrison911fa062018-03-06 21:01:464431 load_state_host_ = host16;
jam73f892642016-09-11 06:04:064432 if (load_state_.state == net::LOAD_STATE_READING_RESPONSE)
4433 SetNotWaitingForResponse();
4434 if (IsLoading()) {
4435 NotifyNavigationStateChanged(static_cast<InvalidateTypes>(
4436 INVALIDATE_TYPE_LOAD | INVALIDATE_TYPE_TAB));
4437 }
4438}
4439
Collin Baker989e0882019-11-01 01:27:174440void WebContentsImpl::SetVisibilityAndNotifyObservers(Visibility visibility) {
Francois Doraye6161152018-03-27 22:05:374441 const Visibility previous_visibility = visibility_;
4442 visibility_ = visibility;
4443
Francois Dorayfe4a1772018-02-17 04:17:094444 // Notify observers if the visibility changed or if WasShown() is being called
4445 // for the first time.
Francois Dorayfe4a1772018-02-17 04:17:094446 if (visibility != previous_visibility ||
4447 (visibility == Visibility::VISIBLE && !did_first_set_visible_)) {
Alexander Timin90c20c32020-08-12 15:28:324448 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4449 observer->OnVisibilityChanged(visibility);
4450 });
Francois Dorayfe4a1772018-02-17 04:17:094451 }
4452}
4453
Michael Thiessen896405db2017-07-20 17:52:324454void WebContentsImpl::NotifyWebContentsFocused(
4455 RenderWidgetHost* render_widget_host) {
Alexander Timin90c20c32020-08-12 15:28:324456 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4457 observer->OnWebContentsFocused(render_widget_host);
4458 });
calamity7fe55ce2015-04-10 03:59:374459}
4460
Michael Thiessen896405db2017-07-20 17:52:324461void WebContentsImpl::NotifyWebContentsLostFocus(
4462 RenderWidgetHost* render_widget_host) {
Alexander Timin90c20c32020-08-12 15:28:324463 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4464 observer->OnWebContentsLostFocus(render_widget_host);
4465 });
zijiehe3bee08e22017-05-17 04:14:464466}
4467
Paul Meyer0c58c3712016-11-17 22:59:514468void WebContentsImpl::SystemDragEnded(RenderWidgetHost* source_rwh) {
4469 if (source_rwh)
4470 source_rwh->DragSourceSystemDragEnded();
Lei Zhang6410ec1a2019-01-31 21:38:584471 if (browser_plugin_embedder_)
[email protected]cf200a562013-05-03 16:24:294472 browser_plugin_embedder_->SystemDragEnded();
[email protected]7813bd72011-02-05 02:19:344473}
4474
[email protected]b172aee2012-04-10 17:05:264475void WebContentsImpl::SetClosedByUserGesture(bool value) {
[email protected]0bfbf882011-12-22 18:19:274476 closed_by_user_gesture_ = value;
4477}
4478
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414479bool WebContentsImpl::GetClosedByUserGesture() {
[email protected]0bfbf882011-12-22 18:19:274480 return closed_by_user_gesture_;
4481}
4482
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414483int WebContentsImpl::GetMinimumZoomPercent() {
[email protected]0bfbf882011-12-22 18:19:274484 return minimum_zoom_percent_;
4485}
4486
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414487int WebContentsImpl::GetMaximumZoomPercent() {
[email protected]0bfbf882011-12-22 18:19:274488 return maximum_zoom_percent_;
4489}
4490
Dave Tapuska8f7c3872020-02-07 01:16:384491void WebContentsImpl::SetPageScale(float scale_factor) {
4492 GetMainFrame()->GetAssociatedLocalMainFrame()->SetScaleFactor(scale_factor);
ccameronb7c1d6c2015-03-09 17:08:244493}
4494
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414495gfx::Size WebContentsImpl::GetPreferredSize() {
Francois Doray24fc62c2017-12-11 17:27:334496 return IsBeingCaptured() ? preferred_size_for_capture_ : preferred_size_;
[email protected]bcd2815602012-01-14 18:17:234497}
4498
James Hollyerd5c9de462020-03-10 19:02:454499bool WebContentsImpl::GotResponseToLockMouseRequest(
4500 blink::mojom::PointerLockResult result) {
lfgf0cd46e2017-01-04 00:05:234501 if (mouse_lock_widget_) {
4502 if (mouse_lock_widget_->delegate()->GetAsWebContents() != this) {
4503 return mouse_lock_widget_->delegate()
4504 ->GetAsWebContents()
James Hollyerd5c9de462020-03-10 19:02:454505 ->GotResponseToLockMouseRequest(result);
lfgf0cd46e2017-01-04 00:05:234506 }
lfgad8244352016-07-13 16:55:514507
James Hollyerd5c9de462020-03-10 19:02:454508 if (mouse_lock_widget_->GotResponseToLockMouseRequest(result))
lfgf0cd46e2017-01-04 00:05:234509 return true;
4510 }
4511
4512 for (WebContentsImpl* current = this; current;
4513 current = current->GetOuterWebContents()) {
4514 current->mouse_lock_widget_ = nullptr;
4515 }
4516
lfgbee1e0a2016-06-08 21:24:214517 return false;
[email protected]0bfbf882011-12-22 18:19:274518}
4519
James Hollyerd5c9de462020-03-10 19:02:454520void WebContentsImpl::GotLockMousePermissionResponse(bool allowed) {
4521 GotResponseToLockMouseRequest(
4522 allowed ? blink::mojom::PointerLockResult::kSuccess
4523 : blink::mojom::PointerLockResult::kPermissionDenied);
4524}
4525
Joe Downing13dd76b2018-04-09 18:32:154526bool WebContentsImpl::GotResponseToKeyboardLockRequest(bool allowed) {
4527 if (!keyboard_lock_widget_)
4528 return false;
4529
4530 if (keyboard_lock_widget_->delegate()->GetAsWebContents() != this) {
4531 NOTREACHED();
4532 return false;
4533 }
4534
4535 // KeyboardLock is only supported when called by the top-level browsing
4536 // context and is not supported in embedded content scenarios.
4537 if (GetOuterWebContents())
4538 return false;
4539
4540 keyboard_lock_widget_->GotResponseToKeyboardLockRequest(allowed);
4541 return true;
4542}
4543
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414544bool WebContentsImpl::HasOpener() {
Ivan Kotenkov2c0d2bb32017-11-01 15:41:284545 return GetOpener() != nullptr;
[email protected]a0358d72012-03-09 14:06:504546}
4547
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414548RenderFrameHostImpl* WebContentsImpl::GetOpener() {
alexmose201c7cd2015-06-10 17:14:214549 FrameTreeNode* opener_ftn = frame_tree_.root()->opener();
lukasza6f8ac622017-06-06 03:10:204550 return opener_ftn ? opener_ftn->current_frame_host() : nullptr;
jochen55ff3502014-12-18 20:52:574551}
4552
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414553bool WebContentsImpl::HasOriginalOpener() {
Ivan Kotenkov2c0d2bb32017-11-01 15:41:284554 return GetOriginalOpener() != nullptr;
jochen6004a362017-02-04 00:11:404555}
4556
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414557RenderFrameHostImpl* WebContentsImpl::GetOriginalOpener() {
jochen6004a362017-02-04 00:11:404558 FrameTreeNode* opener_ftn = frame_tree_.root()->original_opener();
lukasza6f8ac622017-06-06 03:10:204559 return opener_ftn ? opener_ftn->current_frame_host() : nullptr;
jochen6004a362017-02-04 00:11:404560}
4561
[email protected]cb805452013-05-22 15:16:214562void WebContentsImpl::DidChooseColorInColorChooser(SkColor color) {
Joel Hockey85b379d2017-12-11 10:42:134563 color_chooser_->DidChooseColorInColorChooser(color);
[email protected]da8543762012-03-20 08:52:204564}
4565
[email protected]cb805452013-05-22 15:16:214566void WebContentsImpl::DidEndColorChooser() {
Joel Hockey85b379d2017-12-11 10:42:134567 color_chooser_.reset();
[email protected]da8543762012-03-20 08:52:204568}
4569
halton.huoca2eabd2015-07-06 08:17:404570int WebContentsImpl::DownloadImage(
4571 const GURL& url,
4572 bool is_favicon,
Fredrik Söderquistb2b39eb92019-11-18 16:16:504573 uint32_t preferred_size,
halton.huoca2eabd2015-07-06 08:17:404574 uint32_t max_bitmap_size,
4575 bool bypass_cache,
Avi Drissmana5a52dd2018-03-27 03:39:024576 WebContents::ImageDownloadCallback callback) {
Danyao Wanga78f3dd22020-03-05 05:31:274577 return DownloadImageInFrame(GlobalFrameRoutingId(), url, is_favicon,
4578 preferred_size, max_bitmap_size, bypass_cache,
4579 std::move(callback));
4580}
4581
4582int WebContentsImpl::DownloadImageInFrame(
4583 const GlobalFrameRoutingId& initiator_frame_routing_id,
4584 const GURL& url,
4585 bool is_favicon,
4586 uint32_t preferred_size,
4587 uint32_t max_bitmap_size,
4588 bool bypass_cache,
4589 WebContents::ImageDownloadCallback callback) {
amistry9f01b772015-07-29 01:54:554590 DCHECK_CURRENTLY_ON(BrowserThread::UI);
halton.huoca2eabd2015-07-06 08:17:404591 static int next_image_download_id = 0;
Danyao Wanga78f3dd22020-03-05 05:31:274592
4593 RenderFrameHostImpl* initiator_frame =
4594 initiator_frame_routing_id.child_id
4595 ? RenderFrameHostImpl::FromID(initiator_frame_routing_id)
4596 : GetMainFrame();
Julie Jeongeun Kimb1473572019-08-15 05:59:134597 const mojo::Remote<blink::mojom::ImageDownloader>& mojo_image_downloader =
Danyao Wanga78f3dd22020-03-05 05:31:274598 initiator_frame->GetMojoImageDownloader();
amistry9f01b772015-07-29 01:54:554599 const int download_id = ++next_image_download_id;
4600 if (!mojo_image_downloader) {
4601 // If the renderer process is dead (i.e. crash, or memory pressure on
4602 // Android), the downloader service will be invalid. Pre-Mojo, this would
Avi Drissmana5a52dd2018-03-27 03:39:024603 // hang the callback indefinitely since the IPC would be dropped. Now,
amistry9f01b772015-07-29 01:54:554604 // respond with a 400 HTTP error code to indicate that something went wrong.
Gabriel Charettee7cdc5cd2020-05-27 23:35:054605 GetUIThreadTaskRunner({})->PostTask(
4606 FROM_HERE,
tzike2aca992017-09-05 08:50:544607 base::BindOnce(&WebContentsImpl::OnDidDownloadImage,
Avi Drissmana5a52dd2018-03-27 03:39:024608 weak_factory_.GetWeakPtr(), std::move(callback),
4609 download_id, url, 400, std::vector<SkBitmap>(),
4610 std::vector<gfx::Size>()));
amistry9f01b772015-07-29 01:54:554611 return download_id;
4612 }
4613
halton.huoca2eabd2015-07-06 08:17:404614 mojo_image_downloader->DownloadImage(
Fredrik Söderquistb2b39eb92019-11-18 16:16:504615 url, is_favicon, preferred_size, max_bitmap_size, bypass_cache,
tzike2aca992017-09-05 08:50:544616 base::BindOnce(&WebContentsImpl::OnDidDownloadImage,
Avi Drissmana5a52dd2018-03-27 03:39:024617 weak_factory_.GetWeakPtr(), std::move(callback),
4618 download_id, url));
amistry9f01b772015-07-29 01:54:554619 return download_id;
[email protected]795c28972012-12-06 06:13:394620}
4621
[email protected]36ec24f2014-01-09 00:32:084622void WebContentsImpl::Find(int request_id,
4623 const base::string16& search_text,
Rakina Zata Amni3f77dff2018-09-08 16:19:434624 blink::mojom::FindOptionsPtr options) {
thestig6057a6b22015-11-12 23:01:334625 // Cowardly refuse to search for no text.
4626 if (search_text.empty()) {
4627 NOTREACHED();
4628 return;
4629 }
4630
Rakina Zata Amni3f77dff2018-09-08 16:19:434631 GetOrCreateFindRequestManager()->Find(request_id, search_text,
4632 std::move(options));
[email protected]36ec24f2014-01-09 00:32:084633}
4634
4635void WebContentsImpl::StopFinding(StopFindAction action) {
paulmeyerfeafc2d2017-04-25 21:46:404636 if (FindRequestManager* manager = GetFindRequestManager())
4637 manager->StopFinding(action);
[email protected]36ec24f2014-01-09 00:32:084638}
4639
Tommy Steimel18360512017-11-01 00:38:194640bool WebContentsImpl::WasEverAudible() {
4641 return was_ever_audible_;
4642}
4643
Avi Drissmana5a52dd2018-03-27 03:39:024644void WebContentsImpl::GetManifest(GetManifestCallback callback) {
Yuzu Saijofce18322020-05-14 05:02:094645 // TODO(yuzus, 1061899): Move this function to RenderFrameHostImpl.
4646 ManifestManagerHost* manifest_manager_host =
4647 ManifestManagerHost::GetOrCreateForCurrentDocument(GetMainFrame());
4648 manifest_manager_host->GetManifest(std::move(callback));
mlamouriefdca9d2014-09-16 16:55:404649}
4650
bokanece34a82016-01-28 19:49:464651void WebContentsImpl::ExitFullscreen(bool will_cause_resize) {
mlamouri7a78d6fd2015-01-17 13:23:534652 // Clean up related state and initiate the fullscreen exit.
James Hollyerd5c9de462020-03-10 19:02:454653 GetRenderViewHost()->GetWidget()->RejectMouseLockOrUnlockIfNecessary(
4654 blink::mojom::PointerLockResult::kUserRejected);
bokanece34a82016-01-28 19:49:464655 ExitFullscreenMode(will_cause_resize);
mlamouri7a78d6fd2015-01-17 13:23:534656}
4657
Avi Drissman1a55a9d62020-03-10 18:56:454658base::ScopedClosureRunner WebContentsImpl::ForSecurityDropFullscreen() {
Avi Drissman33972942020-06-19 14:16:014659 // Kick WebContentses that are "related" to this WebContents out of
4660 // fullscreen. This needs to be done with two passes, because it is simple to
4661 // walk _up_ the chain of openers and outer contents, but it not simple to
4662 // walk _down_ the chain.
4663
4664 // First, determine if any WebContents that is in fullscreen has this
4665 // WebContents as an upstream contents. Drop that WebContents out of
4666 // fullscreen if it does. This is theoretically quadratic-ish (fullscreen
4667 // contentses x each one's opener length) but neither of those is expected to
4668 // ever be a large number.
4669
4670 auto fullscreen_set_copy = *FullscreenContentsSet(GetBrowserContext());
4671 for (auto* fullscreen_contents : fullscreen_set_copy) {
Avi Drissman97aef042020-06-30 21:04:484672 // Checking IsFullscreen() for tabs in the fullscreen set may seem
4673 // redundant, but teeeeechnically fullscreen is run by the delegate, and
4674 // it's possible that the delegate's notion of fullscreen may have changed
4675 // outside of WebContents's notice.
4676 if (fullscreen_contents->IsFullscreen()) {
Avi Drissman33972942020-06-19 14:16:014677 auto opener_contentses = GetAllOpeningWebContents(fullscreen_contents);
4678 if (opener_contentses.count(this))
4679 fullscreen_contents->ExitFullscreen(true);
4680 }
4681 }
4682
4683 // Second, walk upstream from this WebContents, and drop the fullscreen of
4684 // all WebContentses that are in fullscreen. Block all the WebContentses in
4685 // the chain from entering fullscreen while the returned closure runner is
4686 // alive. It's OK that this set doesn't contain downstream WebContentses, as
4687 // any request to enter fullscreen will have the upstream of the WebContents
4688 // checked. (See CanEnterFullscreenMode().)
Avi Drissmanced52b62019-08-14 21:25:464689
Avi Drissman1a55a9d62020-03-10 18:56:454690 std::vector<base::WeakPtr<WebContentsImpl>> blocked_contentses;
4691
Avi Drissman33972942020-06-19 14:16:014692 for (auto* opener : GetAllOpeningWebContents(this)) {
Avi Drissman1a55a9d62020-03-10 18:56:454693 // Drop fullscreen if the WebContents is in it, and...
Avi Drissman97aef042020-06-30 21:04:484694 if (opener->IsFullscreen())
Avi Drissman33972942020-06-19 14:16:014695 opener->ExitFullscreen(true);
Avi Drissmanced52b62019-08-14 21:25:464696
Avi Drissman1a55a9d62020-03-10 18:56:454697 // ...block the WebContents from entering fullscreen until further notice.
Avi Drissman33972942020-06-19 14:16:014698 ++opener->fullscreen_blocker_count_;
4699 blocked_contentses.push_back(opener->weak_factory_.GetWeakPtr());
Avi Drissmanced52b62019-08-14 21:25:464700 }
Avi Drissman1a55a9d62020-03-10 18:56:454701
4702 return base::ScopedClosureRunner(base::BindOnce(
4703 [](std::vector<base::WeakPtr<WebContentsImpl>> blocked_contentses) {
4704 for (base::WeakPtr<WebContentsImpl>& web_contents :
4705 blocked_contentses) {
4706 if (web_contents) {
4707 DCHECK_GT(web_contents->fullscreen_blocker_count_, 0);
4708 --web_contents->fullscreen_blocker_count_;
4709 }
4710 }
4711 },
4712 std::move(blocked_contentses)));
Avi Drissmanced52b62019-08-14 21:25:464713}
4714
mariakhomenko44bdc4732015-04-29 01:55:384715void WebContentsImpl::ResumeLoadingCreatedWebContents() {
Nasko Oskov83a8cf92018-10-19 14:58:564716 if (delayed_load_url_params_.get()) {
4717 DCHECK(!delayed_open_url_params_);
4718 controller_.LoadURLWithParams(*delayed_load_url_params_.get());
4719 delayed_load_url_params_.reset(nullptr);
4720 return;
4721 }
4722
mariakhomenkoa4971c12015-07-21 19:04:374723 if (delayed_open_url_params_.get()) {
4724 OpenURL(*delayed_open_url_params_.get());
4725 delayed_open_url_params_.reset(nullptr);
4726 return;
4727 }
4728
mariakhomenko44bdc4732015-04-29 01:55:384729 // Resume blocked requests for both the RenderViewHost and RenderFrameHost.
4730 // TODO(brettw): It seems bogus to reach into here and initialize the host.
dfalcantarae6b7b46752015-07-10 18:14:164731 if (is_resume_pending_) {
4732 is_resume_pending_ = false;
avi0f1bbc9712015-11-17 02:58:134733 GetRenderViewHost()->GetWidget()->Init();
dfalcantarae6b7b46752015-07-10 18:14:164734 GetMainFrame()->Init();
4735 }
mariakhomenko44bdc4732015-04-29 01:55:384736}
4737
[email protected]b172aee2012-04-10 17:05:264738bool WebContentsImpl::FocusLocationBarByDefault() {
Xiyuan Xia2a66b112018-12-06 15:52:164739 if (should_focus_location_bar_by_default_)
[email protected]0c9406632013-02-08 01:13:334740 return true;
Xiyuan Xia2a66b112018-12-06 15:52:164741
[email protected]0c9406632013-02-08 01:13:334742 return delegate_ && delegate_->ShouldFocusLocationBarByDefault(this);
[email protected]0bfbf882011-12-22 18:19:274743}
4744
Tommy C. Li8bb5bf42019-01-18 18:45:514745void WebContentsImpl::SetFocusToLocationBar() {
[email protected]0bfbf882011-12-22 18:19:274746 if (delegate_)
Tommy C. Li8bb5bf42019-01-18 18:45:514747 delegate_->SetFocusToLocationBar();
[email protected]c40d6232011-03-25 00:16:214748}
4749
clamy0e119882015-07-31 16:12:334750void WebContentsImpl::DidStartNavigation(NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:484751 TRACE_EVENT1("navigation", "WebContentsImpl::DidStartNavigation",
4752 "navigation_handle", navigation_handle);
Alan Cutterab48fc02020-02-24 12:26:424753 if (navigation_handle->IsInMainFrame())
4754 favicon_urls_.clear();
Mounir Lamouri7b4a1f232019-12-23 16:32:104755
Alexander Timin90c20c32020-08-12 15:28:324756 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4757 observer->DidStartNavigation(navigation_handle);
4758 });
Xiyuan Xia2a66b112018-12-06 15:52:164759 if (navigation_handle->IsInMainFrame()) {
4760 // When the browser is started with about:blank as the startup URL, focus
4761 // the location bar (which will also select its contents) so people can
4762 // simply begin typing to navigate elsewhere.
4763 //
4764 // We need to be careful not to trigger this for anything other than the
4765 // startup navigation. In particular, if we allow an attacker to open a
4766 // popup to about:blank, then navigate, focusing the Omnibox will cause the
4767 // end of the new URL to be scrolled into view instead of the start,
4768 // allowing the attacker to spoof other URLs. The conditions checked here
4769 // are all aimed at ensuring no such attacker-controlled navigation can
4770 // trigger this.
4771 should_focus_location_bar_by_default_ =
4772 controller_.IsInitialNavigation() &&
4773 !navigation_handle->IsRendererInitiated() &&
4774 navigation_handle->GetURL() == url::kAboutBlankURL;
4775 }
clamy0e119882015-07-31 16:12:334776}
4777
4778void WebContentsImpl::DidRedirectNavigation(
4779 NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:484780 TRACE_EVENT1("navigation", "WebContentsImpl::DidRedirectNavigation",
4781 "navigation_handle", navigation_handle);
Alexander Timin90c20c32020-08-12 15:28:324782 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4783 observer->DidRedirectNavigation(navigation_handle);
4784 });
jam5f358e52017-02-13 16:37:034785 // Notify accessibility if this is a reload. This has to called on the
4786 // BrowserAccessibilityManager associated with the old RFHI.
4787 if (navigation_handle->GetReloadType() != ReloadType::NONE) {
Mohamed Abdelhalim95794962019-09-20 11:16:494788 NavigationRequest* request = NavigationRequest::From(navigation_handle);
jam5f358e52017-02-13 16:37:034789 BrowserAccessibilityManager* manager =
Mohamed Abdelhalim95794962019-09-20 11:16:494790 request->frame_tree_node()
jam5f358e52017-02-13 16:37:034791 ->current_frame_host()
4792 ->browser_accessibility_manager();
4793 if (manager)
4794 manager->UserIsReloading();
4795 }
clamy0e119882015-07-31 16:12:334796}
4797
clamyefca29e2015-09-17 00:22:114798void WebContentsImpl::ReadyToCommitNavigation(
4799 NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:484800 TRACE_EVENT1("navigation", "WebContentsImpl::ReadyToCommitNavigation",
4801 "navigation_handle", navigation_handle);
Alexander Timin90c20c32020-08-12 15:28:324802 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4803 observer->ReadyToCommitNavigation(navigation_handle);
4804 });
Kenneth Russell954ed9ce2018-04-12 23:07:014805 // If any domains are blocked from accessing 3D APIs because they may
4806 // have caused the GPU to reset recently, unblock them here if the user
4807 // initiated this navigation. This implies that the user was involved in
4808 // the decision to navigate, so there's no concern about
4809 // denial-of-service issues. Want to do this as early as
4810 // possible to avoid race conditions with pages attempting to access
4811 // WebGL early on.
4812 //
4813 // TODO(crbug.com/617904): currently navigations initiated by the browser
4814 // (reload button, reload menu option, pressing return in the Omnibox)
4815 // return false from HasUserGesture(). If or when that is addressed,
4816 // remove the check for IsRendererInitiated() below.
4817 //
4818 // TODO(crbug.com/832180): HasUserGesture comes from the renderer
4819 // process and isn't validated. Until it is, don't trust it.
4820 if (!navigation_handle->IsRendererInitiated()) {
4821 GpuDataManagerImpl::GetInstance()->UnblockDomainFrom3DAPIs(
4822 navigation_handle->GetURL());
4823 }
4824
John Abd-El-Malekfde08e6da2017-12-05 04:06:244825 if (navigation_handle->IsSameDocument())
4826 return;
4827
Livvie Lin139bf442018-08-10 00:18:544828 // SSLInfo is not needed on subframe navigations since the main-frame
4829 // certificate is the only one that can be inspected (using the info
4830 // bubble) without refreshing the page with DevTools open.
Carlos ILaed1e7b2019-03-12 19:27:214831 // We don't call DidStartResourceResponse on net errors, since that results on
4832 // existing cert exceptions being revoked, which leads to weird behavior with
4833 // committed interstitials or while offline. We only need the error check for
4834 // the main frame case because unlike this method, SubresourceResponseStarted
4835 // does not get called on network errors.
4836 if (navigation_handle->IsInMainFrame() &&
4837 navigation_handle->GetNetErrorCode() == net::OK) {
Livvie Lin139bf442018-08-10 00:18:544838 controller_.ssl_manager()->DidStartResourceResponse(
Lukasz Anforowiczd334bba2020-02-10 23:32:554839 navigation_handle->GetURL(),
Camille Lamy62b826012019-02-26 09:15:474840 navigation_handle->GetSSLInfo().has_value()
4841 ? net::IsCertStatusError(
4842 navigation_handle->GetSSLInfo()->cert_status)
4843 : false);
4844 }
John Abd-El-Malekfde08e6da2017-12-05 04:06:244845
4846 SetNotWaitingForResponse();
clamyefca29e2015-09-17 00:22:114847}
4848
clamy0e119882015-07-31 16:12:334849void WebContentsImpl::DidFinishNavigation(NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:484850 TRACE_EVENT1("navigation", "WebContentsImpl::DidFinishNavigation",
4851 "navigation_handle", navigation_handle);
Steven Holte38041342018-06-22 22:00:574852
Alexander Timin90c20c32020-08-12 15:28:324853 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4854 observer->DidFinishNavigation(navigation_handle);
4855 });
Becca Hughesd11d6502018-07-31 17:01:284856 if (display_cutout_host_impl_)
4857 display_cutout_host_impl_->DidFinishNavigation(navigation_handle);
4858
jam5f358e52017-02-13 16:37:034859 if (navigation_handle->HasCommitted()) {
Ian Prestcdd843d2020-01-28 18:59:584860 // TODO(domfarolino, dmazzoni): Do this using WebContentsObserver. See
4861 // https://crbug.com/981271.
4862 BrowserAccessibilityManager* manager =
4863 static_cast<RenderFrameHostImpl*>(
4864 navigation_handle->GetRenderFrameHost())
4865 ->browser_accessibility_manager();
4866 if (manager) {
4867 if (navigation_handle->IsErrorPage()) {
4868 manager->NavigationFailed();
4869 } else {
4870 manager->NavigationSucceeded();
4871 }
4872 }
4873
Yue Ru Sun979c4b162019-11-06 16:11:044874 if (navigation_handle->IsInMainFrame()) {
4875 last_committed_source_id_including_same_document_ =
Steven Holte38041342018-06-22 22:00:574876 ukm::ConvertToSourceId(navigation_handle->GetNavigationId(),
4877 ukm::SourceIdType::NAVIGATION_ID);
Yue Ru Sun979c4b162019-11-06 16:11:044878
4879 if (!navigation_handle->IsSameDocument()) {
4880 was_ever_audible_ = false;
Yue Ru Sun979c4b162019-11-06 16:11:044881 }
Tommy Steimel18360512017-11-01 00:38:194882 }
Lan Weif81c6e7c2020-02-12 16:46:094883
4884 if (!navigation_handle->IsSameDocument())
4885 last_screen_orientation_change_time_ = base::TimeTicks();
dmazzonibf8cec42015-02-08 08:28:084886 }
Xiyuan Xia2a66b112018-12-06 15:52:164887
4888 // If we didn't end up on about:blank after setting this in DidStartNavigation
4889 // then don't focus the location bar.
4890 if (should_focus_location_bar_by_default_ &&
4891 navigation_handle->GetURL() != url::kAboutBlankURL) {
4892 should_focus_location_bar_by_default_ = false;
4893 }
yilkal796e89e2019-10-02 23:58:284894
yilkal172da772019-11-06 22:49:074895 if (navigation_handle->IsInMainFrame() && first_navigation_completed_)
4896 RecordMaxFrameCountUMA(max_loaded_frame_count_);
yilkal796e89e2019-10-02 23:58:284897
yilkal172da772019-11-06 22:49:074898 // If navigation has successfully finished in the main frame, set
4899 // |first_navigation_completed_| to true so that we will record
4900 // |max_loaded_frame_count_| above when future main frame navigations finish.
4901 if (navigation_handle->IsInMainFrame() && !navigation_handle->IsErrorPage()) {
4902 first_navigation_completed_ = true;
4903
4904 // Navigation has completed in main frame. Reset |max_loaded_frame_count_|.
4905 // |max_loaded_frame_count_| is not necessarily 1 if the navigation was
4906 // served from BackForwardCache.
4907 max_loaded_frame_count_ =
4908 GetMainFrame()->frame_tree_node()->GetFrameTreeSize();
yilkal796e89e2019-10-02 23:58:284909 }
Rakina Zata Amni347b70902020-07-22 10:49:044910
4911 if (web_preferences_) {
4912 // Update the WebPreferences for this WebContents that depends on changes
4913 // that might occur during navigation. This will only update the preferences
4914 // that needs to be updated (and won't cause an update/overwrite preferences
4915 // that needs to stay the same after navigations).
4916 bool value_changed_due_to_override =
4917 GetContentClient()->browser()->OverrideWebPreferencesAfterNavigation(
4918 this, web_preferences_.get());
4919 // We need to update the WebPreferences value on the renderer if the value
4920 // is changed due to the override above, or if the navigation is served from
4921 // the back-forward cache, because the WebPreferences value stored in the
4922 // renderer might be stale (because we don't send WebPreferences updates to
4923 // bfcached renderers).
4924 // TODO(rakina): Maybe handle the back-forward cache case in
4925 // ReadyToCommitNavigation instead?
4926 if (value_changed_due_to_override ||
4927 NavigationRequest::From(navigation_handle)
4928 ->IsServedFromBackForwardCache()) {
4929 SetWebPreferences(*web_preferences_.get());
4930 }
4931 }
[email protected]400992b2012-06-14 00:03:544932}
4933
[email protected]b80624c2014-02-09 02:46:554934void WebContentsImpl::DidFailLoadWithError(
4935 RenderFrameHostImpl* render_frame_host,
[email protected]b80624c2014-02-09 02:46:554936 const GURL& url,
Dave Tapuska924ef3c2020-01-22 18:20:594937 int error_code) {
Alexander Timin90c20c32020-08-12 15:28:324938 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4939 observer->DidFailLoad(render_frame_host, url, error_code);
4940 });
[email protected]b80624c2014-02-09 02:46:554941}
4942
[email protected]52913802013-12-10 05:52:184943void WebContentsImpl::NotifyChangedNavigationState(
4944 InvalidateTypes changed_flags) {
4945 NotifyNavigationStateChanged(changed_flags);
4946}
4947
lukasza1d025732016-09-28 21:36:084948bool WebContentsImpl::ShouldTransferNavigation(bool is_main_frame_navigation) {
creis29460272015-12-16 04:38:224949 if (!delegate_)
4950 return true;
lukasza1d025732016-09-28 21:36:084951 return delegate_->ShouldTransferNavigation(is_main_frame_navigation);
creis29460272015-12-16 04:38:224952}
4953
[email protected]aa62afd2014-04-22 19:22:464954bool WebContentsImpl::ShouldPreserveAbortedURLs() {
4955 if (!delegate_)
4956 return false;
4957 return delegate_->ShouldPreserveAbortedURLs(this);
4958}
4959
[email protected]0d0f4c492014-04-02 06:42:574960void WebContentsImpl::DidNavigateMainFramePreCommit(
[email protected]5cfbddc2014-06-23 23:52:234961 bool navigation_is_within_page) {
[email protected]0d0f4c492014-04-02 06:42:574962 // Ensure fullscreen mode is exited before committing the navigation to a
4963 // different page. The next page will not start out assuming it is in
4964 // fullscreen mode.
[email protected]5cfbddc2014-06-23 23:52:234965 if (navigation_is_within_page) {
[email protected]dfc39cb2014-04-09 22:58:194966 // No page change? Then, the renderer and browser can remain in fullscreen.
[email protected]0d0f4c492014-04-02 06:42:574967 return;
4968 }
Avi Drissman97aef042020-06-30 21:04:484969 if (IsFullscreen())
bokanece34a82016-01-28 19:49:464970 ExitFullscreen(false);
Avi Drissman97aef042020-06-30 21:04:484971 DCHECK(!IsFullscreen());
Joe Downingc1a57efe2018-05-09 18:23:544972
4973 // Clean up keyboard lock state when navigating.
4974 CancelKeyboardLock(keyboard_lock_widget_);
[email protected]0d0f4c492014-04-02 06:42:574975}
4976
[email protected]37567b432014-02-12 01:12:224977void WebContentsImpl::DidNavigateMainFramePostCommit(
sky8b00392d2015-01-10 00:30:284978 RenderFrameHostImpl* render_frame_host,
[email protected]37567b432014-02-12 01:12:224979 const LoadCommittedDetails& details,
4980 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
4981 if (details.is_navigation_to_different_page()) {
4982 // Clear the status bubble. This is a workaround for a bug where WebKit
4983 // doesn't let us know that the cursor left an element during a
4984 // transition (this is also why the mouse cursor remains as a hand after
4985 // clicking on a link); see bugs 1184641 and 980803. We don't want to
4986 // clear the bubble when a user navigates to a named anchor in the same
4987 // page.
Lukasz Anforowiczfd707142018-02-07 19:46:134988 ClearTargetURL();
lanwei9d343ad22015-02-11 01:46:004989
4990 RenderWidgetHostViewBase* rwhvb =
4991 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
4992 if (rwhvb)
4993 rwhvb->OnDidNavigateMainFrameToNewPage();
[email protected]37567b432014-02-12 01:12:224994 }
4995
[email protected]e85165c642014-06-10 14:34:314996 if (delegate_)
[email protected]37567b432014-02-12 01:12:224997 delegate_->DidNavigateMainFramePostCommit(this);
[email protected]e85165c642014-06-10 14:34:314998 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
Shivani Sharma985474f2019-05-23 21:36:474999
Carlos Caballero91fffb22019-10-29 15:24:305000 if (details.is_navigation_to_different_page() &&
5001 GetRenderViewHost()->did_first_visually_non_empty_paint()) {
5002 // This event will not fire again if the page is restored from the
5003 // BackForwardCache. So fire it ourselves if needed.
5004 DidFirstVisuallyNonEmptyPaint(GetRenderViewHost());
5005 }
Carlos Caballero1215f882019-10-29 15:58:435006
5007 if (GetRenderViewHost()->theme_color() != last_sent_theme_color_) {
5008 // This event will not fire again if the page is restored from the
5009 // BackForwardCache. So fire it ourselves if needed.
5010 OnThemeColorChanged(GetRenderViewHost());
5011 }
[email protected]37567b432014-02-12 01:12:225012}
5013
5014void WebContentsImpl::DidNavigateAnyFramePostCommit(
5015 RenderFrameHostImpl* render_frame_host,
5016 const LoadCommittedDetails& details,
5017 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
[email protected]b4c84012014-04-28 19:51:105018 // Now that something has committed, we don't need to track whether the
5019 // initial page has been accessed.
5020 has_accessed_initial_document_ = false;
5021
[email protected]37567b432014-02-12 01:12:225022 // If we navigate off the page, close all JavaScript dialogs.
eugenebutee08663a2017-04-27 17:43:125023 if (!details.is_same_document)
creis89a0f782015-05-27 16:13:175024 CancelActiveAndPendingDialogs();
[email protected]37567b432014-02-12 01:12:225025
avid53461d2016-02-25 17:15:045026 // If this is a user-initiated navigation, start allowing JavaScript dialogs
5027 // again.
avi5d3b8692016-10-12 22:00:465028 if (params.gesture == NavigationGestureUser && dialog_manager_) {
avi6879fcf2017-01-21 05:27:535029 dialog_manager_->CancelDialogs(this, /*reset_state=*/true);
avi5d3b8692016-10-12 22:00:465030 }
[email protected]37567b432014-02-12 01:12:225031}
5032
[email protected]277857a2014-06-03 10:38:015033bool WebContentsImpl::CanOverscrollContent() const {
[email protected]e85165c642014-06-10 14:34:315034 // Disable overscroll when touch emulation is on. See crbug.com/369938.
[email protected]34ff1cfc2014-08-20 06:16:055035 if (force_disable_overscroll_content_)
[email protected]e85165c642014-06-10 14:34:315036 return false;
5037
[email protected]37567b432014-02-12 01:12:225038 if (delegate_)
5039 return delegate_->CanOverscrollContent();
5040
5041 return false;
5042}
5043
Carlos Caballero1215f882019-10-29 15:58:435044void WebContentsImpl::OnThemeColorChanged(RenderViewHostImpl* source) {
5045 if (source->did_first_visually_non_empty_paint() &&
5046 last_sent_theme_color_ != source->theme_color()) {
Alexander Timin90c20c32020-08-12 15:28:325047 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5048 observer->DidChangeThemeColor();
5049 });
peter90afaba2015-06-01 12:05:295050 }
[email protected]e7104762014-06-20 19:17:255051}
5052
Gyuyoung Kim1905f7c2020-05-02 00:00:245053void WebContentsImpl::DidLoadResourceFromMemoryCache(
nicka0ac8382016-12-15 23:59:235054 RenderFrameHostImpl* source,
[email protected]724159a2010-12-30 01:11:185055 const GURL& url,
[email protected]70435962011-08-02 20:13:285056 const std::string& http_method,
[email protected]6d6cfb3a2012-05-23 22:53:185057 const std::string& mime_type,
Kinuko Yasuda433f710a2020-02-14 02:11:585058 network::mojom::RequestDestination request_destination) {
Alexander Timin90c20c32020-08-12 15:28:325059 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5060 observer->DidLoadResourceFromMemoryCache(url, mime_type,
5061 request_destination);
5062 });
[email protected]b0f724c2013-09-05 04:21:135063
Steven Bingler674fb0822018-12-12 18:04:525064 if (url.is_valid() && url.SchemeIsHTTPOrHTTPS()) {
nicka0ac8382016-12-15 23:59:235065 StoragePartition* partition = source->GetProcess()->GetStoragePartition();
John Abd-El-Malekf4fe9d82019-07-31 04:05:595066 partition->GetNetworkContext()->NotifyExternalCacheHit(
Matt Menke2a33dee2019-12-02 17:01:545067 url, http_method, source->GetNetworkIsolationKey());
[email protected]8bfc8272013-09-09 20:10:535068 }
[email protected]724159a2010-12-30 01:11:185069}
5070
carloskd9d97942017-02-16 08:58:095071void WebContentsImpl::DidDisplayInsecureContent() {
estarkc2273502016-10-12 22:03:025072 controller_.ssl_manager()->DidDisplayMixedContent();
[email protected]724159a2010-12-30 01:11:185073}
5074
Dave Tapuskaa657d872019-10-21 20:23:215075void WebContentsImpl::DidContainInsecureFormAction() {
elawrenceb2ac2a232017-03-27 21:46:255076 controller_.ssl_manager()->DidContainInsecureFormAction();
5077}
5078
Julie Jeongeun Kim0b103492020-01-29 05:30:515079void WebContentsImpl::DocumentAvailableInMainFrame() {
Alexander Timin90c20c32020-08-12 15:28:325080 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5081 observer->DocumentAvailableInMainFrame();
5082 });
Julie Jeongeun Kim0b103492020-01-29 05:30:515083}
5084
nicka0ac8382016-12-15 23:59:235085void WebContentsImpl::OnDidRunInsecureContent(RenderFrameHostImpl* source,
5086 const GURL& security_origin,
estark910b4572015-12-09 20:55:415087 const GURL& target_url) {
nicka0ac8382016-12-15 23:59:235088 // TODO(nick, estark): Should we call FilterURL using |source|'s process on
5089 // these parameters? |target_url| seems unused, except for a log message. And
5090 // |security_origin| might be replaceable with the origin of the main frame.
carloskd9d97942017-02-16 08:58:095091 DidRunInsecureContent(security_origin, target_url);
5092}
5093
5094void WebContentsImpl::DidRunInsecureContent(const GURL& security_origin,
5095 const GURL& target_url) {
[email protected]9450c462013-11-23 01:22:585096 LOG(WARNING) << security_origin << " ran insecure content from "
5097 << target_url.possibly_invalid_spec();
[email protected]e6e30ac2014-01-13 21:24:395098 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
estark910b4572015-12-09 20:55:415099 if (base::EndsWith(security_origin.spec(), kDotGoogleDotCom,
brettwa7ff1b292015-07-16 17:49:295100 base::CompareCase::INSENSITIVE_ASCII))
[email protected]e6e30ac2014-01-13 21:24:395101 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
estarkc2273502016-10-12 22:03:025102 controller_.ssl_manager()->DidRunMixedContent(security_origin);
[email protected]724159a2010-12-30 01:11:185103}
5104
carloskd9d97942017-02-16 08:58:095105void WebContentsImpl::PassiveInsecureContentFound(const GURL& resource_url) {
Sergey Kuznetsov3ebc01b2018-02-01 04:57:365106 if (delegate_) {
5107 delegate_->PassiveInsecureContentFound(resource_url);
5108 }
carloskd9d97942017-02-16 08:58:095109}
5110
5111bool WebContentsImpl::ShouldAllowRunningInsecureContent(
carloskd9d97942017-02-16 08:58:095112 bool allowed_per_prefs,
5113 const url::Origin& origin,
5114 const GURL& resource_url) {
Sergey Kuznetsov3ebc01b2018-02-01 04:57:365115 if (delegate_) {
Carlos IL29294a62020-05-15 00:21:165116 return delegate_->ShouldAllowRunningInsecureContent(this, allowed_per_prefs,
5117 origin, resource_url);
Sergey Kuznetsov3ebc01b2018-02-01 04:57:365118 }
5119
5120 return allowed_per_prefs;
carloskd9d97942017-02-16 08:58:095121}
5122
Lukasz Anforowicze1b954d92017-10-30 21:28:065123void WebContentsImpl::ViewSource(RenderFrameHostImpl* frame) {
5124 DCHECK_EQ(this, WebContents::FromRenderFrameHost(frame));
5125
5126 // Don't do anything if there is no |delegate_| that could accept and show the
5127 // new WebContents containing the view-source.
5128 if (!delegate_)
5129 return;
5130
5131 // Use the last committed entry, since the pending entry hasn't loaded yet and
5132 // won't be copied into the cloned tab.
5133 NavigationEntryImpl* last_committed_entry =
Fergal Daly09d6c762020-05-29 02:05:185134 GetController().GetLastCommittedEntry();
Lukasz Anforowicze1b954d92017-10-30 21:28:065135 if (!last_committed_entry)
5136 return;
5137
5138 FrameNavigationEntry* frame_entry =
5139 last_committed_entry->GetFrameEntry(frame->frame_tree_node());
5140 if (!frame_entry)
5141 return;
5142
5143 // Any new WebContents opened while this WebContents is in fullscreen can be
5144 // used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:455145 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
5146 // The new view source contents will be independent of this contents, so
5147 // release the fullscreen block.
5148 fullscreen_block.RunAndReset();
Lukasz Anforowicze1b954d92017-10-30 21:28:065149
5150 // We intentionally don't share the SiteInstance with the original frame so
5151 // that view source has a consistent process model and always ends up in a new
5152 // process (https://crbug.com/699493).
5153 scoped_refptr<SiteInstanceImpl> site_instance_for_view_source = nullptr;
Lukasz Anforowicz435bcb582019-07-12 20:50:065154 // Referrer and initiator are not important, because view-source should not
5155 // hit the network, but should be served from the cache instead.
Lukasz Anforowicze1b954d92017-10-30 21:28:065156 Referrer referrer_for_view_source;
Lukasz Anforowicz435bcb582019-07-12 20:50:065157 base::Optional<url::Origin> initiator_for_view_source = base::nullopt;
Lukasz Anforowicze1b954d92017-10-30 21:28:065158 // Do not restore title, derive it from the url.
5159 base::string16 title_for_view_source;
5160 auto navigation_entry = std::make_unique<NavigationEntryImpl>(
5161 site_instance_for_view_source, frame_entry->url(),
Lukasz Anforowicz435bcb582019-07-12 20:50:065162 referrer_for_view_source, initiator_for_view_source,
5163 title_for_view_source, ui::PAGE_TRANSITION_LINK,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:095164 /* is_renderer_initiated = */ false,
5165 /* blob_url_loader_factory = */ nullptr);
Joel Hockey891e88062020-04-30 05:38:445166 const GURL url(content::kViewSourceScheme + std::string(":") +
5167 frame_entry->url().spec());
5168 navigation_entry->SetVirtualURL(url);
Matt Menkea56c5992020-04-10 20:53:565169 navigation_entry->set_isolation_info(
5170 frame->GetIsolationInfoForSubresources());
Yao Xiaof68f57d2019-10-03 04:20:055171
Lukasz Anforowicze1b954d92017-10-30 21:28:065172 // Do not restore scroller position.
5173 // TODO(creis, lukasza, arthursonzogni): Do not reuse the original PageState,
5174 // but start from a new one and only copy the needed data.
5175 const PageState& new_page_state =
5176 frame_entry->page_state().RemoveScrollOffset();
5177
5178 scoped_refptr<FrameNavigationEntry> new_frame_entry =
5179 navigation_entry->root_node()->frame_entry;
5180 new_frame_entry->set_method(frame_entry->method());
5181 new_frame_entry->SetPageState(new_page_state);
5182
5183 // Create a new WebContents, which is used to display the source code.
erikchenbee5c9622018-04-27 19:30:255184 std::unique_ptr<WebContents> view_source_contents =
Erik Chenbb8e738e2018-04-28 14:10:435185 Create(CreateParams(GetBrowserContext()));
Lukasz Anforowicze1b954d92017-10-30 21:28:065186
5187 // Restore the previously created NavigationEntry.
5188 std::vector<std::unique_ptr<NavigationEntry>> navigation_entries;
5189 navigation_entries.push_back(std::move(navigation_entry));
5190 view_source_contents->GetController().Restore(0, RestoreType::CURRENT_SESSION,
5191 &navigation_entries);
5192
5193 // Add |view_source_contents| as a new tab.
5194 gfx::Rect initial_rect;
5195 constexpr bool kUserGesture = true;
5196 bool ignored_was_blocked;
Joel Hockey891e88062020-04-30 05:38:445197 delegate_->AddNewContents(this, std::move(view_source_contents), url,
Lukasz Anforowicze1b954d92017-10-30 21:28:065198 WindowOpenDisposition::NEW_FOREGROUND_TAB,
5199 initial_rect, kUserGesture, &ignored_was_blocked);
5200 // Note that the |delegate_| could have deleted |view_source_contents| during
5201 // AddNewContents method call.
5202}
5203
Lukasz Anforowiczd334bba2020-02-10 23:32:555204void WebContentsImpl::SubresourceResponseStarted(const GURL& url,
5205 net::CertStatus cert_status) {
5206 controller_.ssl_manager()->DidStartResourceResponse(url, cert_status);
Jay Civellid5904f02018-03-23 19:43:575207 SetNotWaitingForResponse();
5208}
5209
Jay Civelli116683f2018-03-27 19:56:235210void WebContentsImpl::ResourceLoadComplete(
Jay Civelli52a63302018-04-30 22:39:555211 RenderFrameHost* render_frame_host,
Clark DuVall36164bd2018-08-09 22:49:085212 const GlobalRequestID& request_id,
Minggang Wangee5af392020-02-05 02:55:285213 blink::mojom::ResourceLoadInfoPtr resource_load_info) {
Alexander Timin90c20c32020-08-12 15:28:325214 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5215 observer->ResourceLoadComplete(render_frame_host, request_id,
5216 *resource_load_info);
5217 });
John Abd-El-Malekd4882642017-12-04 21:45:195218}
5219
Rakina Zata Amni347b70902020-07-22 10:49:045220const WebPreferences& WebContentsImpl::GetOrCreateWebPreferences() {
5221 // Compute WebPreferences based on the current state if it's null.
5222 if (!web_preferences_)
Rakina Zata Amni4029b6d2020-07-28 02:36:205223 OnWebPreferencesChanged();
Rakina Zata Amni347b70902020-07-22 10:49:045224 return *web_preferences_.get();
5225}
5226
5227bool WebContentsImpl::IsWebPreferencesSet() const {
5228 return web_preferences_.get();
5229}
5230
5231void WebContentsImpl::SetWebPreferences(const WebPreferences& prefs) {
5232 web_preferences_ = std::make_unique<WebPreferences>(prefs);
5233 // Get all the RenderViewHosts (except the ones for currently back-forward
5234 // cached pages), and make them send the current WebPreferences
5235 // to the renderer. WebPreferences updates for back-forward cached pages will
5236 // be sent when we restore those pages from the back-forward cache.
5237 for (auto& rvh : frame_tree_.render_view_hosts()) {
5238 rvh.second->SendWebPreferencesToRenderer();
5239 }
5240}
5241
5242void WebContentsImpl::RecomputeWebPreferencesSlow() {
Rakina Zata Amni4029b6d2020-07-28 02:36:205243 // OnWebPreferencesChanged is a no-op when this is true.
5244 if (updating_web_preferences_)
5245 return;
Rakina Zata Amni347b70902020-07-22 10:49:045246 // Resets |web_preferences_| so that we won't have any cached value for slow
5247 // attributes (which won't get recomputed if we have pre-existing values for
5248 // them).
5249 web_preferences_.reset();
Rakina Zata Amni4029b6d2020-07-28 02:36:205250 OnWebPreferencesChanged();
Rakina Zata Amni347b70902020-07-22 10:49:045251}
5252
Wei Li5bb659742018-02-14 03:07:585253void WebContentsImpl::PrintCrossProcessSubframe(
5254 const gfx::Rect& rect,
5255 int document_cookie,
5256 RenderFrameHost* subframe_host) {
Wei Li5c0b4d12018-03-22 15:05:225257 auto* outer_contents = GetOuterWebContents();
5258 if (outer_contents) {
5259 // When an extension or app page is printed, the content should be
5260 // composited with outer content, so the outer contents should handle the
5261 // print request.
5262 outer_contents->PrintCrossProcessSubframe(rect, document_cookie,
5263 subframe_host);
5264 return;
5265 }
5266
Wei Li5bb659742018-02-14 03:07:585267 // If there is no delegate such as in tests or during deletion, do nothing.
5268 if (!delegate_)
5269 return;
5270
5271 delegate_->PrintCrossProcessSubframe(this, rect, document_cookie,
5272 subframe_host);
5273}
5274
ckitagawa8695799b2020-02-05 16:08:495275void WebContentsImpl::CapturePaintPreviewOfCrossProcessSubframe(
5276 const gfx::Rect& rect,
5277 const base::UnguessableToken& guid,
5278 RenderFrameHost* render_frame_host) {
5279 if (!delegate_)
5280 return;
ckitagawac43ac982020-07-07 17:41:175281 delegate_->CapturePaintPreviewOfSubframe(this, rect, guid, render_frame_host);
ckitagawa8695799b2020-02-05 16:08:495282}
5283
rob.buis300b0872017-03-10 20:43:585284#if defined(OS_ANDROID)
5285base::android::ScopedJavaLocalRef<jobject>
5286WebContentsImpl::GetJavaRenderFrameHostDelegate() {
5287 return GetJavaWebContents();
5288}
5289#endif
5290
Hiroki Nakagawa39d1bbe2020-07-14 16:15:525291void WebContentsImpl::OnDidDisplayContentWithCertificateErrors() {
estarkc2273502016-10-12 22:03:025292 controller_.ssl_manager()->DidDisplayContentWithCertErrors();
estark910b4572015-12-09 20:55:415293}
5294
5295void WebContentsImpl::OnDidRunContentWithCertificateErrors(
Zhuoyu Qian4353f7f2018-01-08 05:33:005296 RenderFrameHostImpl* source) {
Emily Starkabbdd662020-06-05 02:40:135297 // For RenderFrameHosts that are inactive and going to be discarded, we can
5298 // disregard this message; there's no need to update the UI if the UI will
5299 // never be shown again.
5300 //
5301 // We still process this message for speculative RenderFrameHosts. This can
5302 // happen when a subframe's main resource has a certificate error. The
5303 // currently committed navigation entry will get marked as having run insecure
5304 // content and that will carry over to the navigation entry for the
5305 // speculative RFH when it commits.
5306 if (source->lifecycle_state() !=
5307 RenderFrameHostImpl::LifecycleState::kSpeculative &&
5308 source->IsInactiveAndDisallowReactivation()) {
estarkaeda1422016-05-10 02:31:125309 return;
Emily Starkabbdd662020-06-05 02:40:135310 }
estarkcd2e30c2016-08-12 06:51:155311 controller_.ssl_manager()->DidRunContentWithCertErrors(
Emily Starkabbdd662020-06-05 02:40:135312 source->GetMainFrame()->GetLastCommittedOrigin().GetURL());
estark910b4572015-12-09 20:55:415313}
5314
Kouhei Ueno97e0990d2019-09-25 02:57:275315void WebContentsImpl::DOMContentLoaded(RenderFrameHost* render_frame_host) {
Alexander Timin90c20c32020-08-12 15:28:325316 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5317 observer->DOMContentLoaded(render_frame_host);
5318 });
[email protected]724159a2010-12-30 01:11:185319}
5320
Gyuyoung Kim525e0c5d2020-03-09 15:04:195321void WebContentsImpl::OnDidFinishLoad(RenderFrameHost* render_frame_host,
nicka0ac8382016-12-15 23:59:235322 const GURL& url) {
[email protected]8b3af1e2014-01-24 13:29:125323 GURL validated_url(url);
Gyuyoung Kim525e0c5d2020-03-09 15:04:195324 render_frame_host->GetProcess()->FilterURL(false, &validated_url);
[email protected]028053d42014-03-05 22:20:375325
Alexander Timin90c20c32020-08-12 15:28:325326 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5327 observer->DidFinishLoad(render_frame_host, validated_url);
5328 });
yilkal172da772019-11-06 22:49:075329 size_t tree_size = frame_tree_.root()->GetFrameTreeSize();
5330 if (max_loaded_frame_count_ < tree_size)
5331 max_loaded_frame_count_ = tree_size;
5332
Gyuyoung Kim525e0c5d2020-03-09 15:04:195333 if (!render_frame_host->GetParent())
yilkal172da772019-11-06 22:49:075334 UMA_HISTOGRAM_COUNTS_1000("Navigation.MainFrame.FrameCount", tree_size);
[email protected]1a55c5be2011-11-29 11:36:315335}
5336
Dave Tapuska549baab2019-03-19 15:52:405337void WebContentsImpl::OnGoToEntryAtOffset(RenderFrameHostImpl* source,
Julie Jeongeun Kim144f8192020-01-18 06:59:035338 int32_t offset,
Dave Tapuska043b94a2019-09-10 14:14:355339 bool has_user_gesture) {
Arthur Sonzognia7d715a2018-09-20 16:11:135340 // Non-user initiated navigations coming from the renderer should be ignored
5341 // if there is an ongoing browser-initiated navigation.
5342 // See https://crbug.com/879965.
5343 // TODO(arthursonzogni): See if this should check for ongoing navigations in
5344 // the frame(s) affected by the session history navigation, rather than just
5345 // the main frame.
Kevin McNee96851e12020-07-16 03:43:225346 if (Navigator::ShouldIgnoreIncomingRendererRequest(
5347 frame_tree_.root()->navigation_request(), has_user_gesture))
5348 return;
Arthur Sonzognia7d715a2018-09-20 16:11:135349
nicka0ac8382016-12-15 23:59:235350 // All frames are allowed to navigate the global history.
Dave Tapuska8bfd84c2019-03-26 20:47:165351 if (!delegate_ || delegate_->OnGoToEntryOffset(offset)) {
arthursonzognib93a4472020-04-10 07:38:005352 if (source->IsSandboxed(network::mojom::WebSandboxFlags::kTopNavigation)) {
Dave Tapuska8bfd84c2019-03-26 20:47:165353 // Keep track of whether this is a session history from a sandboxed iframe
5354 // with top level navigation disallowed.
5355 controller_.GoToOffsetInSandboxedFrame(offset,
5356 source->GetFrameTreeNodeId());
5357 } else {
5358 controller_.GoToOffset(offset);
5359 }
5360 }
[email protected]216813952011-05-19 22:21:265361}
5362
Dave Tapuska4c02911b2020-02-14 22:52:075363void WebContentsImpl::OnPageScaleFactorChanged(RenderFrameHostImpl* source,
nicka0ac8382016-12-15 23:59:235364 float page_scale_factor) {
mcnee336ea2c2017-05-23 22:50:595365#if !defined(OS_ANDROID)
5366 // While page scale factor is used on mobile, this PageScaleFactorIsOne logic
5367 // is only needed on desktop.
mcnee432e47d2015-11-09 19:37:465368 bool is_one = page_scale_factor == 1.f;
5369 if (is_one != page_scale_factor_is_one_) {
5370 page_scale_factor_is_one_ = is_one;
5371
5372 HostZoomMapImpl* host_zoom_map =
5373 static_cast<HostZoomMapImpl*>(HostZoomMap::GetForWebContents(this));
5374
nicka0ac8382016-12-15 23:59:235375 if (host_zoom_map) {
mcnee432e47d2015-11-09 19:37:465376 host_zoom_map->SetPageScaleFactorIsOneForView(
Dave Tapuska4c02911b2020-02-14 22:52:075377 source->GetProcess()->GetID(),
5378 source->GetRenderViewHost()->GetRoutingID(),
mcnee432e47d2015-11-09 19:37:465379 page_scale_factor_is_one_);
5380 }
5381 }
mcnee336ea2c2017-05-23 22:50:595382#endif // !defined(OS_ANDROID)
mcnee432e47d2015-11-09 19:37:465383
Alexander Timin90c20c32020-08-12 15:28:325384 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5385 observer->OnPageScaleFactorChanged(page_scale_factor);
5386 });
mcnee432e47d2015-11-09 19:37:465387}
5388
W. James MacLean62198672019-06-04 16:46:105389void WebContentsImpl::OnTextAutosizerPageInfoChanged(
Henrique Ferreiroba535472020-04-21 11:38:365390 RenderFrameHostImpl* source,
5391 blink::mojom::TextAutosizerPageInfoPtr page_info) {
W. James MacLean62198672019-06-04 16:46:105392 // Keep a copy of |page_info| in case we create a new RenderView before
5393 // the next update.
Henrique Ferreiroba535472020-04-21 11:38:365394 text_autosizer_page_info_.main_frame_width = page_info->main_frame_width;
5395 text_autosizer_page_info_.main_frame_layout_width =
5396 page_info->main_frame_layout_width;
5397 text_autosizer_page_info_.device_scale_adjustment =
5398 page_info->device_scale_adjustment;
Antonio Gomesda7e03d2020-08-05 15:03:085399
5400 auto remote_frames_broadcast_callback = base::BindRepeating(
5401 [](const blink::mojom::TextAutosizerPageInfo& page_info,
5402 RenderFrameProxyHost* proxy_host) {
5403 DCHECK(proxy_host);
5404 proxy_host->GetAssociatedRemoteMainFrame()->UpdateTextAutosizerPageInfo(
5405 page_info.Clone());
5406 },
5407 text_autosizer_page_info_);
5408
5409 frame_tree_.root()->render_manager()->ExecuteRemoteFramesBroadcastMethod(
5410 std::move(remote_frames_broadcast_callback), source->GetSiteInstance());
W. James MacLean62198672019-06-04 16:46:105411}
5412
Kent Tamura8c9e0562018-11-06 07:02:195413void WebContentsImpl::EnumerateDirectory(
5414 RenderFrameHost* render_frame_host,
Kent Tamura3abb32d2020-07-02 00:23:015415 scoped_refptr<FileChooserImpl::FileSelectListenerImpl> listener,
Kent Tamura8c9e0562018-11-06 07:02:195416 const base::FilePath& directory_path) {
Avi Drissman1a55a9d62020-03-10 18:56:455417 // Any explicit focusing of another window while this WebContents is in
5418 // fullscreen can be used to confuse the user, so drop fullscreen.
5419 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
5420 listener->SetFullscreenBlock(std::move(fullscreen_block));
5421
Kent Tamura8c9e0562018-11-06 07:02:195422 if (delegate_)
5423 delegate_->EnumerateDirectory(this, std::move(listener), directory_path);
5424 else
5425 listener->FileSelectionCanceled();
[email protected]3a29a6e2011-08-24 18:26:215426}
5427
Dave Tapuskaf9fc3122019-10-18 19:42:555428void WebContentsImpl::RegisterProtocolHandler(RenderFrameHostImpl* source,
5429 const std::string& protocol,
5430 const GURL& url,
5431 const base::string16& title,
5432 bool user_gesture) {
nicka0ac8382016-12-15 23:59:235433 // TODO(nick): Do we need to apply FilterURL to |url|?
[email protected]e5f2de02012-07-20 22:15:435434 if (!delegate_)
5435 return;
5436
Raymes Khoury58373df2019-08-06 06:29:205437 if (!AreValidRegisterProtocolHandlerArguments(
5438 protocol, url, source->GetLastCommittedOrigin())) {
5439 ReceivedBadMessage(source->GetProcess(),
5440 bad_message::REGISTER_PROTOCOL_HANDLER_INVALID_URL);
[email protected]b9535422012-02-09 01:47:595441 return;
Raymes Khoury58373df2019-08-06 06:29:205442 }
[email protected]8f810632013-06-06 22:33:325443
Carlos Caballero8a6c6b72020-07-20 16:56:225444 delegate_->RegisterProtocolHandler(source, protocol, url, user_gesture);
[email protected]7d189022011-08-25 22:54:205445}
5446
Dave Tapuskaf9fc3122019-10-18 19:42:555447void WebContentsImpl::UnregisterProtocolHandler(RenderFrameHostImpl* source,
5448 const std::string& protocol,
5449 const GURL& url,
5450 bool user_gesture) {
nicka0ac8382016-12-15 23:59:235451 // TODO(nick): Do we need to apply FilterURL to |url|?
[email protected]f5273e52014-07-14 16:30:205452 if (!delegate_)
5453 return;
5454
Raymes Khoury58373df2019-08-06 06:29:205455 if (!AreValidRegisterProtocolHandlerArguments(
5456 protocol, url, source->GetLastCommittedOrigin())) {
5457 ReceivedBadMessage(source->GetProcess(),
5458 bad_message::REGISTER_PROTOCOL_HANDLER_INVALID_URL);
[email protected]f5273e52014-07-14 16:30:205459 return;
Raymes Khoury58373df2019-08-06 06:29:205460 }
[email protected]f5273e52014-07-14 16:30:205461
Carlos Caballero8a6c6b72020-07-20 16:56:225462 delegate_->UnregisterProtocolHandler(source, protocol, url, user_gesture);
[email protected]f5273e52014-07-14 16:30:205463}
5464
Marijn Kruisselbrink7f519672019-02-05 19:12:505465void WebContentsImpl::OnAppCacheAccessed(const GURL& manifest_url,
[email protected]b172aee2012-04-10 17:05:265466 bool blocked_by_policy) {
nicka0ac8382016-12-15 23:59:235467 // TODO(nick): Should we consider |source| here? Should we call FilterURL on
5468 // |manifest_url|?
5469
[email protected]7fc4bbb2011-09-08 21:23:105470 // Notify observers about navigation.
Alexander Timin90c20c32020-08-12 15:28:325471 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5472 observer->AppCacheAccessed(manifest_url, blocked_by_policy);
5473 });
[email protected]7fc4bbb2011-09-08 21:23:105474}
5475
Gyuyoung Kimc5f4ac12020-05-08 10:59:395476void WebContentsImpl::DomOperationResponse(const std::string& json_string) {
5477 // TODO(lukasza): The notification below should probably indicate which
5478 // RenderFrameHostImpl the message is coming from. This can enable tests to
5479 // talk to 2 frames at the same time, without being confused which frame a
5480 // given response comes from. See also a corresponding TODO in the
5481 // ExecuteScriptHelper in //content/public/test/browser_test_utils.cc
5482 NotificationService::current()->Notify(
5483 NOTIFICATION_DOM_OPERATION_RESPONSE, Source<WebContents>(this),
5484 Details<const std::string>(&json_string));
5485}
5486
Gyuyoung Kim4c50517842020-06-04 17:50:445487void WebContentsImpl::SavableResourceLinksResponse(
5488 RenderFrameHostImpl* source,
5489 const std::vector<GURL>& resources_list,
5490 blink::mojom::ReferrerPtr referrer,
5491 const std::vector<blink::mojom::SavableSubframePtr>& subframes) {
5492 save_package_->SavableResourceLinksResponse(source, resources_list,
5493 std::move(referrer), subframes);
5494}
5495
5496void WebContentsImpl::SavableResourceLinksError(RenderFrameHostImpl* source) {
5497 save_package_->SavableResourceLinksError(source);
5498}
5499
Alexander Timin17edc742020-04-23 18:22:185500void WebContentsImpl::OnServiceWorkerAccessed(
5501 RenderFrameHost* render_frame_host,
5502 const GURL& scope,
5503 AllowServiceWorkerResult allowed) {
Alexander Timin90c20c32020-08-12 15:28:325504 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5505 observer->OnServiceWorkerAccessed(render_frame_host, scope, allowed);
5506 });
Alexander Timin17edc742020-04-23 18:22:185507}
5508
5509void WebContentsImpl::OnServiceWorkerAccessed(
5510 NavigationHandle* navigation,
5511 const GURL& scope,
5512 AllowServiceWorkerResult allowed) {
Alexander Timin90c20c32020-08-12 15:28:325513 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5514 observer->OnServiceWorkerAccessed(navigation, scope, allowed);
5515 });
Alexander Timin17edc742020-04-23 18:22:185516}
5517
Miyoung Shincb6475a2019-11-09 10:49:455518void WebContentsImpl::OnColorChooserFactoryReceiver(
Julie Jeongeun Kim8e2879e2019-08-06 23:55:205519 mojo::PendingReceiver<blink::mojom::ColorChooserFactory> receiver) {
5520 color_chooser_factory_receivers_.Add(this, std::move(receiver));
Joel Hockey85b379d2017-12-11 10:42:135521}
5522
5523void WebContentsImpl::OpenColorChooser(
Julie Jeongeun Kim8e2879e2019-08-06 23:55:205524 mojo::PendingReceiver<blink::mojom::ColorChooser> chooser_receiver,
5525 mojo::PendingRemote<blink::mojom::ColorChooserClient> client,
[email protected]8ed16472014-04-11 19:02:485526 SkColor color,
Joel Hockey163835a2017-12-20 11:51:575527 std::vector<blink::mojom::ColorSuggestionPtr> suggestions) {
Joel Hockey85b379d2017-12-11 10:42:135528 content::ColorChooser* new_color_chooser =
Ivan Kotenkov2c0d2bb32017-11-01 15:41:285529 delegate_ ? delegate_->OpenColorChooser(this, color, suggestions)
5530 : nullptr;
[email protected]820957a2014-01-14 14:56:305531 if (!new_color_chooser)
[email protected]cb805452013-05-22 15:16:215532 return;
[email protected]8ed16472014-04-11 19:02:485533
Joel Hockey85b379d2017-12-11 10:42:135534 color_chooser_.reset();
5535 color_chooser_ = std::make_unique<ColorChooser>(
Julie Jeongeun Kim8e2879e2019-08-06 23:55:205536 new_color_chooser, std::move(chooser_receiver), std::move(client));
[email protected]da8543762012-03-20 08:52:205537}
5538
brettw4b461082016-11-19 18:55:165539#if BUILDFLAG(ENABLE_PLUGINS)
nicka0ac8382016-12-15 23:59:235540void WebContentsImpl::OnPepperInstanceCreated(RenderFrameHostImpl* source,
5541 int32_t pp_instance) {
Alexander Timin90c20c32020-08-12 15:28:325542 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5543 observer->PepperInstanceCreated();
5544 });
nicka0ac8382016-12-15 23:59:235545 pepper_playback_observer_->PepperInstanceCreated(source, pp_instance);
emaxxe70f5e12015-05-29 11:26:005546}
5547
nicka0ac8382016-12-15 23:59:235548void WebContentsImpl::OnPepperInstanceDeleted(RenderFrameHostImpl* source,
5549 int32_t pp_instance) {
Alexander Timin90c20c32020-08-12 15:28:325550 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5551 observer->PepperInstanceDeleted();
5552 });
nicka0ac8382016-12-15 23:59:235553 pepper_playback_observer_->PepperInstanceDeleted(source, pp_instance);
emaxxe70f5e12015-05-29 11:26:005554}
5555
nicka0ac8382016-12-15 23:59:235556void WebContentsImpl::OnPepperPluginHung(RenderFrameHostImpl* source,
5557 int plugin_child_id,
tommyclie6633ca72014-10-31 00:40:425558 const base::FilePath& path,
5559 bool is_hung) {
Steven Holte95922222018-09-14 20:06:235560 UMA_HISTOGRAM_COUNTS_1M("Pepper.PluginHung", 1);
tommyclie6633ca72014-10-31 00:40:425561
Alexander Timin90c20c32020-08-12 15:28:325562 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5563 observer->PluginHungStatusChanged(plugin_child_id, path, is_hung);
5564 });
tommyclie6633ca72014-10-31 00:40:425565}
5566
nicka0ac8382016-12-15 23:59:235567void WebContentsImpl::OnPepperStartsPlayback(RenderFrameHostImpl* source,
5568 int32_t pp_instance) {
5569 pepper_playback_observer_->PepperStartsPlayback(source, pp_instance);
zqzhang181047e62016-07-01 13:37:175570}
5571
nicka0ac8382016-12-15 23:59:235572void WebContentsImpl::OnPepperStopsPlayback(RenderFrameHostImpl* source,
5573 int32_t pp_instance) {
5574 pepper_playback_observer_->PepperStopsPlayback(source, pp_instance);
zqzhang181047e62016-07-01 13:37:175575}
5576
nicka0ac8382016-12-15 23:59:235577void WebContentsImpl::OnPluginCrashed(RenderFrameHostImpl* source,
5578 const base::FilePath& plugin_path,
tommyclie6633ca72014-10-31 00:40:425579 base::ProcessId plugin_pid) {
nicka0ac8382016-12-15 23:59:235580 // TODO(nick): Eliminate the |plugin_pid| parameter, which can't be trusted,
Gyuyoung Kim26c7bc92020-04-29 00:53:005581 // and is only used by WebTestControlHost.
Alexander Timin90c20c32020-08-12 15:28:325582 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5583 observer->PluginCrashed(plugin_path, plugin_pid);
5584 });
tommyclie6633ca72014-10-31 00:40:425585}
5586
[email protected]d8415ad92012-08-23 14:40:505587void WebContentsImpl::OnRequestPpapiBrokerPermission(
nicka0ac8382016-12-15 23:59:235588 RenderViewHostImpl* source,
5589 int ppb_broker_route_id,
[email protected]d8415ad92012-08-23 14:40:505590 const GURL& url,
[email protected]2dec8ec2013-02-07 19:20:345591 const base::FilePath& plugin_path) {
Avi Drissman0a2a967d2019-04-01 19:33:525592 base::OnceCallback<void(bool)> permission_result_callback = base::BindOnce(
nicka0ac8382016-12-15 23:59:235593 &WebContentsImpl::SendPpapiBrokerPermissionResult, base::Unretained(this),
5594 source->GetProcess()->GetID(), ppb_broker_route_id);
[email protected]8c8fc292012-11-23 18:57:165595 if (!delegate_) {
Tommy Nyquist4b749d02018-03-20 21:46:295596 std::move(permission_result_callback).Run(false);
[email protected]8c8fc292012-11-23 18:57:165597 return;
[email protected]d8415ad92012-08-23 14:40:505598 }
5599
Avi Drissman0a2a967d2019-04-01 19:33:525600 delegate_->RequestPpapiBrokerPermission(
5601 this, url, plugin_path, std::move(permission_result_callback));
[email protected]d8415ad92012-08-23 14:40:505602}
5603
nicka0ac8382016-12-15 23:59:235604void WebContentsImpl::SendPpapiBrokerPermissionResult(int process_id,
5605 int ppb_broker_route_id,
5606 bool result) {
5607 RenderProcessHost* rph = RenderProcessHost::FromID(process_id);
5608 if (rph) {
5609 // TODO(nick): Convert this from ViewMsg_ to a Ppapi msg, since it
5610 // is not routed to a RenderView.
5611 rph->Send(
5612 new ViewMsg_PpapiBrokerPermissionResult(ppb_broker_route_id, result));
5613 }
[email protected]d8415ad92012-08-23 14:40:505614}
brettw4b461082016-11-19 18:55:165615#endif // BUILDFLAG(ENABLE_PLUGINS)
[email protected]19be7a62012-10-01 23:03:375616
Miyoung Shin5709ab02020-02-19 06:50:415617void WebContentsImpl::UpdateFaviconURL(
5618 RenderFrameHost* source,
5619 std::vector<blink::mojom::FaviconURLPtr> candidates) {
lukasza178ff092017-06-07 23:39:505620 // Ignore favicons for non-main frame.
5621 if (source->GetParent()) {
5622 NOTREACHED();
5623 return;
5624 }
5625
pkotwiczf9bc20592015-04-21 18:57:065626 // We get updated favicon URLs after the page stops loading. If a cross-site
5627 // navigation occurs while a page is still loading, the initial page
5628 // may stop loading and send us updated favicon URLs after the navigation
5629 // for the new page has committed.
lukasza178ff092017-06-07 23:39:505630 if (!source->IsCurrent())
pkotwiczf9bc20592015-04-21 18:57:065631 return;
5632
Miyoung Shin5709ab02020-02-19 06:50:415633 favicon_urls_ = std::move(candidates);
Mounir Lamouri7b4a1f232019-12-23 16:32:105634
Alexander Timin90c20c32020-08-12 15:28:325635 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5636 observer->DidUpdateFaviconURL(source, favicon_urls_);
5637 });
[email protected]795c28972012-12-06 06:13:395638}
5639
qinmin72e8bd02016-10-21 19:35:375640void WebContentsImpl::SetIsOverlayContent(bool is_overlay_content) {
5641 is_overlay_content_ = is_overlay_content;
5642}
5643
Albert J. Wongfb64e142018-10-16 01:10:455644void WebContentsImpl::DidFirstVisuallyNonEmptyPaint(
5645 RenderViewHostImpl* source) {
nicka0ac8382016-12-15 23:59:235646 // TODO(nick): When this is ported to FrameHostMsg_, we should only listen if
5647 // |source| is the main frame.
Alexander Timin90c20c32020-08-12 15:28:325648 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5649 observer->DidFirstVisuallyNonEmptyPaint();
5650 });
Carlos Caballero1215f882019-10-29 15:58:435651 if (source->theme_color() != last_sent_theme_color_) {
yusufod41c5f92015-03-06 00:14:285652 // Theme color should have updated by now if there was one.
Alexander Timin90c20c32020-08-12 15:28:325653 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5654 observer->DidChangeThemeColor();
5655 });
Carlos Caballero1215f882019-10-29 15:58:435656 last_sent_theme_color_ = source->theme_color();
yusufod41c5f92015-03-06 00:14:285657 }
[email protected]9f268072013-11-07 00:02:155658}
[email protected]d9030b82013-07-19 08:26:065659
Kevin McNee068c3eb2020-04-03 18:24:195660bool WebContentsImpl::IsPortal() {
Adithya Srinivasan46b8a792019-02-01 14:47:235661 return portal();
5662}
5663
Kevin McNee94ea52f52020-06-23 17:42:065664WebContentsImpl* WebContentsImpl::GetPortalHostWebContents() {
5665 return portal() ? portal()->GetPortalHostContents() : nullptr;
5666}
5667
[email protected]17e286e2013-03-01 23:29:395668void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
Alexander Timin90c20c32020-08-12 15:28:325669 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5670 observer->BeforeFormRepostWarningShow();
5671 });
[email protected]17e286e2013-03-01 23:29:395672}
5673
[email protected]ec6c05f2013-10-23 18:41:575674void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
5675 Activate();
5676 if (delegate_)
5677 delegate_->ShowRepostFormWarningDialog(this);
5678}
5679
[email protected]b4c84012014-04-28 19:51:105680bool WebContentsImpl::HasAccessedInitialDocument() {
5681 return has_accessed_initial_document_;
5682}
5683
afakhry6f0c1ec22016-07-14 13:55:135684void WebContentsImpl::UpdateTitleForEntry(NavigationEntry* entry,
[email protected]fcf75d42013-12-03 20:11:265685 const base::string16& title) {
[email protected]fcf75d42013-12-03 20:11:265686 base::string16 final_title;
Avi Drissman93002212017-09-27 03:20:525687 base::TrimWhitespace(title, base::TRIM_ALL, &final_title);
[email protected]420ae012009-04-24 05:16:325688
[email protected]987fc3a2011-05-26 14:18:095689 // If a page is created via window.open and never navigated,
5690 // there will be no navigation entry. In this situation,
[email protected]73eb2602012-02-09 19:50:555691 // |page_title_when_no_navigation_entry_| will be used for page title.
[email protected]987fc3a2011-05-26 14:18:095692 if (entry) {
[email protected]36fc0392011-12-25 03:59:515693 if (final_title == entry->GetTitle())
afakhry6f0c1ec22016-07-14 13:55:135694 return; // Nothing changed, don't bother.
[email protected]420ae012009-04-24 05:16:325695
[email protected]36fc0392011-12-25 03:59:515696 entry->SetTitle(final_title);
Avi Drissman93002212017-09-27 03:20:525697
5698 // The title for display may differ from the title just set; grab it.
5699 final_title = entry->GetTitleForDisplay();
[email protected]987fc3a2011-05-26 14:18:095700 } else {
5701 if (page_title_when_no_navigation_entry_ == final_title)
afakhry6f0c1ec22016-07-14 13:55:135702 return; // Nothing changed, don't bother.
[email protected]987fc3a2011-05-26 14:18:095703
5704 page_title_when_no_navigation_entry_ = final_title;
5705 }
[email protected]420ae012009-04-24 05:16:325706
[email protected]420ae012009-04-24 05:16:325707 // Lastly, set the title for the view.
[email protected]790e2fd2011-09-21 20:28:235708 view_->SetPageTitle(final_title);
[email protected]420ae012009-04-24 05:16:325709
Alexander Timin90c20c32020-08-12 15:28:325710 observers_.ForEachObserver(
5711 [&](WebContentsObserver* observer) { observer->TitleWasSet(entry); });
afakhry6f0c1ec22016-07-14 13:55:135712 // Broadcast notifications when the UI should be updated.
5713 if (entry == controller_.GetEntryAtOffset(0))
5714 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE);
[email protected]420ae012009-04-24 05:16:325715}
5716
fdegansa696e5112015-04-17 01:57:595717void WebContentsImpl::SendChangeLoadProgress() {
[email protected]960b0372014-05-19 18:01:005718 loading_last_progress_update_ = base::TimeTicks::Now();
Alexander Timin90c20c32020-08-12 15:28:325719 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5720 observer->LoadProgressChanged(frame_tree_.load_progress());
5721 });
[email protected]960b0372014-05-19 18:01:005722}
5723
5724void WebContentsImpl::ResetLoadProgressState() {
fdegans1d16355162015-03-26 11:58:345725 frame_tree_.ResetLoadProgress();
[email protected]960b0372014-05-19 18:01:005726 loading_weak_factory_.InvalidateWeakPtrs();
5727 loading_last_progress_update_ = base::TimeTicks();
5728}
5729
clamy44e84ce2016-02-22 15:38:255730// Notifies the RenderWidgetHost instance about the fact that the page is
5731// loading, or done loading.
5732void WebContentsImpl::LoadingStateChanged(bool to_different_document,
clamy44e84ce2016-02-22 15:38:255733 LoadNotificationDetails* details) {
Nate Chapin22ea6592019-03-05 22:29:025734 if (is_being_destroyed_)
5735 return;
clamy44e84ce2016-02-22 15:38:255736
5737 bool is_loading = IsLoading();
5738
5739 if (!is_loading) {
5740 load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
5741 base::string16());
5742 load_state_host_.clear();
5743 upload_size_ = 0;
5744 upload_position_ = 0;
5745 }
5746
5747 GetRenderManager()->SetIsLoading(is_loading);
5748
5749 waiting_for_response_ = is_loading;
5750 is_load_to_different_document_ = to_different_document;
5751
5752 if (delegate_)
5753 delegate_->LoadingStateChanged(this, to_different_document);
5754 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD);
5755
5756 std::string url = (details ? details->url.possibly_invalid_spec() : "NULL");
5757 if (is_loading) {
5758 TRACE_EVENT_ASYNC_BEGIN2("browser,navigation", "WebContentsImpl Loading",
5759 this, "URL", url, "Main FrameTreeNode id",
5760 GetFrameTree()->root()->frame_tree_node_id());
Alexander Timin90c20c32020-08-12 15:28:325761 observers_.ForEachObserver(
5762 [&](WebContentsObserver* observer) { observer->DidStartLoading(); });
clamy44e84ce2016-02-22 15:38:255763 } else {
5764 TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
5765 this, "URL", url);
Alexander Timin90c20c32020-08-12 15:28:325766 observers_.ForEachObserver(
5767 [&](WebContentsObserver* observer) { observer->DidStopLoading(); });
clamy44e84ce2016-02-22 15:38:255768 }
5769
5770 // TODO(avi): Remove. http://crbug.com/170921
5771 int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP;
5772 NotificationDetails det = NotificationService::NoDetails();
5773 if (details)
5774 det = Details<LoadNotificationDetails>(details);
5775 NotificationService::current()->Notify(
5776 type, Source<NavigationController>(&controller_), det);
5777}
5778
danakja0bce4c952020-05-12 20:40:285779void WebContentsImpl::NotifyViewSwapped(RenderViewHost* old_view,
5780 RenderViewHost* new_view) {
5781 DCHECK_NE(old_view, new_view);
[email protected]420ae012009-04-24 05:16:325782 // After sending out a swap notification, we need to send a disconnect
5783 // notification so that clients that pick up a pointer to |this| can NULL the
5784 // pointer. See Bug 1230284.
5785 notify_disconnection_ = true;
Alexander Timin90c20c32020-08-12 15:28:325786 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5787 observer->RenderViewHostChanged(old_view, new_view);
5788 });
danakja0bce4c952020-05-12 20:40:285789 view_->RenderViewHostChanged(old_view, new_view);
Jinsuk Kimdc5284c22018-07-11 02:22:065790
Lucas Furukawa Gadanif9ea4fc2018-08-03 23:57:135791 // If this is an inner WebContents that has swapped views, we need to reattach
5792 // it to its outer WebContents.
5793 if (node_.outer_web_contents())
5794 ReattachToOuterWebContentsFrame();
5795
[email protected]7a846df2012-09-20 19:17:395796 // Ensure that the associated embedder gets cleared after a RenderViewHost
5797 // gets swapped, so we don't reuse the same embedder next time a
5798 // RenderViewHost is attached to this WebContents.
5799 RemoveBrowserPluginEmbedder();
[email protected]420ae012009-04-24 05:16:325800}
5801
danakja0bce4c952020-05-12 20:40:285802void WebContentsImpl::NotifyFrameSwapped(RenderFrameHost* old_frame,
5803 RenderFrameHost* new_frame,
Jinsuk Kim895b2c52018-07-03 06:49:165804 bool is_main_frame) {
Bo Liu168c8642017-08-28 18:26:025805#if defined(OS_ANDROID)
danakja0bce4c952020-05-12 20:40:285806 // Copy importance from |old_frame| if |new_frame| is a main frame.
5807 if (old_frame && !new_frame->GetParent()) {
5808 RenderWidgetHostImpl* old_widget =
5809 static_cast<RenderFrameHostImpl*>(old_frame)->GetRenderWidgetHost();
5810 RenderWidgetHostImpl* new_widget =
5811 static_cast<RenderFrameHostImpl*>(new_frame)->GetRenderWidgetHost();
5812 new_widget->SetImportance(old_widget->importance());
Bo Liu7c6779e92017-08-16 02:02:285813 }
Bo Liu168c8642017-08-28 18:26:025814#endif
Alexander Timin90c20c32020-08-12 15:28:325815 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5816 observer->RenderFrameHostChanged(old_frame, new_frame);
5817 });
[email protected]02d7b6e2014-06-24 21:01:505818}
5819
[email protected]da7a7182013-09-06 08:11:115820// TODO(avi): Remove this entire function because this notification is already
5821// covered by two observer functions. http://crbug.com/170921
[email protected]b172aee2012-04-10 17:05:265822void WebContentsImpl::NotifyDisconnected() {
[email protected]420ae012009-04-24 05:16:325823 if (!notify_disconnection_)
5824 return;
5825
5826 notify_disconnection_ = false;
[email protected]8ff00d72012-10-23 19:12:215827 NotificationService::current()->Notify(
5828 NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
5829 Source<WebContents>(this),
5830 NotificationService::NoDetails());
[email protected]420ae012009-04-24 05:16:325831}
5832
[email protected]cbb1ef592013-06-05 19:49:465833void WebContentsImpl::NotifyNavigationEntryCommitted(
5834 const LoadCommittedDetails& load_details) {
Alexander Timin90c20c32020-08-12 15:28:325835 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5836 observer->NavigationEntryCommitted(load_details);
5837 });
[email protected]cbb1ef592013-06-05 19:49:465838}
5839
Sam McNally5c087a32017-08-25 01:46:145840void WebContentsImpl::NotifyNavigationEntryChanged(
5841 const EntryChangedDetails& change_details) {
Alexander Timin90c20c32020-08-12 15:28:325842 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5843 observer->NavigationEntryChanged(change_details);
5844 });
Sam McNally5c087a32017-08-25 01:46:145845}
5846
5847void WebContentsImpl::NotifyNavigationListPruned(
5848 const PrunedDetails& pruned_details) {
Alexander Timin90c20c32020-08-12 15:28:325849 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5850 observer->NavigationListPruned(pruned_details);
5851 });
Sam McNally5c087a32017-08-25 01:46:145852}
5853
Christian Dullweber1af31e62018-02-22 11:49:485854void WebContentsImpl::NotifyNavigationEntriesDeleted() {
Alexander Timin90c20c32020-08-12 15:28:325855 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5856 observer->NavigationEntriesDeleted();
5857 });
Christian Dullweber1af31e62018-02-22 11:49:485858}
5859
rockotf62002a2016-09-15 00:08:595860void WebContentsImpl::OnAssociatedInterfaceRequest(
5861 RenderFrameHost* render_frame_host,
5862 const std::string& interface_name,
5863 mojo::ScopedInterfaceEndpointHandle handle) {
Julie Jeongeun Kim7d0986172019-12-04 03:17:255864 auto it = receiver_sets_.find(interface_name);
5865 if (it != receiver_sets_.end())
5866 it->second->OnReceiverForFrame(render_frame_host, std::move(handle));
rockotf62002a2016-09-15 00:08:595867}
5868
Ben Goodger9e24929e2017-07-21 03:13:405869void WebContentsImpl::OnInterfaceRequest(
5870 RenderFrameHost* render_frame_host,
5871 const std::string& interface_name,
5872 mojo::ScopedMessagePipeHandle* interface_pipe) {
Alexander Timin90c20c32020-08-12 15:28:325873 for (auto& observer : observers_.observer_list()) {
Ben Goodger9e24929e2017-07-21 03:13:405874 observer.OnInterfaceRequestFromFrame(render_frame_host, interface_name,
5875 interface_pipe);
5876 if (!interface_pipe->is_valid())
5877 break;
5878 }
5879}
5880
Varun Khaneja5da94302019-06-25 04:48:105881void WebContentsImpl::OnDidBlockNavigation(
5882 const GURL& blocked_url,
5883 const GURL& initiator_url,
Abhijeet Kandalkarde7348e2020-01-13 06:06:545884 blink::mojom::NavigationBlockedReason reason) {
Nicolas Dossou-gbetebcab2472017-09-09 12:28:405885 if (delegate_)
Varun Khaneja5da94302019-06-25 04:48:105886 delegate_->OnDidBlockNavigation(this, blocked_url, initiator_url, reason);
Nicolas Dossou-gbetebcab2472017-09-09 12:28:405887}
5888
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:415889const GURL& WebContentsImpl::GetMainFrameLastCommittedURL() {
[email protected]c31a84802014-04-03 15:55:495890 return GetLastCommittedURL();
5891}
5892
[email protected]b849847b2013-12-10 21:57:585893void WebContentsImpl::RenderFrameCreated(RenderFrameHost* render_frame_host) {
Alexander Timin90c20c32020-08-12 15:28:325894 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5895 observer->RenderFrameCreated(render_frame_host);
5896 });
dmazzonif8a31042016-12-03 00:52:135897 UpdateAccessibilityModeOnFrame(render_frame_host);
clamy91b7abf2016-03-24 15:17:455898
Becca Hughesd11d6502018-07-31 17:01:285899 if (display_cutout_host_impl_)
5900 display_cutout_host_impl_->RenderFrameCreated(render_frame_host);
5901
clamy91b7abf2016-03-24 15:17:455902 if (!render_frame_host->IsRenderFrameLive() || render_frame_host->GetParent())
5903 return;
5904
5905 NavigationEntry* entry = controller_.GetPendingEntry();
5906 if (entry && entry->IsViewSourceMode()) {
5907 // Put the renderer in view source mode.
Dave Tapuska3c05e1c2019-11-27 18:34:185908 static_cast<RenderFrameHostImpl*>(render_frame_host)
5909 ->GetAssociatedLocalFrame()
5910 ->EnableViewSourceMode();
clamy91b7abf2016-03-24 15:17:455911 }
[email protected]b849847b2013-12-10 21:57:585912}
5913
5914void WebContentsImpl::RenderFrameDeleted(RenderFrameHost* render_frame_host) {
yilkal172da772019-11-06 22:49:075915 if (IsBeingDestroyed() && !render_frame_host->GetParent() &&
5916 first_navigation_completed_ &&
Hajime Hoshibbc509c2020-04-06 08:55:085917 !render_frame_host->IsInBackForwardCache()) {
yilkal796e89e2019-10-02 23:58:285918 // Main frame has been deleted because WebContents is being destroyed.
Rakina Zata Amni74627df2019-10-15 02:03:175919 // Note that we aren't recording this here when the main frame is in the
5920 // back-forward cache because that means we've actually already navigated
5921 // away from it (and we got to this point because the WebContents is
yilkal172da772019-11-06 22:49:075922 // deleted), which means |max_loaded_frame_count_| is already overwritten.
5923 // The |max_loaded_frame_count_| value will instead be recorded from within
5924 // |WebContentsImpl::DidFinishNavigation()|.
5925 RecordMaxFrameCountUMA(max_loaded_frame_count_);
yilkal796e89e2019-10-02 23:58:285926 }
5927
Alexander Timin90c20c32020-08-12 15:28:325928 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5929 observer->RenderFrameDeleted(render_frame_host);
5930 });
zqzhang7b6f4f02016-12-07 22:10:225931#if BUILDFLAG(ENABLE_PLUGINS)
5932 pepper_playback_observer_->RenderFrameDeleted(render_frame_host);
5933#endif
Becca Hughesfd5d8f892018-06-14 18:23:365934
Becca Hughesd11d6502018-07-31 17:01:285935 if (display_cutout_host_impl_)
5936 display_cutout_host_impl_->RenderFrameDeleted(render_frame_host);
5937
Becca Hughesfd5d8f892018-06-14 18:23:365938 // Remove any fullscreen state that the frame has stored.
5939 FullscreenStateChanged(render_frame_host, false /* is_fullscreen */);
[email protected]b849847b2013-12-10 21:57:585940}
5941
[email protected]a09d53ce2014-01-31 00:46:425942void WebContentsImpl::ShowContextMenu(RenderFrameHost* render_frame_host,
5943 const ContextMenuParams& params) {
avie9fd8722017-04-10 16:17:585944 // If a renderer fires off a second command to show a context menu before the
5945 // first context menu is closed, just ignore it. https://crbug.com/707534
ekaramadf6750aa2017-06-06 18:29:425946 if (showing_context_menu_)
avie9fd8722017-04-10 16:17:585947 return;
5948
[email protected]077e704b2014-05-23 19:24:105949 ContextMenuParams context_menu_params(params);
[email protected]a09d53ce2014-01-31 00:46:425950 // Allow WebContentsDelegates to handle the context menu operation first.
Joel Klinghed0ea22ea2019-02-20 22:04:225951 if (delegate_ &&
5952 delegate_->HandleContextMenu(render_frame_host, context_menu_params))
[email protected]a09d53ce2014-01-31 00:46:425953 return;
5954
[email protected]077e704b2014-05-23 19:24:105955 render_view_host_delegate_view_->ShowContextMenu(render_frame_host,
5956 context_menu_params);
[email protected]a09d53ce2014-01-31 00:46:425957}
5958
Avi Drissman4891b852018-09-25 18:12:585959namespace {
5960// Normalizes the line endings: \r\n -> \n, lone \r -> \n.
5961base::string16 NormalizeLineBreaks(const base::string16& source) {
5962 static const base::NoDestructor<base::string16> kReturnNewline(
5963 base::ASCIIToUTF16("\r\n"));
5964 static const base::NoDestructor<base::string16> kReturn(
5965 base::ASCIIToUTF16("\r"));
5966 static const base::NoDestructor<base::string16> kNewline(
5967 base::ASCIIToUTF16("\n"));
5968
5969 std::vector<base::StringPiece16> pieces;
5970
5971 for (const auto& rn_line : base::SplitStringPieceUsingSubstr(
5972 source, *kReturnNewline, base::KEEP_WHITESPACE,
5973 base::SPLIT_WANT_ALL)) {
5974 auto r_lines = base::SplitStringPieceUsingSubstr(
5975 rn_line, *kReturn, base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
5976 std::move(std::begin(r_lines), std::end(r_lines),
5977 std::back_inserter(pieces));
5978 }
5979
5980 return base::JoinString(pieces, *kNewline);
5981}
5982} // namespace
5983
Dave Tapuskacdf545cc2020-01-23 18:38:525984void WebContentsImpl::RunJavaScriptDialog(
5985 RenderFrameHost* render_frame_host,
5986 const base::string16& message,
5987 const base::string16& default_prompt,
5988 JavaScriptDialogType dialog_type,
5989 JavaScriptDialogCallback response_callback) {
Avi Drissman2ccbb402018-03-20 21:11:365990 // Ensure that if showing a dialog is the first thing that a page does, that
5991 // the contents of the previous page aren't shown behind it. This is required
5992 // because showing a dialog freezes the renderer, so no frames will be coming
5993 // from it. https://crbug.com/823353
5994 auto* render_widget_host_impl =
5995 static_cast<RenderFrameHostImpl*>(render_frame_host)
5996 ->GetRenderWidgetHost();
5997 if (render_widget_host_impl)
5998 render_widget_host_impl->ForceFirstFrameAfterNavigationTimeout();
5999
avi0720b02e2017-06-13 03:22:136000 // Running a dialog causes an exit to webpage-initiated fullscreen.
6001 // http://crbug.com/728276
Avi Drissman1a55a9d62020-03-10 18:56:456002 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
avi0720b02e2017-06-13 03:22:136003
Avi Drissman1a55a9d62020-03-10 18:56:456004 auto callback =
6005 base::BindOnce(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
6006 render_frame_host->GetProcess()->GetID(),
6007 render_frame_host->GetRoutingID(),
6008 std::move(response_callback), std::move(fullscreen_block));
Pavel Feldman3c1842b2017-08-02 05:00:166009
Pavel Feldman3c1842b2017-08-02 05:00:166010 std::vector<protocol::PageHandler*> page_handlers =
6011 protocol::PageHandler::EnabledForWebContents(this);
6012
Pavel Feldmanfab3cb62017-10-05 01:02:016013 if (delegate_)
6014 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
6015
Charlie Reis96077362019-07-04 00:34:046016 // While a JS message dialog is showing, defer commits in this WebContents.
6017 javascript_dialog_navigation_deferrer_ =
6018 std::make_unique<JavaScriptDialogNavigationDeferrer>();
6019
Carlos IL07f282f2020-05-15 22:58:296020 // Suppress JavaScript dialogs when requested.
6021 bool should_suppress = delegate_ && delegate_->ShouldSuppressDialogs(this);
Pavel Feldman1c587bc52018-04-04 21:16:056022 bool has_non_devtools_handlers = delegate_ && dialog_manager_;
6023 bool has_handlers = page_handlers.size() || has_non_devtools_handlers;
Pavel Feldmanfab3cb62017-10-05 01:02:016024 bool suppress_this_message = should_suppress || !has_handlers;
6025
6026 if (suppress_this_message) {
Avi Drissmane04d3992017-10-05 15:11:366027 std::move(callback).Run(true, false, base::string16());
Pavel Feldman3c1842b2017-08-02 05:00:166028 return;
6029 }
6030
6031 scoped_refptr<CloseDialogCallbackWrapper> wrapper =
Avi Drissmane04d3992017-10-05 15:11:366032 new CloseDialogCallbackWrapper(std::move(callback));
Pavel Feldman3c1842b2017-08-02 05:00:166033
6034 is_showing_javascript_dialog_ = true;
6035
Avi Drissman4891b852018-09-25 18:12:586036 base::string16 normalized_message = NormalizeLineBreaks(message);
6037
Pavel Feldman3c1842b2017-08-02 05:00:166038 for (auto* handler : page_handlers) {
Avi Drissmane04d3992017-10-05 15:11:366039 handler->DidRunJavaScriptDialog(
Avi Drissman4891b852018-09-25 18:12:586040 render_frame_host->GetLastCommittedURL(), normalized_message,
6041 default_prompt, dialog_type, has_non_devtools_handlers,
Avi Drissmane04d3992017-10-05 15:11:366042 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
Pavel Feldman3c1842b2017-08-02 05:00:166043 }
6044
6045 if (dialog_manager_) {
[email protected]87de04b02014-04-08 22:14:496046 dialog_manager_->RunJavaScriptDialog(
Avi Drissman4891b852018-09-25 18:12:586047 this, render_frame_host, dialog_type, normalized_message,
6048 default_prompt,
Avi Drissmane04d3992017-10-05 15:11:366049 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false),
6050 &suppress_this_message);
[email protected]87de04b02014-04-08 22:14:496051 }
6052
6053 if (suppress_this_message) {
6054 // If we are suppressing messages, just reply as if the user immediately
6055 // pressed "Cancel", passing true to |dialog_was_suppressed|.
Avi Drissmane04d3992017-10-05 15:11:366056 wrapper->Run(true, false, base::string16());
[email protected]87de04b02014-04-08 22:14:496057 }
[email protected]87de04b02014-04-08 22:14:496058}
6059
6060void WebContentsImpl::RunBeforeUnloadConfirm(
[email protected]39f2f9252014-05-03 00:54:016061 RenderFrameHost* render_frame_host,
[email protected]87de04b02014-04-08 22:14:496062 bool is_reload,
Dave Tapuskacdf545cc2020-01-23 18:38:526063 JavaScriptDialogCallback response_callback) {
Avi Drissman2ccbb402018-03-20 21:11:366064 // Ensure that if showing a dialog is the first thing that a page does, that
6065 // the contents of the previous page aren't shown behind it. This is required
6066 // because showing a dialog freezes the renderer, so no frames will be coming
6067 // from it. https://crbug.com/823353
6068 auto* render_widget_host_impl =
6069 static_cast<RenderFrameHostImpl*>(render_frame_host)
6070 ->GetRenderWidgetHost();
6071 if (render_widget_host_impl)
6072 render_widget_host_impl->ForceFirstFrameAfterNavigationTimeout();
6073
avi0720b02e2017-06-13 03:22:136074 // Running a dialog causes an exit to webpage-initiated fullscreen.
6075 // http://crbug.com/728276
Avi Drissman1a55a9d62020-03-10 18:56:456076 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
avi0720b02e2017-06-13 03:22:136077
[email protected]39f2f9252014-05-03 00:54:016078 RenderFrameHostImpl* rfhi =
6079 static_cast<RenderFrameHostImpl*>(render_frame_host);
[email protected]87de04b02014-04-08 22:14:496080 if (delegate_)
6081 delegate_->WillRunBeforeUnloadConfirm();
6082
Avi Drissman1a55a9d62020-03-10 18:56:456083 auto callback =
6084 base::BindOnce(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
6085 render_frame_host->GetProcess()->GetID(),
6086 render_frame_host->GetRoutingID(),
6087 std::move(response_callback), std::move(fullscreen_block));
Pavel Feldman3c1842b2017-08-02 05:00:166088
Pavel Feldman3c1842b2017-08-02 05:00:166089 std::vector<protocol::PageHandler*> page_handlers =
6090 protocol::PageHandler::EnabledForWebContents(this);
6091
Pavel Feldmanfab3cb62017-10-05 01:02:016092 if (delegate_)
6093 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
6094
Charlie Reis96077362019-07-04 00:34:046095 // While a JS beforeunload dialog is showing, defer commits in this
6096 // WebContents.
6097 javascript_dialog_navigation_deferrer_ =
6098 std::make_unique<JavaScriptDialogNavigationDeferrer>();
6099
Sreeja Kamishettyf352e302020-06-10 13:21:246100 bool should_suppress = !rfhi->IsCurrent() ||
Tarun Bansalc209b742019-12-24 06:53:256101 (delegate_ && delegate_->ShouldSuppressDialogs(this));
Pavel Feldman1c587bc52018-04-04 21:16:056102 bool has_non_devtools_handlers = delegate_ && dialog_manager_;
6103 bool has_handlers = page_handlers.size() || has_non_devtools_handlers;
Pavel Feldmanfab3cb62017-10-05 01:02:016104 if (should_suppress || !has_handlers) {
Avi Drissmane04d3992017-10-05 15:11:366105 std::move(callback).Run(false, true, base::string16());
[email protected]87de04b02014-04-08 22:14:496106 return;
6107 }
6108
6109 is_showing_before_unload_dialog_ = true;
Pavel Feldman3c1842b2017-08-02 05:00:166110
6111 scoped_refptr<CloseDialogCallbackWrapper> wrapper =
Avi Drissmane04d3992017-10-05 15:11:366112 new CloseDialogCallbackWrapper(std::move(callback));
Pavel Feldman3c1842b2017-08-02 05:00:166113
6114 GURL frame_url = rfhi->GetLastCommittedURL();
6115 for (auto* handler : page_handlers) {
Avi Drissmane04d3992017-10-05 15:11:366116 handler->DidRunBeforeUnloadConfirm(
Pavel Feldman1c587bc52018-04-04 21:16:056117 frame_url, has_non_devtools_handlers,
Avi Drissmane04d3992017-10-05 15:11:366118 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
Pavel Feldman3c1842b2017-08-02 05:00:166119 }
6120
6121 if (dialog_manager_) {
Avi Drissmane04d3992017-10-05 15:11:366122 dialog_manager_->RunBeforeUnloadDialog(
Avi Drissmanff9ed752017-11-28 21:18:126123 this, render_frame_host, is_reload,
Avi Drissmane04d3992017-10-05 15:11:366124 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
Pavel Feldman3c1842b2017-08-02 05:00:166125 }
[email protected]87de04b02014-04-08 22:14:496126}
6127
Kent Tamurac260c9a2018-09-14 09:10:566128void WebContentsImpl::RunFileChooser(
6129 RenderFrameHost* render_frame_host,
Kent Tamura3abb32d2020-07-02 00:23:016130 scoped_refptr<FileChooserImpl::FileSelectListenerImpl> listener,
Kent Tamurac260c9a2018-09-14 09:10:566131 const blink::mojom::FileChooserParams& params) {
Avi Drissman3d41e7712018-08-27 21:18:086132 // Any explicit focusing of another window while this WebContents is in
6133 // fullscreen can be used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:456134 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
6135 listener->SetFullscreenBlock(std::move(fullscreen_block));
Avi Drissman3d41e7712018-08-27 21:18:086136
naskoada75b22016-06-11 16:09:466137 if (delegate_)
Kent Tamura512a27e2018-10-04 00:49:326138 delegate_->RunFileChooser(render_frame_host, std::move(listener), params);
6139 else
6140 listener->FileSelectionCanceled();
naskoada75b22016-06-11 16:09:466141}
6142
[email protected]a86c0e962013-12-17 17:10:396143WebContents* WebContentsImpl::GetAsWebContents() {
6144 return this;
6145}
6146
mcnee336ea2c2017-05-23 22:50:596147#if !defined(OS_ANDROID)
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416148double WebContentsImpl::GetPendingPageZoomLevel() {
wjmaclean64951902016-04-29 20:59:126149 NavigationEntry* pending_entry = GetController().GetPendingEntry();
6150 if (!pending_entry)
6151 return HostZoomMap::GetZoomLevel(this);
6152
6153 GURL url = pending_entry->GetURL();
6154 return HostZoomMap::GetForWebContents(this)->GetZoomLevelForHostAndScheme(
6155 url.scheme(), net::GetHostOrSpecFromURL(url));
6156}
mcnee336ea2c2017-05-23 22:50:596157#endif // !defined(OS_ANDROID)
wjmaclean64951902016-04-29 20:59:126158
qinmin72e8bd02016-10-21 19:35:376159bool WebContentsImpl::HideDownloadUI() const {
6160 return is_overlay_content_;
6161}
6162
mlamouri5cd9ae82017-02-18 11:05:096163bool WebContentsImpl::HasPersistentVideo() const {
6164 return has_persistent_video_;
6165}
6166
Ian Vollick5d5c37f2019-06-19 22:50:576167bool WebContentsImpl::IsSpatialNavigationDisabled() const {
6168 return is_spatial_navigation_disabled_;
6169}
6170
Albert J. Wong65fe64d2019-09-20 02:48:146171RenderFrameHostImpl* WebContentsImpl::GetPendingMainFrame() {
clamy610c63b32017-12-22 15:05:186172 return GetRenderManager()->speculative_frame_host();
Alex Moshchuk27caae82017-09-11 23:11:186173}
6174
mlamourie52c1b542017-02-23 14:57:506175bool WebContentsImpl::HasActiveEffectivelyFullscreenVideo() const {
6176 return media_web_contents_observer_->HasActiveEffectivelyFullscreenVideo();
6177}
6178
François Beaufortad6c5232018-02-26 11:00:446179bool WebContentsImpl::IsPictureInPictureAllowedForFullscreenVideo() const {
6180 return media_web_contents_observer_
6181 ->IsPictureInPictureAllowedForFullscreenVideo();
6182}
6183
ekaramada110f642016-12-21 19:47:286184bool WebContentsImpl::IsFocusedElementEditable() {
6185 RenderFrameHostImpl* frame = GetFocusedFrame();
6186 return frame && frame->has_focused_editable_element();
6187}
6188
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416189bool WebContentsImpl::IsShowingContextMenu() {
ekaramadf6750aa2017-06-06 18:29:426190 return showing_context_menu_;
6191}
6192
6193void WebContentsImpl::SetShowingContextMenu(bool showing) {
6194 DCHECK_NE(showing_context_menu_, showing);
6195 showing_context_menu_ = showing;
6196
6197 if (auto* view = GetRenderWidgetHostView()) {
6198 // Notify the main frame's RWHV to run the platform-specific code, if any.
6199 static_cast<RenderWidgetHostViewBase*>(view)->SetShowingContextMenu(
6200 showing);
6201 }
6202}
6203
ekaramada110f642016-12-21 19:47:286204void WebContentsImpl::ClearFocusedElement() {
6205 if (auto* frame = GetFocusedFrame())
6206 frame->ClearFocusedElement();
6207}
6208
danakj77eb7e82020-01-09 19:38:466209bool WebContentsImpl::IsNeverComposited() {
[email protected]7912e822014-04-16 02:37:036210 if (!delegate_)
6211 return false;
danakj77eb7e82020-01-09 19:38:466212 return delegate_->IsNeverComposited(this);
[email protected]7912e822014-04-16 02:37:036213}
6214
[email protected]5a3bdf52012-05-24 15:12:576215RenderViewHostDelegateView* WebContentsImpl::GetDelegateView() {
6216 return render_view_host_delegate_view_;
[email protected]420ae012009-04-24 05:16:326217}
6218
Peter Marshall2dc74e92020-07-29 20:02:306219blink::mojom::RendererPreferences WebContentsImpl::GetRendererPrefs() const {
[email protected]840b1512009-07-21 16:53:466220 return renderer_preferences_;
[email protected]80d96fa2009-06-10 22:34:516221}
6222
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166223RenderFrameHostImpl* WebContentsImpl::GetOuterWebContentsFrame() {
6224 if (GetOuterDelegateFrameTreeNodeId() ==
6225 FrameTreeNode::kFrameTreeNodeInvalidId) {
6226 return nullptr;
6227 }
6228
6229 FrameTreeNode* outer_node =
6230 FrameTreeNode::GloballyFindByID(GetOuterDelegateFrameTreeNodeId());
6231 // The outer node should be in the outer WebContents.
6232 DCHECK_EQ(outer_node->frame_tree(), GetOuterWebContents()->GetFrameTree());
Alexander Timin381e7e182020-04-28 19:04:036233 return outer_node->parent();
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166234}
6235
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416236WebContentsImpl* WebContentsImpl::GetOuterWebContents() {
Lucas Furukawa Gadani105de1e812018-05-31 19:38:396237 return node_.outer_web_contents();
avallee0206f782016-07-28 18:55:336238}
6239
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166240std::vector<WebContents*> WebContentsImpl::GetInnerWebContents() {
6241 std::vector<WebContents*> all_inner_contents;
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166242 const auto& inner_contents = node_.GetInnerWebContents();
6243 all_inner_contents.insert(all_inner_contents.end(), inner_contents.begin(),
6244 inner_contents.end());
6245 return all_inner_contents;
6246}
6247
Jeremy Roman7e70bf92020-01-07 23:23:586248WebContentsImpl* WebContentsImpl::GetResponsibleWebContents() {
6249 // Iteratively ask delegates which other contents is responsible until a fixed
6250 // point is found.
6251 WebContentsImpl* contents = this;
6252 while (WebContentsDelegate* delegate = contents->GetDelegate()) {
6253 auto* responsible_contents = static_cast<WebContentsImpl*>(
6254 delegate->GetResponsibleWebContents(contents));
6255 if (responsible_contents == contents)
6256 break;
6257 contents = responsible_contents;
6258 }
6259 return contents;
6260}
6261
avallee0206f782016-07-28 18:55:336262WebContentsImpl* WebContentsImpl::GetFocusedWebContents() {
lfg601233692017-03-06 22:45:446263 return GetOutermostWebContents()->node_.focused_web_contents();
avallee0206f782016-07-28 18:55:336264}
6265
avallee9993fca2016-11-17 06:16:506266bool WebContentsImpl::ContainsOrIsFocusedWebContents() {
6267 for (WebContentsImpl* focused_contents = GetFocusedWebContents();
6268 focused_contents;
6269 focused_contents = focused_contents->GetOuterWebContents()) {
6270 if (focused_contents == this)
6271 return true;
6272 }
6273
6274 return false;
6275}
6276
W. James MacLean9437b5bf2019-12-06 17:33:446277void WebContentsImpl::RemoveBrowserPluginEmbedder() {
6278 browser_plugin_embedder_.reset();
6279}
6280
avallee0206f782016-07-28 18:55:336281WebContentsImpl* WebContentsImpl::GetOutermostWebContents() {
6282 WebContentsImpl* root = this;
6283 while (root->GetOuterWebContents())
6284 root = root->GetOuterWebContents();
6285 return root;
6286}
6287
avalleed68cdd12017-06-21 22:07:276288void WebContentsImpl::FocusOuterAttachmentFrameChain() {
6289 WebContentsImpl* outer_contents = GetOuterWebContents();
6290 if (!outer_contents)
6291 return;
6292
6293 FrameTreeNode* outer_node =
6294 FrameTreeNode::GloballyFindByID(GetOuterDelegateFrameTreeNodeId());
6295 outer_contents->frame_tree_.SetFocusedFrame(outer_node, nullptr);
6296
6297 // For a browser initiated focus change, let embedding renderer know of the
6298 // change. Otherwise, if the currently focused element is just across a
6299 // process boundary in focus order, it will not be possible to move across
6300 // that boundary. This is because the target element will already be focused
6301 // (that renderer was not notified) and drop the event.
6302 if (GetRenderManager()->GetProxyToOuterDelegate())
6303 GetRenderManager()->GetProxyToOuterDelegate()->SetFocusedFrame();
6304
6305 outer_contents->FocusOuterAttachmentFrameChain();
6306}
6307
Sean Toppingbbc4a2bd2019-01-30 02:16:146308void WebContentsImpl::InnerWebContentsCreated(WebContents* inner_web_contents) {
Alexander Timin90c20c32020-08-12 15:28:326309 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6310 observer->InnerWebContentsCreated(inner_web_contents);
6311 });
Sean Toppingbbc4a2bd2019-01-30 02:16:146312}
6313
Jeremy Roman03ce13ce2020-05-29 22:16:576314void WebContentsImpl::InnerWebContentsAttached(
6315 WebContents* inner_web_contents) {
6316 if (inner_web_contents->IsCurrentlyAudible())
6317 OnAudioStateChanged();
6318}
6319
6320void WebContentsImpl::InnerWebContentsDetached(
6321 WebContents* inner_web_contents) {
6322 if (!is_being_destroyed_)
6323 OnAudioStateChanged();
6324}
6325
[email protected]b172aee2012-04-10 17:05:266326void WebContentsImpl::RenderViewCreated(RenderViewHost* render_view_host) {
[email protected]86f98a22013-03-20 14:35:006327 if (delegate_)
[email protected]e85165c642014-06-10 14:34:316328 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
[email protected]a6b73c62013-02-11 23:05:086329
[email protected]8ff00d72012-10-23 19:12:216330 NotificationService::current()->Notify(
6331 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
6332 Source<WebContents>(this),
6333 Details<RenderViewHost>(render_view_host));
[email protected]420ae012009-04-24 05:16:326334
Alexander Timin90c20c32020-08-12 15:28:326335 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6336 observer->RenderViewCreated(render_view_host);
6337 });
Joel Einbinder848001c2017-09-19 21:39:316338 if (delegate_)
6339 RenderFrameDevToolsAgentHost::WebContentsCreated(this);
[email protected]420ae012009-04-24 05:16:326340}
6341
[email protected]b172aee2012-04-10 17:05:266342void WebContentsImpl::RenderViewReady(RenderViewHost* rvh) {
[email protected]151a63d2011-12-20 22:32:526343 if (rvh != GetRenderViewHost()) {
[email protected]420ae012009-04-24 05:16:326344 // Don't notify the world, since this came from a renderer in the
6345 // background.
6346 return;
6347 }
6348
dmazzoni62111452017-04-28 23:46:556349 RenderWidgetHostViewBase* rwhv =
6350 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
6351 if (rwhv)
6352 rwhv->SetMainFrameAXTreeID(GetMainFrame()->GetAXTreeID());
6353
[email protected]da7a7182013-09-06 08:11:116354 notify_disconnection_ = true;
[email protected]da7a7182013-09-06 08:11:116355
[email protected]be1f56ab2011-12-22 06:55:316356 bool was_crashed = IsCrashed();
[email protected]443b80e2010-12-14 00:42:236357 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING, 0);
[email protected]9d8a4642009-07-29 17:25:306358
6359 // Restore the focus to the tab (otherwise the focus will be on the top
6360 // window).
[email protected]484ae5912010-09-29 19:16:146361 if (was_crashed && !FocusLocationBarByDefault() &&
6362 (!delegate_ || delegate_->ShouldFocusPageAfterCrash())) {
[email protected]f3615f02013-02-26 06:09:066363 view_->Focus();
[email protected]484ae5912010-09-29 19:16:146364 }
[email protected]32ded2212011-11-10 18:51:436365
Alexander Timin90c20c32020-08-12 15:28:326366 observers_.ForEachObserver(
6367 [&](WebContentsObserver* observer) { observer->RenderViewReady(); });
Jinsuk Kim895b2c52018-07-03 06:49:166368 view_->RenderViewReady();
[email protected]420ae012009-04-24 05:16:326369}
6370
[email protected]ec6a7eb2013-04-22 17:34:226371void WebContentsImpl::RenderViewTerminated(RenderViewHost* rvh,
6372 base::TerminationStatus status,
6373 int error_code) {
[email protected]151a63d2011-12-20 22:32:526374 if (rvh != GetRenderViewHost()) {
[email protected]420ae012009-04-24 05:16:326375 // The pending page's RenderViewHost is gone.
6376 return;
6377 }
6378
[email protected]2fcdcc32014-03-05 02:14:076379 // Ensure fullscreen mode is exited in the |delegate_| since a crashed
6380 // renderer may not have made a clean exit.
Avi Drissman97aef042020-06-30 21:04:486381 if (IsFullscreen())
bokanece34a82016-01-28 19:49:466382 ExitFullscreenMode(false);
[email protected]2fcdcc32014-03-05 02:14:076383
Jennifer Apacibleb4b972a2018-06-07 04:41:026384 // Ensure any video in Picture-in-Picture is exited in the |delegate_| since
6385 // a crashed renderer may not have made a clean exit.
6386 if (HasPictureInPictureVideo())
6387 ExitPictureInPicture();
6388
[email protected]698191dc2014-02-25 01:06:136389 // Cancel any visible dialogs so they are not left dangling over the sad tab.
creis89a0f782015-05-27 16:13:176390 CancelActiveAndPendingDialogs();
[email protected]698191dc2014-02-25 01:06:136391
dalecurtis3d1e1302017-02-20 22:33:256392 audio_stream_monitor_.RenderProcessGone(rvh->GetProcess()->GetID());
6393
[email protected]960b0372014-05-19 18:01:006394 // Reset the loading progress. TODO(avi): What does it mean to have a
6395 // "renderer crash" when there is more than one renderer process serving a
6396 // webpage? Once this function is called at a more granular frame level, we
6397 // probably will need to more granularly reset the state here.
6398 ResetLoadProgressState();
clamy44e84ce2016-02-22 15:38:256399 NotifyDisconnected();
6400 SetIsCrashed(status, error_code);
[email protected]960b0372014-05-19 18:01:006401
Alexander Timin90c20c32020-08-12 15:28:326402 TRACE_EVENT0("content", "Dispatching WebContentsObserver::RenderProcessGone");
6403 // Some observers might destroy WebContents in RenderViewTerminated.
6404 base::WeakPtr<WebContentsImpl> weak_ptr = weak_factory_.GetWeakPtr();
6405 auto crashed_status = GetCrashedStatus();
6406 for (auto& observer : observers_.observer_list()) {
6407 observer.RenderProcessGone(crashed_status);
6408 if (!weak_ptr)
6409 return;
6410 }
6411
6412 // |this| might have been deleted. Do not add code here.
[email protected]420ae012009-04-24 05:16:326413}
6414
[email protected]b172aee2012-04-10 17:05:266415void WebContentsImpl::RenderViewDeleted(RenderViewHost* rvh) {
Alexander Timin90c20c32020-08-12 15:28:326416 observers_.ForEachObserver(
6417 [&](WebContentsObserver* observer) { observer->RenderViewDeleted(rvh); });
[email protected]2e4633c2009-07-09 16:58:066418}
6419
sky8b00392d2015-01-10 00:30:286420void WebContentsImpl::UpdateTargetURL(RenderViewHost* render_view_host,
6421 const GURL& url) {
6422 if (fullscreen_widget_routing_id_ != MSG_ROUTING_NONE) {
Lukasz Anforowiczfd707142018-02-07 19:46:136423 // If we're in flash fullscreen (i.e. Pepper plugin fullscreen) only update
6424 // the url if it's from the fullscreen renderer.
sky8b00392d2015-01-10 00:30:286425 RenderWidgetHostView* fs = GetFullscreenRenderWidgetHostView();
avif9ab5d942015-10-15 14:05:446426 if (fs && fs->GetRenderWidgetHost() != render_view_host->GetWidget())
sky8b00392d2015-01-10 00:30:286427 return;
6428 }
Lukasz Anforowiczfd707142018-02-07 19:46:136429
6430 // In case of racey updates from multiple RenderViewHosts, the last URL should
6431 // be shown - see also some discussion in https://crbug.com/807776.
6432 if (!url.is_valid() && render_view_host != view_that_set_last_target_url_)
6433 return;
6434 view_that_set_last_target_url_ = url.is_valid() ? render_view_host : nullptr;
6435
[email protected]6934a702011-12-20 00:04:516436 if (delegate_)
avi450ce00e2014-09-24 01:58:526437 delegate_->UpdateTargetURL(this, url);
[email protected]420ae012009-04-24 05:16:326438}
6439
Lukasz Anforowiczfd707142018-02-07 19:46:136440void WebContentsImpl::ClearTargetURL() {
6441 view_that_set_last_target_url_ = nullptr;
6442 if (delegate_)
6443 delegate_->UpdateTargetURL(this, GURL());
6444}
6445
[email protected]b172aee2012-04-10 17:05:266446void WebContentsImpl::Close(RenderViewHost* rvh) {
Avi Drissman7c57be72020-07-29 20:09:466447#if defined(OS_MAC)
[email protected]07707302009-11-06 00:50:296448 // The UI may be in an event-tracking loop, such as between the
6449 // mouse-down and mouse-up in text selection or a button click.
6450 // Defer the close until after tracking is complete, so that we
6451 // don't free objects out from under the UI.
[email protected]07707302009-11-06 00:50:296452 // TODO(shess): This could get more fine-grained. For instance,
6453 // closing a tab in another window while selecting text in the
6454 // current window's Omnibox should be just fine.
Christopher Cameron9ae31e0d2019-03-01 20:01:196455 if (view_->CloseTabAfterEventTrackingIfNeeded())
[email protected]07707302009-11-06 00:50:296456 return;
[email protected]60780f412013-02-25 16:34:106457#endif
[email protected]07707302009-11-06 00:50:296458
[email protected]420ae012009-04-24 05:16:326459 // Ignore this if it comes from a RenderViewHost that we aren't showing.
[email protected]151a63d2011-12-20 22:32:526460 if (delegate_ && rvh == GetRenderViewHost())
[email protected]6934a702011-12-20 00:04:516461 delegate_->CloseContents(this);
[email protected]420ae012009-04-24 05:16:326462}
6463
Avi Drissman014dec72018-06-07 02:34:016464void WebContentsImpl::RequestSetBounds(const gfx::Rect& new_bounds) {
6465 if (delegate_)
6466 delegate_->SetContentsBounds(this, new_bounds);
[email protected]420ae012009-04-24 05:16:326467}
6468
fdegansa696e5112015-04-17 01:57:596469void WebContentsImpl::DidStartLoading(FrameTreeNode* frame_tree_node,
[email protected]e3b10d12014-03-28 16:06:096470 bool to_different_document) {
Evan Stadec3b26022017-07-14 19:50:246471 LoadingStateChanged(frame_tree_node->IsMainFrame() && to_different_document,
Carlos IL07f282f2020-05-15 22:58:296472 nullptr);
dmazzonibf8cec42015-02-08 08:28:086473
Xiyuan Xia2a66b112018-12-06 15:52:166474 // Reset the focus state from DidStartNavigation to false if a new load starts
6475 // afterward, in case loading logic triggers a FocusLocationBarByDefault call.
6476 should_focus_location_bar_by_default_ = false;
Ian Prestcdd843d2020-01-28 18:59:586477
6478 // Notify accessibility that the user is navigating away from the
6479 // current document.
6480 // TODO(domfarolino, dmazzoni): Do this using WebContentsObserver. See
6481 // https://crbug.com/981271.
6482 BrowserAccessibilityManager* manager =
6483 frame_tree_node->current_frame_host()->browser_accessibility_manager();
6484 if (manager)
6485 manager->UserIsNavigatingAway();
[email protected]420ae012009-04-24 05:16:326486}
6487
fdegansc73eec22015-03-19 14:47:546488void WebContentsImpl::DidStopLoading() {
dcheng59716272016-04-09 05:19:086489 std::unique_ptr<LoadNotificationDetails> details;
[email protected]420ae012009-04-24 05:16:326490
[email protected]9595fd82013-04-19 21:28:496491 // Use the last committed entry rather than the active one, in case a
6492 // pending entry has been created.
6493 NavigationEntry* entry = controller_.GetLastCommittedEntry();
6494
[email protected]420ae012009-04-24 05:16:326495 // An entry may not exist for a stop when loading an initial blank page or
6496 // if an iframe injected by script into a blank page finishes loading.
6497 if (entry) {
[email protected]420ae012009-04-24 05:16:326498 details.reset(new LoadNotificationDetails(
[email protected]36fc0392011-12-25 03:59:516499 entry->GetVirtualURL(),
[email protected]420ae012009-04-24 05:16:326500 &controller_,
6501 controller_.GetCurrentEntryIndex()));
6502 }
6503
Carlos IL07f282f2020-05-15 22:58:296504 LoadingStateChanged(true, details.get());
[email protected]420ae012009-04-24 05:16:326505}
6506
fdegansa696e5112015-04-17 01:57:596507void WebContentsImpl::DidChangeLoadProgress() {
Nate Chapin22ea6592019-03-05 22:29:026508 if (is_being_destroyed_)
6509 return;
fdegansa696e5112015-04-17 01:57:596510 double load_progress = frame_tree_.load_progress();
6511
6512 // The delegate is notified immediately for the first and last updates. Also,
6513 // since the message loop may be pretty busy when a page is loaded, it might
6514 // not execute a posted task in a timely manner so the progress report is sent
6515 // immediately if enough time has passed.
6516 base::TimeDelta min_delay =
6517 base::TimeDelta::FromMilliseconds(kMinimumDelayBetweenLoadingUpdatesMS);
6518 bool delay_elapsed = loading_last_progress_update_.is_null() ||
6519 base::TimeTicks::Now() - loading_last_progress_update_ > min_delay;
6520
6521 if (load_progress == 0.0 || load_progress == 1.0 || delay_elapsed) {
6522 // If there is a pending task to send progress, it is now obsolete.
6523 loading_weak_factory_.InvalidateWeakPtrs();
6524
6525 // Notify the load progress change.
6526 SendChangeLoadProgress();
6527
6528 // Clean-up the states if needed.
6529 if (load_progress == 1.0)
6530 ResetLoadProgressState();
6531 return;
6532 }
6533
6534 if (loading_weak_factory_.HasWeakPtrs())
6535 return;
6536
skyostil95082a62015-06-05 19:53:076537 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
tzike2aca992017-09-05 08:50:546538 FROM_HERE,
6539 base::BindOnce(&WebContentsImpl::SendChangeLoadProgress,
6540 loading_weak_factory_.GetWeakPtr()),
fdegansa696e5112015-04-17 01:57:596541 min_delay);
6542}
6543
avid6d88b912017-01-13 00:16:006544std::vector<std::unique_ptr<NavigationThrottle>>
6545WebContentsImpl::CreateThrottlesForNavigation(
clamycbf524d42016-09-27 12:48:356546 NavigationHandle* navigation_handle) {
Charlie Reis96077362019-07-04 00:34:046547 auto throttles = GetContentClient()->browser()->CreateThrottlesForNavigation(
clamycbf524d42016-09-27 12:48:356548 navigation_handle);
Charlie Reis96077362019-07-04 00:34:046549
6550 // This is not a normal place to be adding a throttle. However, in the case
6551 // javascript dialogs, related logic is present in the web_contents/ layer,
6552 // and the purpose of the throttle is to ensure that navigation commits are
6553 // deferred for the entire WebContents. Most throttles are either added by
6554 // the embederrer outside of content/, or are per-frame and added by
6555 // NavigationThrottleRunner.
6556 std::unique_ptr<content::NavigationThrottle> dialog_throttle =
6557 JavaScriptDialogNavigationThrottle::MaybeCreateThrottleFor(
6558 navigation_handle);
6559 if (dialog_throttle)
6560 throttles.push_back(std::move(dialog_throttle));
6561
6562 return throttles;
clamycbf524d42016-09-27 12:48:356563}
6564
clamy1e5574e2016-09-29 16:48:446565std::unique_ptr<NavigationUIData> WebContentsImpl::GetNavigationUIData(
6566 NavigationHandle* navigation_handle) {
clamy1e5574e2016-09-29 16:48:446567 return GetContentClient()->browser()->GetNavigationUIData(navigation_handle);
6568}
6569
W. James MacLean1c40862c2020-04-27 21:05:576570void WebContentsImpl::RegisterExistingOriginToPreventOptInIsolation(
W. James MacLeanb70fab82020-05-01 18:51:146571 const url::Origin& origin,
6572 NavigationRequest* navigation_request_to_exclude) {
W. James MacLean1c40862c2020-04-27 21:05:576573 // Note: This function can be made static if we ever need call it without
6574 // a WebContentsImpl instance, in which case we can use a wrapper to
6575 // implement the override from NavigatorDelegate.
6576 for (WebContentsImpl* web_contents : GetAllWebContents()) {
6577 web_contents->controller_.RegisterExistingOriginToPreventOptInIsolation(
6578 origin);
W. James MacLeanb70fab82020-05-01 18:51:146579 // Walk the frame tree to pick up any frames without FrameNavigationEntries.
6580 // * Some frames won't have FrameNavigationEntries (Issues 524208, 608402).
6581 // * Some pending navigations won't have NavigationEntries.
6582 web_contents->GetFrameTree()->RegisterExistingOriginToPreventOptInIsolation(
6583 origin, navigation_request_to_exclude);
W. James MacLean1c40862c2020-04-27 21:05:576584 }
6585}
6586
pdr15f5b5b2017-06-20 00:58:006587void WebContentsImpl::DidCancelLoading() {
6588 controller_.DiscardNonCommittedEntries();
6589
6590 // Update the URL display.
6591 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
6592}
6593
[email protected]59167c22013-06-03 18:07:326594void WebContentsImpl::DidAccessInitialDocument() {
[email protected]b4c84012014-04-28 19:51:106595 has_accessed_initial_document_ = true;
6596
[email protected]d1371bf8e2014-04-19 03:26:246597 // We may have left a failed browser-initiated navigation in the address bar
6598 // to let the user edit it and try again. Clear it now that content might
6599 // show up underneath it.
6600 if (!IsLoading() && controller_.GetPendingEntry())
avi45a72532015-04-07 21:01:456601 controller_.DiscardPendingEntry(false);
[email protected]d1371bf8e2014-04-19 03:26:246602
[email protected]59167c22013-06-03 18:07:326603 // Update the URL display.
thestigc4cac8f2014-09-04 21:17:506604 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
[email protected]59167c22013-06-03 18:07:326605}
6606
alexmosbe2f4c32015-03-10 02:30:236607void WebContentsImpl::DidChangeName(RenderFrameHost* render_frame_host,
6608 const std::string& name) {
Alexander Timin90c20c32020-08-12 15:28:326609 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6610 observer->FrameNameChanged(render_frame_host, name);
6611 });
alexmosbe2f4c32015-03-10 02:30:236612}
6613
John Delaneyedd8d6c2019-01-25 00:23:576614void WebContentsImpl::DidReceiveFirstUserActivation(
6615 RenderFrameHost* render_frame_host) {
Alexander Timin90c20c32020-08-12 15:28:326616 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6617 observer->FrameReceivedFirstUserActivation(render_frame_host);
6618 });
John Delaneyedd8d6c2019-01-25 00:23:576619}
6620
John Delaney0146a742019-01-25 19:25:286621void WebContentsImpl::DidChangeDisplayState(RenderFrameHost* render_frame_host,
6622 bool is_display_none) {
Alexander Timin90c20c32020-08-12 15:28:326623 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6624 observer->FrameDisplayStateChanged(render_frame_host, is_display_none);
6625 });
John Delaney0146a742019-01-25 19:25:286626}
6627
6628void WebContentsImpl::FrameSizeChanged(RenderFrameHost* render_frame_host,
6629 const gfx::Size& frame_size) {
Alexander Timin90c20c32020-08-12 15:28:326630 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6631 observer->FrameSizeChanged(render_frame_host, frame_size);
6632 });
John Delaney0146a742019-01-25 19:25:286633}
6634
[email protected]39f2f9252014-05-03 00:54:016635void WebContentsImpl::DocumentOnLoadCompleted(
[email protected]50279492014-05-05 23:24:296636 RenderFrameHost* render_frame_host) {
falken52a56e32016-12-08 05:02:406637 ShowInsecureLocalhostWarningIfNeeded();
6638
Alexander Timindd0fa0c52019-11-06 13:03:376639 GetRenderViewHost()->DocumentOnLoadCompletedInMainFrame();
6640
Alexander Timin90c20c32020-08-12 15:28:326641 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6642 observer->DocumentOnLoadCompletedInMainFrame();
6643 });
[email protected]6578fef2013-10-14 02:35:096644
6645 // TODO(avi): Remove. http://crbug.com/170921
[email protected]8ff00d72012-10-23 19:12:216646 NotificationService::current()->Notify(
6647 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
6648 Source<WebContents>(this),
[email protected]50279492014-05-05 23:24:296649 NotificationService::NoDetails());
[email protected]25497492010-09-11 15:15:086650}
6651
creis8eb8ef22015-11-04 22:51:386652void WebContentsImpl::UpdateStateForFrame(RenderFrameHost* render_frame_host,
6653 const PageState& page_state) {
creis8eb8ef22015-11-04 22:51:386654 // The state update affects the last NavigationEntry associated with the given
6655 // |render_frame_host|. This may not be the last committed NavigationEntry (as
6656 // in the case of an UpdateState from a frame being swapped out). We track
6657 // which entry this is in the RenderFrameHost's nav_entry_id.
6658 RenderFrameHostImpl* rfhi =
6659 static_cast<RenderFrameHostImpl*>(render_frame_host);
6660 NavigationEntryImpl* entry =
6661 controller_.GetEntryWithUniqueID(rfhi->nav_entry_id());
6662 if (!entry)
6663 return;
6664
6665 FrameNavigationEntry* frame_entry =
6666 entry->GetFrameEntry(rfhi->frame_tree_node());
6667 if (!frame_entry)
6668 return;
6669
creisd06a9422015-11-11 03:08:456670 // The SiteInstance might not match if we do a cross-process navigation with
6671 // replacement (e.g., auto-subframe), in which case the swap out of the old
6672 // RenderFrameHost runs in the background after the old FrameNavigationEntry
6673 // has already been replaced and destroyed.
6674 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
6675 return;
6676
creis8eb8ef22015-11-04 22:51:386677 if (page_state == frame_entry->page_state())
6678 return; // Nothing to update.
6679
creis0cade2e2017-02-28 06:37:476680 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
nasko34634672016-07-29 18:46:066681
6682 // The document_sequence_number and item_sequence_number recorded in the
6683 // FrameNavigationEntry should not differ from the one coming with the update,
6684 // since it must come from the same document. Do not update it if a difference
6685 // is detected, as this indicates that |frame_entry| is not the correct one.
6686 ExplodedPageState exploded_state;
6687 if (!DecodePageState(page_state.ToEncodedData(), &exploded_state))
6688 return;
6689
6690 if (exploded_state.top.document_sequence_number !=
6691 frame_entry->document_sequence_number() ||
6692 exploded_state.top.item_sequence_number !=
6693 frame_entry->item_sequence_number()) {
6694 return;
6695 }
6696
nasko04a322f25a2016-09-01 00:00:346697 frame_entry->SetPageState(page_state);
creis8eb8ef22015-11-04 22:51:386698 controller_.NotifyEntryChanged(entry);
6699}
6700
[email protected]ef3adfc2014-05-11 00:04:546701void WebContentsImpl::UpdateTitle(RenderFrameHost* render_frame_host,
[email protected]ef3adfc2014-05-11 00:04:546702 const base::string16& title,
6703 base::i18n::TextDirection title_direction) {
[email protected]ef3adfc2014-05-11 00:04:546704 // Try to find the navigation entry, which might not be the current one.
avi286019ce2015-07-29 01:26:586705 // For example, it might be from a recently swapped out RFH.
avi1edc8552016-10-13 21:37:166706 NavigationEntryImpl* entry = controller_.GetEntryWithUniqueID(
creisad8c31a2016-05-24 17:07:046707 static_cast<RenderFrameHostImpl*>(render_frame_host)->nav_entry_id());
[email protected]ef3adfc2014-05-11 00:04:546708
6709 // We can handle title updates when we don't have an entry in
6710 // UpdateTitleForEntry, but only if the update is from the current RVH.
6711 // TODO(avi): Change to make decisions based on the RenderFrameHost.
avi286019ce2015-07-29 01:26:586712 if (!entry && render_frame_host != GetMainFrame())
[email protected]ef3adfc2014-05-11 00:04:546713 return;
6714
6715 // TODO(evan): make use of title_direction.
6716 // http://code.google.com/p/chromium/issues/detail?id=27094
afakhry6f0c1ec22016-07-14 13:55:136717 UpdateTitleForEntry(entry, title);
[email protected]ef3adfc2014-05-11 00:04:546718}
6719
alexmose7da5a12015-04-09 02:22:166720bool WebContentsImpl::ShouldRouteMessageEvent(
6721 RenderFrameHost* target_rfh,
6722 SiteInstance* source_site_instance) const {
6723 // Allow the message if this WebContents is dedicated to a browser plugin
6724 // guest.
[email protected]0eba810b2012-10-18 03:19:366725 // Note: This check means that an embedder could theoretically receive a
6726 // postMessage from anyone (not just its own guests). However, this is
6727 // probably not a risk for apps since other pages won't have references
6728 // to App windows.
alexmose7da5a12015-04-09 02:22:166729 return GetBrowserPluginGuest() || GetBrowserPluginEmbedder();
6730}
[email protected]f546640b2012-05-15 00:03:496731
alexmos58729042015-06-18 23:20:006732void WebContentsImpl::EnsureOpenerProxiesExist(RenderFrameHost* source_rfh) {
alexmose7da5a12015-04-09 02:22:166733 WebContentsImpl* source_web_contents = static_cast<WebContentsImpl*>(
6734 WebContents::FromRenderFrameHost(source_rfh));
[email protected]f546640b2012-05-15 00:03:496735
alexmose7da5a12015-04-09 02:22:166736 if (source_web_contents) {
lazyboy6ec48b2a2015-06-29 15:18:146737 // If this message is going to outer WebContents from inner WebContents,
6738 // then we should not create a RenderView. AttachToOuterWebContentsFrame()
6739 // already created a RenderFrameProxyHost for that purpose.
6740 if (GetBrowserPluginEmbedder() &&
W. James MacLean2539adb32019-12-13 00:40:446741 source_web_contents->browser_plugin_guest_) {
lazyboy6ec48b2a2015-06-29 15:18:146742 return;
W. James MacLean2539adb32019-12-13 00:40:446743 }
lazyboy6ec48b2a2015-06-29 15:18:146744
lfg812874d2016-02-09 22:26:136745 if (this != source_web_contents && GetBrowserPluginGuest()) {
naskob3041b98a42016-03-12 04:43:066746 // We create a RenderFrameProxyHost for the embedder in the guest's render
6747 // process but we intentionally do not expose the embedder's opener chain
6748 // to it.
6749 source_web_contents->GetRenderManager()->CreateRenderFrameProxy(
6750 GetSiteInstance());
[email protected]f546640b2012-05-15 00:03:496751 } else {
alexmos58729042015-06-18 23:20:006752 RenderFrameHostImpl* source_rfhi =
6753 static_cast<RenderFrameHostImpl*>(source_rfh);
6754 source_rfhi->frame_tree_node()->render_manager()->CreateOpenerProxies(
alexmos90325cf2015-09-02 17:18:396755 GetSiteInstance(), nullptr);
[email protected]f546640b2012-05-15 00:03:496756 }
6757 }
[email protected]f546640b2012-05-15 00:03:496758}
6759
avallee9993fca2016-11-17 06:16:506760void WebContentsImpl::SetAsFocusedWebContentsIfNecessary() {
Adithya Srinivasan11af2c52019-12-16 22:52:556761 DCHECK(!portal());
avallee9993fca2016-11-17 06:16:506762 // Only change focus if we are not currently focused.
6763 WebContentsImpl* old_contents = GetFocusedWebContents();
6764 if (old_contents == this)
6765 return;
6766
paulmeyerfeafc2d2017-04-25 21:46:406767 GetOutermostWebContents()->node_.SetFocusedWebContents(this);
6768
avallee9993fca2016-11-17 06:16:506769 // Send a page level blur to the old contents so that it displays inactive UI
6770 // and focus this contents to activate it.
6771 if (old_contents)
6772 old_contents->GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(false);
avalleec2ff1ef2017-01-21 00:12:306773
6774 // Make sure the outer web contents knows our frame is focused. Otherwise, the
6775 // outer renderer could have the element before or after the frame element
6776 // focused which would return early without actually advancing focus.
avalleed68cdd12017-06-21 22:07:276777 FocusOuterAttachmentFrameChain();
avalleec2ff1ef2017-01-21 00:12:306778
Carlos ILd51e7702020-05-07 18:51:396779 GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(true);
avallee9993fca2016-11-17 06:16:506780}
6781
avallee0206f782016-07-28 18:55:336782void WebContentsImpl::SetFocusedFrame(FrameTreeNode* node,
6783 SiteInstance* source) {
Adithya Srinivasan11af2c52019-12-16 22:52:556784 DCHECK(!portal());
avallee0206f782016-07-28 18:55:336785 frame_tree_.SetFocusedFrame(node, source);
avalleed68cdd12017-06-21 22:07:276786
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:576787 if (auto* inner_contents = node_.GetInnerWebContentsInFrame(node)) {
6788 // |this| is an outer WebContents and |node| represents an inner
6789 // WebContents. Transfer the focus to the inner contents if |this| is
6790 // focused.
6791 if (GetFocusedWebContents() == this)
6792 inner_contents->SetAsFocusedWebContentsIfNecessary();
6793 } else if (node_.OuterContentsFrameTreeNode() &&
6794 node_.OuterContentsFrameTreeNode()
6795 ->current_frame_host()
6796 ->GetSiteInstance() == source) {
6797 // |this| is an inner WebContents, |node| is its main FrameTreeNode and
6798 // the outer WebContents FrameTreeNode is at |source|'s SiteInstance.
6799 // Transfer the focus to the inner WebContents if the outer WebContents is
6800 // focused. This branch is used when an inner WebContents is focused through
Lowell Mannersa9530382019-08-01 09:46:576801 // its RenderFrameProxyHost (via FrameFocused mojo call, used to
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:576802 // implement the window.focus() API).
6803 if (GetFocusedWebContents() == GetOuterWebContents())
6804 SetAsFocusedWebContentsIfNecessary();
6805 } else if (!GetOuterWebContents()) {
6806 // This is an outermost WebContents.
6807 SetAsFocusedWebContentsIfNecessary();
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:576808 }
avalleed68cdd12017-06-21 22:07:276809}
6810
Avi Drissman36f801f2018-02-01 20:06:046811void WebContentsImpl::DidCallFocus() {
6812 // Any explicit focusing of another window while this WebContents is in
6813 // fullscreen can be used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:456814 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
6815 // The other contents is independent of this contents, so release the
6816 // fullscreen block.
6817 fullscreen_block.RunAndReset();
Avi Drissman36f801f2018-02-01 20:06:046818}
6819
avalleed68cdd12017-06-21 22:07:276820RenderFrameHost* WebContentsImpl::GetFocusedFrameIncludingInnerWebContents() {
6821 WebContentsImpl* contents = this;
6822 FrameTreeNode* focused_node = contents->frame_tree_.GetFocusedFrame();
6823
6824 // If there is no focused frame in the outer WebContents, we need to return
6825 // null.
6826 if (!focused_node)
6827 return nullptr;
6828
6829 // If the focused frame is embedding an inner WebContents, we must descend
6830 // into that contents. If the current WebContents does not have a focused
6831 // frame, return the main frame of this contents instead of the focused empty
6832 // frame embedding this contents.
6833 while (true) {
6834 contents = contents->node_.GetInnerWebContentsInFrame(focused_node);
6835 if (!contents)
6836 return focused_node->current_frame_host();
6837
6838 focused_node = contents->frame_tree_.GetFocusedFrame();
6839 if (!focused_node)
6840 return contents->GetMainFrame();
6841 }
avallee0206f782016-07-28 18:55:336842}
6843
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:576844void WebContentsImpl::OnAdvanceFocus(RenderFrameHostImpl* source_rfh) {
6845 // When a RenderFrame needs to advance focus to a RenderFrameProxy (by hitting
6846 // TAB), the RenderFrameProxy sends an IPC to RenderFrameProxyHost. When this
6847 // RenderFrameProxyHost represents an inner WebContents, the outer WebContents
6848 // needs to focus the inner WebContents.
6849 if (GetOuterWebContents() &&
6850 GetOuterWebContents() == source_rfh->delegate()->GetAsWebContents() &&
6851 GetFocusedWebContents() == GetOuterWebContents()) {
6852 SetAsFocusedWebContentsIfNecessary();
6853 }
6854}
6855
ekaramada110f642016-12-21 19:47:286856void WebContentsImpl::OnFocusedElementChangedInFrame(
6857 RenderFrameHostImpl* frame,
6858 const gfx::Rect& bounds_in_root_view) {
6859 RenderWidgetHostViewBase* root_view =
6860 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
6861 if (!root_view || !frame->GetView())
6862 return;
Katie De0131372020-07-09 23:03:106863 // Convert to screen coordinates from window coordinates by adding the
6864 // window's origin.
ekaramada110f642016-12-21 19:47:286865 gfx::Point origin = bounds_in_root_view.origin();
6866 origin += root_view->GetViewBounds().OffsetFromOrigin();
6867 gfx::Rect bounds_in_screen(origin, bounds_in_root_view.size());
6868
6869 root_view->FocusedNodeChanged(frame->has_focused_editable_element(),
6870 bounds_in_screen);
6871
6872 FocusedNodeDetails details = {frame->has_focused_editable_element(),
6873 bounds_in_screen};
6874
6875 // TODO(ekaramad): We should replace this with an observer notification
6876 // (https://crbug.com/675975).
6877 NotificationService::current()->Notify(
6878 NOTIFICATION_FOCUS_CHANGED_IN_PAGE,
6879 Source<RenderViewHost>(GetRenderViewHost()),
6880 Details<FocusedNodeDetails>(&details));
Jeff Fisher709b4c52019-07-29 20:07:346881
Alexander Timin90c20c32020-08-12 15:28:326882 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6883 observer->OnFocusChangedInPage(&details);
6884 });
ekaramada110f642016-12-21 19:47:286885}
6886
Lowell Manners1de5242e2019-04-25 10:18:466887bool WebContentsImpl::DidAddMessageToConsole(
6888 blink::mojom::ConsoleMessageLevel log_level,
6889 const base::string16& message,
6890 int32_t line_no,
6891 const base::string16& source_id) {
Alexander Timin90c20c32020-08-12 15:28:326892 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6893 observer->OnDidAddMessageToConsole(log_level, message, line_no, source_id);
6894 });
[email protected]a796f202012-05-30 14:14:256895 if (!delegate_)
6896 return false;
Lowell Manners1de5242e2019-04-25 10:18:466897 return delegate_->DidAddMessageToConsole(this, log_level, message, line_no,
avia90ae4e2016-11-11 20:49:336898 source_id);
[email protected]a796f202012-05-30 14:14:256899}
6900
Daniel Cheng90196c82018-04-25 21:49:146901void WebContentsImpl::DidReceiveInputEvent(
dominickn9c7ceaa32016-02-27 01:52:536902 RenderWidgetHostImpl* render_widget_host,
Emily Starkc7bd40c42020-07-21 19:12:556903 const blink::WebInputEvent& event) {
6904 if (!IsUserInteractionInputType(event.GetType()))
Daniel Cheng90196c82018-04-25 21:49:146905 return;
6906
kenrb19221852016-04-29 17:21:406907 // Ignore unless the widget is currently in the frame tree.
6908 if (!HasMatchingWidgetHost(&frame_tree_, render_widget_host))
avic3aa8422015-11-09 20:57:226909 return;
6910
Emily Starkc7bd40c42020-07-21 19:12:556911 if (event.GetType() != blink::WebInputEvent::Type::kGestureScrollBegin)
Daniel Cheng90196c82018-04-25 21:49:146912 last_interactive_input_event_time_ = ui::EventTimeForNow();
dominickn9c7ceaa32016-02-27 01:52:536913
Alexander Timin90c20c32020-08-12 15:28:326914 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6915 observer->DidGetUserInteraction(event);
6916 });
dominickn2dd142dd2015-10-29 05:30:506917}
6918
Avi Drissman738ea192018-08-29 20:24:166919bool WebContentsImpl::ShouldIgnoreInputEvents() {
6920 WebContentsImpl* web_contents = this;
6921 while (web_contents) {
6922 if (web_contents->ignore_input_events_)
6923 return true;
6924 web_contents = web_contents->GetOuterWebContents();
6925 }
6926
6927 return false;
6928}
6929
avallee9993fca2016-11-17 06:16:506930void WebContentsImpl::FocusOwningWebContents(
6931 RenderWidgetHostImpl* render_widget_host) {
Alex Moshchukc4f0a722019-11-19 22:41:286932 RenderWidgetHostImpl* main_frame_widget_host =
6933 GetMainFrame()->GetRenderWidgetHost();
avallee9993fca2016-11-17 06:16:506934 RenderWidgetHostImpl* focused_widget =
Alex Moshchukc4f0a722019-11-19 22:41:286935 GetFocusedRenderWidgetHost(main_frame_widget_host);
avallee9993fca2016-11-17 06:16:506936
6937 if (focused_widget != render_widget_host &&
avallee8e881592016-11-19 00:39:306938 (!focused_widget ||
6939 focused_widget->delegate() != render_widget_host->delegate())) {
avallee9993fca2016-11-17 06:16:506940 SetAsFocusedWebContentsIfNecessary();
6941 }
6942}
6943
[email protected]b172aee2012-04-10 17:05:266944void WebContentsImpl::OnIgnoredUIEvent() {
[email protected]31145092011-09-30 01:49:446945 // Notify observers.
Alexander Timin90c20c32020-08-12 15:28:326946 observers_.ForEachObserver(
6947 [&](WebContentsObserver* observer) { observer->DidGetIgnoredUIEvent(); });
[email protected]fa1cf0b82010-01-15 21:49:446948}
6949
avic3aa8422015-11-09 20:57:226950void WebContentsImpl::RendererUnresponsive(
Lukasz Anforowicz52b93722018-06-20 16:11:396951 RenderWidgetHostImpl* render_widget_host,
6952 base::RepeatingClosure hang_monitor_restarter) {
avic031d392017-03-03 03:09:426953 if (ShouldIgnoreUnresponsiveRenderer())
[email protected]e5fc1632011-08-08 07:51:536954 return;
6955
Lukasz Anforowicz4f0593d2018-09-21 18:33:546956 // Do not report hangs (to task manager, to hang renderer dialog, etc.) for
6957 // invisible tabs (like extension background page, background tabs). See
6958 // https://crbug.com/881812 for rationale and for choosing the visibility
6959 // (rather than process priority) as the signal here.
6960 if (GetVisibility() != Visibility::VISIBLE)
6961 return;
6962
Avi Drissman8920def2018-01-31 19:53:366963 if (!render_widget_host->renderer_initialized())
[email protected]55452902011-06-01 21:57:476964 return;
6965
Alexander Timin90c20c32020-08-12 15:28:326966 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6967 observer->OnRendererUnresponsive(render_widget_host->GetProcess());
6968 });
Dave Tapuskac6146c52017-12-20 22:48:156969 if (delegate_)
Lukasz Anforowicz52b93722018-06-20 16:11:396970 delegate_->RendererUnresponsive(this, render_widget_host,
6971 std::move(hang_monitor_restarter));
[email protected]420ae012009-04-24 05:16:326972}
6973
avic3aa8422015-11-09 20:57:226974void WebContentsImpl::RendererResponsive(
6975 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin90c20c32020-08-12 15:28:326976 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6977 observer->OnRendererResponsive(render_widget_host->GetProcess());
6978 });
[email protected]6934a702011-12-20 00:04:516979 if (delegate_)
Avi Drissman1572e8c3c2018-02-02 19:06:366980 delegate_->RendererResponsive(this, render_widget_host);
[email protected]420ae012009-04-24 05:16:326981}
6982
Alex Moshchuk7b4f0652019-05-30 18:54:416983void WebContentsImpl::SubframeCrashed(
6984 blink::mojom::FrameVisibility visibility) {
6985 // If a subframe crashed on a hidden tab, mark the tab for reload to avoid
6986 // showing a sad frame to the user if they ever switch back to that tab. Do
6987 // this for subframes that are either visible in viewport or visible but
6988 // scrolled out of view, but skip subframes that are not rendered (e.g., via
6989 // "display:none"), since in that case the user wouldn't see a sad frame
6990 // anyway.
6991 bool did_mark_for_reload = false;
6992 if (IsHidden() && visibility != blink::mojom::FrameVisibility::kNotRendered &&
6993 base::FeatureList::IsEnabled(
6994 features::kReloadHiddenTabsWithCrashedSubframes)) {
6995 controller_.SetNeedsReload(
6996 NavigationControllerImpl::NeedsReloadType::kCrashedSubframe);
6997 did_mark_for_reload = true;
6998 UMA_HISTOGRAM_ENUMERATION(
6999 "Stability.ChildFrameCrash.TabMarkedForReload.Visibility", visibility);
7000 }
7001
7002 UMA_HISTOGRAM_BOOLEAN("Stability.ChildFrameCrash.TabMarkedForReload",
7003 did_mark_for_reload);
7004}
7005
[email protected]b172aee2012-04-10 17:05:267006void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
[email protected]feaded02012-09-25 19:12:557007 bool proceed, const base::TimeTicks& proceed_time,
[email protected]420ae012009-04-24 05:16:327008 bool* proceed_to_fire_unload) {
Alexander Timin90c20c32020-08-12 15:28:327009 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7010 observer->BeforeUnloadFired(proceed, proceed_time);
7011 });
[email protected]6934a702011-12-20 00:04:517012 if (delegate_)
7013 delegate_->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
[email protected]e80af492013-06-24 21:52:097014 // Note: |this| might be deleted at this point.
[email protected]420ae012009-04-24 05:16:327015}
7016
[email protected]58d5cfe2013-07-10 02:40:527017void WebContentsImpl::RenderProcessGoneFromRenderManager(
[email protected]3a3d47472010-07-15 21:03:547018 RenderViewHost* render_view_host) {
[email protected]443b80e2010-12-14 00:42:237019 DCHECK(crashed_status_ != base::TERMINATION_STATUS_STILL_RUNNING);
[email protected]ec6a7eb2013-04-22 17:34:227020 RenderViewTerminated(render_view_host, crashed_status_, crashed_error_code_);
[email protected]3a3d47472010-07-15 21:03:547021}
7022
[email protected]af905902013-10-01 21:38:517023void WebContentsImpl::CancelModalDialogsForRenderManager() {
7024 // We need to cancel modal dialogs when doing a process swap, since the load
avi2460c762015-04-17 15:21:547025 // deferrer would prevent us from swapping out. We also clear the state
7026 // because this is a cross-process navigation, which means that it's a new
7027 // site that should not have to pay for the sins of its predecessor.
creis89a0f782015-05-27 16:13:177028 //
Lei Zhang6410ec1a2019-01-31 21:38:587029 // Note that we don't bother telling |browser_plugin_embedder_| because the
creis89a0f782015-05-27 16:13:177030 // cross-process navigation will either destroy the browser plugins or not
7031 // require their dialogs to close.
avi5d3b8692016-10-12 22:00:467032 if (dialog_manager_) {
avi6879fcf2017-01-21 05:27:537033 dialog_manager_->CancelDialogs(this, /*reset_state=*/true);
avi5d3b8692016-10-12 22:00:467034 }
[email protected]af905902013-10-01 21:38:517035}
7036
danakja0bce4c952020-05-12 20:40:287037void WebContentsImpl::NotifySwappedFromRenderManager(RenderFrameHost* old_frame,
7038 RenderFrameHost* new_frame,
[email protected]02d7b6e2014-06-24 21:01:507039 bool is_main_frame) {
7040 if (is_main_frame) {
danakja0bce4c952020-05-12 20:40:287041 // The |new_frame| and its various compadres are already swapped into place
7042 // for the WebContentsImpl when this method is called.
7043 DCHECK(GetMainFrame() == new_frame);
7044 DCHECK(GetRenderViewHost() == new_frame->GetRenderViewHost());
7045 DCHECK(GetRenderWidgetHostView() == new_frame->GetView());
7046
Fergal Daly6767b2e2020-02-04 03:15:167047 RenderViewHost* old_rvh =
danakja0bce4c952020-05-12 20:40:287048 old_frame ? old_frame->GetRenderViewHost() : nullptr;
7049 RenderViewHost* new_rvh = new_frame->GetRenderViewHost();
Fergal Daly6767b2e2020-02-04 03:15:167050 // |old_rvh| and |new_rvh| might be equal when navigating from a crashed
7051 // RenderFrameHost to a new same-site one. With RenderDocument, this will
7052 // happen for every same-site navigation.
7053 if (old_rvh != new_rvh)
7054 NotifyViewSwapped(old_rvh, new_rvh);
[email protected]a6b73c62013-02-11 23:05:087055
[email protected]02d7b6e2014-06-24 21:01:507056 // Make sure the visible RVH reflects the new delegate's preferences.
7057 if (delegate_)
7058 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
[email protected]d56a49e2013-02-23 00:47:397059
danakja0bce4c952020-05-12 20:40:287060 auto* rwhv = static_cast<RenderWidgetHostViewBase*>(new_frame->GetView());
7061 if (rwhv) {
7062 rwhv->SetMainFrameAXTreeID(new_frame->GetAXTreeID());
7063
7064 // The RenderWidgetHostView for the speculative RenderFrameHost is not
7065 // resized with the current RenderFrameHost while a navigation is
7066 // pending. So when we swap in the main frame, we need to update the
7067 // RenderWidgetHostView's size.
7068 //
7069 // Historically, this was done to fix b/1079768 for interstitials.
7070 rwhv->SetSize(GetSizeForMainFrame());
7071 }
[email protected]02d7b6e2014-06-24 21:01:507072 }
7073
danakja0bce4c952020-05-12 20:40:287074 NotifyFrameSwapped(old_frame, new_frame, is_main_frame);
[email protected]3a3d47472010-07-15 21:03:547075}
7076
naskof5940b9f2015-03-02 23:04:057077void WebContentsImpl::NotifyMainFrameSwappedFromRenderManager(
danakja0bce4c952020-05-12 20:40:287078 RenderFrameHost* old_frame,
7079 RenderFrameHost* new_frame) {
7080 NotifyViewSwapped(old_frame ? old_frame->GetRenderViewHost() : nullptr,
7081 new_frame->GetRenderViewHost());
naskof5940b9f2015-03-02 23:04:057082}
7083
[email protected]b172aee2012-04-10 17:05:267084NavigationControllerImpl& WebContentsImpl::GetControllerForRenderManager() {
[email protected]d1198fd2012-08-13 22:50:197085 return GetController();
[email protected]3a3d47472010-07-15 21:03:547086}
7087
dcheng59716272016-04-09 05:19:087088std::unique_ptr<WebUIImpl> WebContentsImpl::CreateWebUIForRenderFrameHost(
Miyoung Shin072d4052020-07-13 07:52:447089 RenderFrameHost* frame_host,
Denis Kuznetsov [CET]2c6f0159f2020-05-18 14:18:167090 const GURL& url) {
Miyoung Shin072d4052020-07-13 07:52:447091 return CreateWebUI(frame_host, url);
[email protected]420ae012009-04-24 05:16:327092}
7093
lfgbede6392015-09-11 21:54:067094void WebContentsImpl::CreateRenderWidgetHostViewForRenderManager(
7095 RenderViewHost* render_view_host) {
lfgc740d4b22016-04-15 16:45:337096 RenderWidgetHostViewBase* rwh_view =
W. James MacLean13d834d2019-12-04 16:06:457097 view_->CreateViewForWidget(render_view_host->GetWidget());
danakja0bce4c952020-05-12 20:40:287098 rwh_view->SetSize(GetSizeForMainFrame());
lfgbede6392015-09-11 21:54:067099}
7100
7101bool WebContentsImpl::CreateRenderViewForRenderManager(
7102 RenderViewHost* render_view_host,
Antonio Gomesb3dd5fc2020-05-25 22:53:277103 const base::Optional<base::UnguessableToken>& opener_frame_token,
Daniel Chengabfdb002020-06-04 06:02:307104 int proxy_routing_id) {
lfgbede6392015-09-11 21:54:067105 TRACE_EVENT0("browser,navigation",
7106 "WebContentsImpl::CreateRenderViewForRenderManager");
7107
piman00cf9402017-04-03 17:09:207108 if (proxy_routing_id == MSG_ROUTING_NONE)
lfg9431efd2016-12-14 14:45:267109 CreateRenderWidgetHostViewForRenderManager(render_view_host);
lfg9431efd2016-12-14 14:45:267110
piman00cf9402017-04-03 17:09:207111 if (!static_cast<RenderViewHostImpl*>(render_view_host)
Daniel Chengabfdb002020-06-04 06:02:307112 ->CreateRenderView(opener_frame_token, proxy_routing_id,
Antonio Gomesb3dd5fc2020-05-25 22:53:277113 created_with_opener_)) {
[email protected]a4127722011-04-27 23:13:527114 return false;
[email protected]14392a52012-05-02 20:28:447115 }
W. James MacLean62198672019-06-04 16:46:107116 // Set the TextAutosizer state from the main frame's renderer on the new view,
7117 // but only if it's not for the main frame. Main frame renderers should create
7118 // this state themselves from up-to-date values, so we shouldn't override it
7119 // with the cached values.
7120 if (!render_view_host->GetMainFrame()) {
Antonio Gomesda7e03d2020-08-05 15:03:087121 auto* proxy_host = GetRenderManager()->GetRenderFrameProxyHost(
7122 render_view_host->GetSiteInstance());
7123 proxy_host->GetAssociatedRemoteMainFrame()->UpdateTextAutosizerPageInfo(
7124 text_autosizer_page_info_.Clone());
W. James MacLean62198672019-06-04 16:46:107125 }
[email protected]a4127722011-04-27 23:13:527126
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:147127 if (proxy_routing_id == MSG_ROUTING_NONE && node_.outer_web_contents())
7128 ReattachToOuterWebContentsFrame();
7129
avi2b177592014-12-10 02:08:027130 SetHistoryOffsetAndLengthForView(render_view_host,
7131 controller_.GetLastCommittedEntryIndex(),
7132 controller_.GetEntryCount());
7133
Avi Drissman7c57be72020-07-29 20:09:467134#if defined(OS_POSIX) && !defined(OS_MAC) && !defined(OS_ANDROID)
[email protected]f8233cc2011-05-31 20:24:507135 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
7136 // linux. See crbug.com/83941.
avif9ab5d942015-10-15 14:05:447137 RenderWidgetHostView* rwh_view = render_view_host->GetWidget()->GetView();
[email protected]245f7d52011-11-28 15:36:447138 if (rwh_view) {
7139 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
Fady Samuel0b911822018-04-25 13:22:167140 render_widget_host->SynchronizeVisualProperties();
[email protected]245f7d52011-11-28 15:36:447141 }
[email protected]f8233cc2011-05-31 20:24:507142#endif
7143
[email protected]420ae012009-04-24 05:16:327144 return true;
7145}
7146
[email protected]82307f6b2014-08-07 03:30:127147bool WebContentsImpl::CreateRenderFrameForRenderManager(
7148 RenderFrameHost* render_frame_host,
arthursonzogni1efc7b962019-03-14 09:36:337149 int previous_routing_id,
Antonio Gomes9d150542020-05-25 18:32:117150 const base::Optional<base::UnguessableToken>& opener_frame_token,
japhete6adf142014-10-31 00:01:497151 int parent_routing_id,
alexmosa181efc2015-09-03 00:39:047152 int previous_sibling_routing_id) {
naskob8744d22014-08-28 17:07:437153 TRACE_EVENT0("browser,navigation",
7154 "WebContentsImpl::CreateRenderFrameForRenderManager");
[email protected]82307f6b2014-08-07 03:30:127155
7156 RenderFrameHostImpl* rfh =
7157 static_cast<RenderFrameHostImpl*>(render_frame_host);
Antonio Gomes9d150542020-05-25 18:32:117158 if (!rfh->CreateRenderFrame(previous_routing_id, opener_frame_token,
7159 parent_routing_id, previous_sibling_routing_id)) {
[email protected]82307f6b2014-08-07 03:30:127160 return false;
Antonio Gomes9d150542020-05-25 18:32:117161 }
[email protected]82307f6b2014-08-07 03:30:127162
7163 // TODO(nasko): When RenderWidgetHost is owned by RenderFrameHost, the passed
7164 // RenderFrameHost will have to be associated with the appropriate
7165 // RenderWidgetHostView or a new one should be created here.
7166
7167 return true;
7168}
7169
mfomitchev2b8b066a2016-01-28 19:23:157170#if defined(OS_ANDROID)
[email protected]fc2b46b2014-05-03 16:33:457171
[email protected]155c7f22013-12-09 17:07:187172base::android::ScopedJavaLocalRef<jobject>
7173WebContentsImpl::GetJavaWebContents() {
mostynb042582e2015-03-16 22:13:407174 DCHECK_CURRENTLY_ON(BrowserThread::UI);
[email protected]0e813a52014-08-13 10:34:567175 return GetWebContentsAndroid()->GetJavaObject();
7176}
[email protected]155c7f22013-12-09 17:07:187177
[email protected]0e813a52014-08-13 10:34:567178WebContentsAndroid* WebContentsImpl::GetWebContentsAndroid() {
Kevin McNee576bb5d82019-05-29 16:47:517179 if (!web_contents_android_) {
7180 web_contents_android_ = std::make_unique<WebContentsAndroid>(this);
[email protected]155c7f22013-12-09 17:07:187181 }
Kevin McNee576bb5d82019-05-29 16:47:517182 return web_contents_android_.get();
7183}
7184
7185void WebContentsImpl::ClearWebContentsAndroid() {
7186 DCHECK_CURRENTLY_ON(BrowserThread::UI);
7187 web_contents_android_.reset();
[email protected]155c7f22013-12-09 17:07:187188}
7189
paulmeyerc0b762b2016-04-13 11:55:177190void WebContentsImpl::ActivateNearestFindResult(float x,
7191 float y) {
7192 GetOrCreateFindRequestManager()->ActivateNearestFindResult(x, y);
7193}
7194
7195void WebContentsImpl::RequestFindMatchRects(int current_version) {
7196 GetOrCreateFindRequestManager()->RequestFindMatchRects(current_version);
7197}
7198
rockot400ea35b2016-10-15 19:15:327199service_manager::InterfaceProvider* WebContentsImpl::GetJavaInterfaces() {
sammcf5f1b0f2016-09-20 23:05:117200 if (!java_interfaces_) {
Gyuyoung Kim6c9ce9022019-11-26 05:40:087201 mojo::PendingRemote<service_manager::mojom::InterfaceProvider> provider;
7202 BindInterfaceRegistryForWebContents(
7203 provider.InitWithNewPipeAndPassReceiver(), this);
rockot400ea35b2016-10-15 19:15:327204 java_interfaces_.reset(new service_manager::InterfaceProvider);
sammcf5f1b0f2016-09-20 23:05:117205 java_interfaces_->Bind(std::move(provider));
7206 }
7207 return java_interfaces_.get();
7208}
7209
Francois Doray6c26f3342018-08-24 17:17:227210#endif
7211
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:417212bool WebContentsImpl::CompletedFirstVisuallyNonEmptyPaint() {
Carlos Caballero91fffb22019-10-29 15:24:307213 return GetRenderViewHost()->did_first_visually_non_empty_paint();
spqchane72c3cb2017-06-30 23:02:107214}
7215
pkotwicz75ca8ffd2016-02-16 23:10:197216void WebContentsImpl::OnDidDownloadImage(
Avi Drissmana5a52dd2018-03-27 03:39:027217 ImageDownloadCallback callback,
pkotwicz75ca8ffd2016-02-16 23:10:197218 int id,
7219 const GURL& image_url,
leon.hancbc4bc3c2016-02-26 07:08:527220 int32_t http_status_code,
leon.hanc2228532016-08-16 05:59:187221 const std::vector<SkBitmap>& images,
7222 const std::vector<gfx::Size>& original_image_sizes) {
Avi Drissmana5a52dd2018-03-27 03:39:027223 std::move(callback).Run(id, http_status_code, image_url, images,
7224 original_image_sizes);
pkotwicz75ca8ffd2016-02-16 23:10:197225}
7226
[email protected]6fba26d2014-04-29 09:38:287227void WebContentsImpl::OnDialogClosed(int render_process_id,
7228 int render_frame_id,
Dave Tapuskacdf545cc2020-01-23 18:38:527229 JavaScriptDialogCallback response_callback,
Avi Drissman1a55a9d62020-03-10 18:56:457230 base::ScopedClosureRunner fullscreen_block,
[email protected]87de04b02014-04-08 22:14:497231 bool dialog_was_suppressed,
[email protected]b172aee2012-04-10 17:05:267232 bool success,
[email protected]fcf75d42013-12-03 20:11:267233 const base::string16& user_input) {
[email protected]6fba26d2014-04-29 09:38:287234 RenderFrameHostImpl* rfh = RenderFrameHostImpl::FromID(render_process_id,
7235 render_frame_id);
[email protected]87de04b02014-04-08 22:14:497236 last_dialog_suppressed_ = dialog_was_suppressed;
Avi Drissman1a55a9d62020-03-10 18:56:457237 fullscreen_block.RunAndReset();
[email protected]87de04b02014-04-08 22:14:497238
Charlie Reis96077362019-07-04 00:34:047239 javascript_dialog_navigation_deferrer_.reset();
7240
[email protected]beb440c2009-11-06 04:08:547241 if (is_showing_before_unload_dialog_ && !success) {
clamybc6f4152016-04-01 20:14:237242 // It is possible for the current RenderFrameHost to have changed in the
7243 // meantime. Do not reset the navigation state in that case.
7244 if (rfh && rfh == rfh->frame_tree_node()->current_frame_host()) {
clamy44e84ce2016-02-22 15:38:257245 rfh->frame_tree_node()->BeforeUnloadCanceled();
clamybc6f4152016-04-01 20:14:237246 controller_.DiscardNonCommittedEntries();
7247 }
[email protected]ec8e8b02013-06-19 04:57:107248
Charles Reis15d60b132017-11-03 17:43:477249 // Update the URL display either way, to avoid showing a stale URL.
7250 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
7251
Alexander Timin90c20c32020-08-12 15:28:327252 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7253 observer->BeforeUnloadDialogCancelled();
7254 });
[email protected]beb440c2009-11-06 04:08:547255 }
[email protected]87de04b02014-04-08 22:14:497256
Dave Tapuskacdf545cc2020-01-23 18:38:527257 std::move(response_callback).Run(success, user_input);
Pavel Feldman3c1842b2017-08-02 05:00:167258
Dave Tapuskacdf545cc2020-01-23 18:38:527259 std::vector<protocol::PageHandler*> page_handlers =
7260 protocol::PageHandler::EnabledForWebContents(this);
7261 for (auto* handler : page_handlers)
7262 handler->DidCloseJavaScriptDialog(success, user_input);
avi1c51fb62017-02-27 20:43:037263
7264 is_showing_javascript_dialog_ = false;
7265 is_showing_before_unload_dialog_ = false;
[email protected]beb440c2009-11-06 04:08:547266}
7267
[email protected]1ac10dca2013-08-20 20:47:047268bool WebContentsImpl::IsHidden() {
Francois Doraye6161152018-03-27 22:05:377269 return !IsBeingCaptured() && visibility_ != Visibility::VISIBLE;
[email protected]1ac10dca2013-08-20 20:47:047270}
7271
rob97250742015-12-10 17:45:157272int WebContentsImpl::GetOuterDelegateFrameTreeNodeId() {
lfg601233692017-03-06 22:45:447273 return node_.outer_contents_frame_tree_node_id();
lazyboy6ec48b2a2015-06-29 15:18:147274}
7275
ekaramadaeb3c5c2016-11-09 03:22:357276RenderWidgetHostImpl* WebContentsImpl::GetFullscreenRenderWidgetHost() const {
7277 return RenderWidgetHostImpl::FromID(fullscreen_widget_process_id_,
7278 fullscreen_widget_routing_id_);
7279}
7280
[email protected]b0936d22013-11-28 06:47:367281RenderFrameHostManager* WebContentsImpl::GetRenderManager() const {
[email protected]fa944cb82013-11-15 17:51:217282 return frame_tree_.root()->render_manager();
7283}
7284
[email protected]f8497342013-02-05 22:15:027285BrowserPluginGuest* WebContentsImpl::GetBrowserPluginGuest() const {
[email protected]7a846df2012-09-20 19:17:397286 return browser_plugin_guest_.get();
7287}
7288
Albert J. Wongc55cc64d2018-10-12 02:50:047289void WebContentsImpl::SetBrowserPluginGuest(
7290 std::unique_ptr<BrowserPluginGuest> guest) {
7291 DCHECK(!browser_plugin_guest_);
7292 DCHECK(guest);
7293 browser_plugin_guest_ = std::move(guest);
[email protected]738f57a2013-06-29 21:06:547294}
7295
Aidan Wolter52bcc12a2018-11-14 03:27:297296base::UnguessableToken WebContentsImpl::GetAudioGroupId() {
Aidan Wolter52bcc12a2018-11-14 03:27:297297 return GetAudioStreamFactory()->group_id();
7298}
7299
Miyoung Shin5709ab02020-02-19 06:50:417300const std::vector<blink::mojom::FaviconURLPtr>&
7301WebContentsImpl::GetFaviconURLs() {
Mounir Lamouri7b4a1f232019-12-23 16:32:107302 return favicon_urls_;
7303}
7304
Mugdha Lakhani0a0d7862020-07-29 09:58:457305// The Mac implementation of the next two methods is in
7306// web_contents_impl_mac.mm
Avi Drissmand4d79f72020-07-30 18:35:187307#if !defined(OS_MAC)
Mugdha Lakhani0a0d7862020-07-29 09:58:457308
7309void WebContentsImpl::Resize(const gfx::Rect& new_bounds) {
7310#if defined(USE_AURA)
7311 aura::Window* window = GetNativeView();
7312 window->SetBounds(gfx::Rect(window->bounds().origin(), new_bounds.size()));
7313#elif defined(OS_ANDROID)
7314 content::RenderWidgetHostView* view = GetRenderWidgetHostView();
7315 if (view)
7316 view->SetBounds(new_bounds);
7317#endif
7318}
7319
7320gfx::Size WebContentsImpl::GetSize() {
7321#if defined(USE_AURA)
7322 aura::Window* window = GetNativeView();
7323 return window->bounds().size();
7324#elif defined(OS_ANDROID)
7325 ui::ViewAndroid* view_android = GetNativeView();
7326 return view_android->bounds().size();
7327#endif
7328}
7329
Avi Drissmand4d79f72020-07-30 18:35:187330#endif // !defined(OS_MAC)
Mugdha Lakhani0a0d7862020-07-29 09:58:457331
[email protected]f8497342013-02-05 22:15:027332BrowserPluginEmbedder* WebContentsImpl::GetBrowserPluginEmbedder() const {
[email protected]7a846df2012-09-20 19:17:397333 return browser_plugin_embedder_.get();
7334}
[email protected]8ff00d72012-10-23 19:12:217335
fsamuel60b42282015-03-10 03:29:147336void WebContentsImpl::CreateBrowserPluginEmbedderIfNecessary() {
7337 if (browser_plugin_embedder_)
7338 return;
7339 browser_plugin_embedder_.reset(BrowserPluginEmbedder::Create(this));
7340}
7341
danakja0bce4c952020-05-12 20:40:287342gfx::Size WebContentsImpl::GetSizeForMainFrame() {
7343 if (delegate_) {
7344 // The delegate has a chance to specify a size independent of the UI.
7345 gfx::Size delegate_size = delegate_->GetSizeForNewRenderView(this);
7346 if (!delegate_size.IsEmpty())
7347 return delegate_size;
7348 }
7349
7350 // Device emulation, when enabled, can specify a size independent of the UI.
7351 if (!device_emulation_size_.IsEmpty())
7352 return device_emulation_size_;
7353
7354 return GetContainerBounds().size();
[email protected]dc0fd432013-08-27 15:29:217355}
7356
[email protected]ae7eeda2014-07-04 01:53:267357void WebContentsImpl::OnFrameRemoved(RenderFrameHost* render_frame_host) {
Alexander Timin90c20c32020-08-12 15:28:327358 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7359 observer->FrameDeleted(render_frame_host);
7360 });
[email protected]9b159a52013-10-03 17:24:557361}
7362
[email protected]222f5822014-02-05 23:40:497363void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size& old_size) {
7364 if (!delegate_)
7365 return;
7366 const gfx::Size new_size = GetPreferredSize();
7367 if (new_size != old_size)
7368 delegate_->UpdatePreferredSize(this, new_size);
7369}
7370
Miyoung Shin072d4052020-07-13 07:52:447371std::unique_ptr<WebUIImpl> WebContentsImpl::CreateWebUI(
7372 RenderFrameHost* frame_host,
7373 const GURL& url) {
7374 std::unique_ptr<WebUIImpl> web_ui =
7375 std::make_unique<WebUIImpl>(this, frame_host);
Lei Zhangee3b63ad2018-06-06 23:25:317376 std::unique_ptr<WebUIController> controller(
avie865b1d2016-10-24 19:42:597377 WebUIControllerFactoryRegistry::GetInstance()
Lei Zhangee3b63ad2018-06-06 23:25:317378 ->CreateWebUIControllerForURL(web_ui.get(), url));
dbeama1b926a2015-08-31 23:17:517379 if (controller) {
Lei Zhangee3b63ad2018-06-06 23:25:317380 web_ui->SetController(std::move(controller));
dbeama1b926a2015-08-31 23:17:517381 return web_ui;
7382 }
7383
avie865b1d2016-10-24 19:42:597384 return nullptr;
dbeama1b926a2015-08-31 23:17:517385}
7386
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:417387FindRequestManager* WebContentsImpl::GetFindRequestManager() {
7388 for (auto* contents = this; contents;
paulmeyerfeafc2d2017-04-25 21:46:407389 contents = contents->GetOuterWebContents()) {
7390 if (contents->find_request_manager_)
7391 return contents->find_request_manager_.get();
7392 }
7393
7394 return nullptr;
7395}
7396
paulmeyerc0b762b2016-04-13 11:55:177397FindRequestManager* WebContentsImpl::GetOrCreateFindRequestManager() {
paulmeyerfeafc2d2017-04-25 21:46:407398 if (FindRequestManager* manager = GetFindRequestManager())
7399 return manager;
7400
Ehsan Karamad6beb2ea2018-11-25 18:15:137401 DCHECK(!browser_plugin_guest_ || GetOuterWebContents());
7402
paulmeyerfeafc2d2017-04-25 21:46:407403 // No existing FindRequestManager found, so one must be created.
7404 find_request_manager_.reset(new FindRequestManager(this));
7405
7406 // Concurrent find sessions must not overlap, so destroy any existing
7407 // FindRequestManagers in any inner WebContentses.
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:167408 for (WebContents* contents : GetWebContentsAndAllInner()) {
7409 auto* web_contents_impl = static_cast<WebContentsImpl*>(contents);
7410 if (web_contents_impl == this)
paulmeyerfeafc2d2017-04-25 21:46:407411 continue;
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:167412 if (web_contents_impl->find_request_manager_) {
7413 web_contents_impl->find_request_manager_->StopFinding(
7414 STOP_FIND_ACTION_CLEAR_SELECTION);
7415 web_contents_impl->find_request_manager_.release();
paulmeyerfeafc2d2017-04-25 21:46:407416 }
7417 }
paulmeyerc0b762b2016-04-13 11:55:177418
7419 return find_request_manager_.get();
7420}
7421
7422void WebContentsImpl::NotifyFindReply(int request_id,
7423 int number_of_matches,
7424 const gfx::Rect& selection_rect,
7425 int active_match_ordinal,
7426 bool final_update) {
Sebastien Marchandcf97ed52017-07-24 23:50:347427 if (delegate_ && !is_being_destroyed_ &&
Lukasz Anforowicze9ae3722017-09-29 17:37:387428 !GetMainFrame()->GetProcess()->FastShutdownStarted()) {
paulmeyerc0b762b2016-04-13 11:55:177429 delegate_->FindReply(this, request_id, number_of_matches, selection_rect,
7430 active_match_ordinal, final_update);
7431 }
7432}
7433
ortuno467e5792016-06-10 04:32:397434void WebContentsImpl::IncrementBluetoothConnectedDeviceCount() {
7435 // Trying to invalidate the tab state while being destroyed could result in a
7436 // use after free.
7437 if (IsBeingDestroyed()) {
7438 return;
7439 }
7440 // Notify for UI updates if the state changes.
7441 bluetooth_connected_device_count_++;
7442 if (bluetooth_connected_device_count_ == 1) {
Francois Doray66766a572019-12-17 20:56:497443 OnIsConnectedToBluetoothDeviceChanged(true);
ortuno467e5792016-06-10 04:32:397444 }
7445}
7446
7447void WebContentsImpl::DecrementBluetoothConnectedDeviceCount() {
7448 // Trying to invalidate the tab state while being destroyed could result in a
7449 // use after free.
7450 if (IsBeingDestroyed()) {
7451 return;
7452 }
7453 // Notify for UI updates if the state changes.
Lukasz Anforowicze9ae3722017-09-29 17:37:387454 DCHECK_NE(bluetooth_connected_device_count_, 0u);
ortuno467e5792016-06-10 04:32:397455 bluetooth_connected_device_count_--;
7456 if (bluetooth_connected_device_count_ == 0) {
Francois Doray66766a572019-12-17 20:56:497457 OnIsConnectedToBluetoothDeviceChanged(false);
7458 }
7459}
7460
7461void WebContentsImpl::OnIsConnectedToBluetoothDeviceChanged(
7462 bool is_connected_to_bluetooth_device) {
7463 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
Alexander Timin90c20c32020-08-12 15:28:327464 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7465 observer->OnIsConnectedToBluetoothDeviceChanged(
Francois Doray66766a572019-12-17 20:56:497466 is_connected_to_bluetooth_device);
Alexander Timin90c20c32020-08-12 15:28:327467 });
ortuno467e5792016-06-10 04:32:397468}
7469
Ovidio Henriquez76696f62020-07-08 03:06:597470void WebContentsImpl::IncrementBluetoothScanningSessionsCount() {
7471 // Trying to invalidate the tab state while being destroyed could result in a
7472 // use after free.
7473 if (IsBeingDestroyed())
7474 return;
7475
7476 // Notify for UI updates if the state changes.
7477 bluetooth_scanning_sessions_count_++;
7478 if (bluetooth_scanning_sessions_count_ == 1)
7479 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
7480}
7481
7482void WebContentsImpl::DecrementBluetoothScanningSessionsCount() {
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 DCHECK_NE(0u, bluetooth_scanning_sessions_count_);
7489 bluetooth_scanning_sessions_count_--;
7490 if (bluetooth_scanning_sessions_count_ == 0)
7491 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
7492}
7493
Reilly Grant5e7c79b22019-04-09 17:26:207494void WebContentsImpl::IncrementSerialActiveFrameCount() {
7495 // Trying to invalidate the tab state while being destroyed could result in a
7496 // use after free.
7497 if (IsBeingDestroyed())
7498 return;
7499
7500 // Notify for UI updates if the state changes.
7501 serial_active_frame_count_++;
7502 if (serial_active_frame_count_ == 1)
7503 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
7504}
7505
7506void WebContentsImpl::DecrementSerialActiveFrameCount() {
7507 // Trying to invalidate the tab state while being destroyed could result in a
7508 // use after free.
7509 if (IsBeingDestroyed())
7510 return;
7511
7512 // Notify for UI updates if the state changes.
7513 DCHECK_NE(0u, serial_active_frame_count_);
7514 serial_active_frame_count_--;
7515 if (serial_active_frame_count_ == 0)
7516 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
7517}
7518
Matt Reynoldse8c6c1f2019-11-02 09:53:537519void WebContentsImpl::IncrementHidActiveFrameCount() {
7520 // Trying to invalidate the tab state while being destroyed could result in a
7521 // use after free.
7522 if (IsBeingDestroyed())
7523 return;
7524
7525 // Notify for UI updates if the active frame count transitions from zero to
7526 // non-zero.
7527 hid_active_frame_count_++;
7528 if (hid_active_frame_count_ == 1)
7529 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
7530}
7531
7532void WebContentsImpl::DecrementHidActiveFrameCount() {
7533 // Trying to invalidate the tab state while being destroyed could result in a
7534 // use after free.
7535 if (IsBeingDestroyed())
7536 return;
7537
7538 // Notify for UI updates if the active frame count transitions from non-zero
7539 // to zero.
7540 DCHECK_NE(0u, hid_active_frame_count_);
7541 hid_active_frame_count_--;
7542 if (hid_active_frame_count_ == 0)
7543 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
7544}
7545
Marijn Kruisselbrink29051042019-08-06 22:56:557546void WebContentsImpl::IncrementNativeFileSystemHandleCount() {
7547 // Trying to invalidate the tab state while being destroyed could result in a
7548 // use after free.
7549 if (IsBeingDestroyed())
7550 return;
7551
7552 // Notify for UI updates if the state changes. Need both TYPE_TAB and TYPE_URL
7553 // to update both the tab-level usage indicator and the usage indicator in the
7554 // omnibox.
7555 native_file_system_handle_count_++;
7556 if (native_file_system_handle_count_ == 1) {
7557 NotifyNavigationStateChanged(static_cast<content::InvalidateTypes>(
7558 INVALIDATE_TYPE_TAB | INVALIDATE_TYPE_URL));
7559 }
7560}
7561
7562void WebContentsImpl::DecrementNativeFileSystemHandleCount() {
7563 // Trying to invalidate the tab state while being destroyed could result in a
7564 // use after free.
7565 if (IsBeingDestroyed())
7566 return;
7567
7568 // Notify for UI updates if the state changes. Need both TYPE_TAB and TYPE_URL
7569 // to update both the tab-level usage indicator and the usage indicator in the
7570 // omnibox.
7571 DCHECK_NE(0u, native_file_system_handle_count_);
7572 native_file_system_handle_count_--;
7573 if (native_file_system_handle_count_ == 0) {
7574 NotifyNavigationStateChanged(static_cast<content::InvalidateTypes>(
7575 INVALIDATE_TYPE_TAB | INVALIDATE_TYPE_URL));
7576 }
7577}
7578
zqzhang8ac49002017-03-16 21:51:357579void WebContentsImpl::SetHasPersistentVideo(bool has_persistent_video) {
7580 if (has_persistent_video_ == has_persistent_video)
mlamouri5cd9ae82017-02-18 11:05:097581 return;
7582
zqzhang8ac49002017-03-16 21:51:357583 has_persistent_video_ = has_persistent_video;
mlamouri5cd9ae82017-02-18 11:05:097584 NotifyPreferencesChanged();
zqzhang8ac49002017-03-16 21:51:357585 media_web_contents_observer()->RequestPersistentVideo(has_persistent_video);
mlamouri5cd9ae82017-02-18 11:05:097586}
7587
Ian Vollick5d5c37f2019-06-19 22:50:577588void WebContentsImpl::SetSpatialNavigationDisabled(bool disabled) {
7589 if (is_spatial_navigation_disabled_ == disabled)
7590 return;
7591
7592 is_spatial_navigation_disabled_ = disabled;
7593 NotifyPreferencesChanged();
7594}
7595
paulmeyerfeafc2d2017-04-25 21:46:407596void WebContentsImpl::BrowserPluginGuestWillDetach() {
7597 WebContentsImpl* outermost = GetOutermostWebContents();
7598 if (this != outermost && ContainsOrIsFocusedWebContents())
7599 outermost->SetAsFocusedWebContentsIfNecessary();
7600}
7601
Becca Hughes112832e2019-06-11 17:19:027602PictureInPictureResult WebContentsImpl::EnterPictureInPicture(
Mounir Lamouri11e9ef42018-05-22 03:10:167603 const viz::SurfaceId& surface_id,
7604 const gfx::Size& natural_size) {
François Beaufortf09e4462019-01-18 14:34:517605 return delegate_
7606 ? delegate_->EnterPictureInPicture(this, surface_id, natural_size)
Becca Hughes112832e2019-06-11 17:19:027607 : PictureInPictureResult::kNotSupported;
Mounir Lamouri11e9ef42018-05-22 03:10:167608}
7609
Mounir Lamouri6d759e12018-05-16 20:01:307610void WebContentsImpl::ExitPictureInPicture() {
7611 if (delegate_)
7612 delegate_->ExitPictureInPicture();
7613}
7614
paulmeyerc0b762b2016-04-13 11:55:177615#if defined(OS_ANDROID)
7616void WebContentsImpl::NotifyFindMatchRectsReply(
7617 int version,
7618 const std::vector<gfx::RectF>& rects,
7619 const gfx::RectF& active_rect) {
7620 if (delegate_)
7621 delegate_->FindMatchRectsReply(this, version, rects, active_rect);
7622}
7623#endif
7624
[email protected]34ff1cfc2014-08-20 06:16:057625void WebContentsImpl::SetForceDisableOverscrollContent(bool force_disable) {
7626 force_disable_overscroll_content_ = force_disable;
7627 if (view_)
7628 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
7629}
7630
Jianzhou Fengd8720c72018-01-18 03:06:307631bool WebContentsImpl::SetDeviceEmulationSize(const gfx::Size& new_size) {
7632 device_emulation_size_ = new_size;
7633 RenderWidgetHostView* rwhv = GetMainFrame()->GetView();
7634
7635 const gfx::Size current_size = rwhv->GetViewBounds().size();
7636 if (view_size_before_emulation_.IsEmpty())
7637 view_size_before_emulation_ = current_size;
7638
7639 if (current_size != new_size)
7640 rwhv->SetSize(new_size);
7641
7642 return current_size != new_size;
7643}
7644
7645void WebContentsImpl::ClearDeviceEmulationSize() {
7646 RenderWidgetHostView* rwhv = GetMainFrame()->GetView();
7647 // WebContentsView could get resized during emulation, which also resizes
7648 // RWHV. If it happens, assume user would like to keep using the size after
7649 // emulation.
7650 // TODO(jzfeng): Prohibit resizing RWHV through any other means (at least when
7651 // WebContentsView size changes).
Dmitry Gozmanc63707182018-03-06 00:09:397652 if (!view_size_before_emulation_.IsEmpty() && rwhv &&
7653 rwhv->GetViewBounds().size() == device_emulation_size_) {
Jianzhou Fengd8720c72018-01-18 03:06:307654 rwhv->SetSize(view_size_before_emulation_);
Dmitry Gozmanc63707182018-03-06 00:09:397655 }
Jianzhou Fengd8720c72018-01-18 03:06:307656 device_emulation_size_ = gfx::Size();
7657 view_size_before_emulation_ = gfx::Size();
7658}
7659
Max Morin5bc74f52018-05-09 07:00:217660ForwardingAudioStreamFactory* WebContentsImpl::GetAudioStreamFactory() {
7661 if (!audio_stream_factory_) {
7662 audio_stream_factory_.emplace(
7663 this,
Max Morinddebb972018-09-20 10:04:147664 // BrowserMainLoop::GetInstance() may be null in unit tests.
7665 BrowserMainLoop::GetInstance()
7666 ? static_cast<media::UserInputMonitorBase*>(
7667 BrowserMainLoop::GetInstance()->user_input_monitor())
7668 : nullptr,
Ken Rockot72964402019-12-06 10:40:517669 AudioStreamBrokerFactory::CreateImpl());
Max Morin5bc74f52018-05-09 07:00:217670 }
7671
7672 return &*audio_stream_factory_;
7673}
7674
dalecurtis88c240072015-12-09 02:11:187675void WebContentsImpl::MediaStartedPlaying(
billorr21c005d2016-11-17 03:57:047676 const WebContentsObserver::MediaPlayerInfo& media_info,
Mounir Lamouri0f5bdf52019-04-04 16:32:357677 const MediaPlayerId& id) {
billorr21c005d2016-11-17 03:57:047678 if (media_info.has_video)
7679 currently_playing_video_count_++;
7680
Alexander Timin90c20c32020-08-12 15:28:327681 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7682 observer->MediaStartedPlaying(media_info, id);
7683 });
dalecurtis88c240072015-12-09 02:11:187684}
7685
7686void WebContentsImpl::MediaStoppedPlaying(
billorr21c005d2016-11-17 03:57:047687 const WebContentsObserver::MediaPlayerInfo& media_info,
Mounir Lamouri0f5bdf52019-04-04 16:32:357688 const MediaPlayerId& id,
Becca Hughes220bfc102017-11-14 18:24:077689 WebContentsObserver::MediaStoppedReason reason) {
billorr21c005d2016-11-17 03:57:047690 if (media_info.has_video)
7691 currently_playing_video_count_--;
7692
Alexander Timin90c20c32020-08-12 15:28:327693 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7694 observer->MediaStoppedPlaying(media_info, id, reason);
7695 });
billorr21c005d2016-11-17 03:57:047696}
7697
Mounir Lamouri0f5bdf52019-04-04 16:32:357698void WebContentsImpl::MediaResized(const gfx::Size& size,
7699 const MediaPlayerId& id) {
peconn257951522017-06-09 18:24:597700 cached_video_sizes_[id] = size;
7701
Alexander Timin90c20c32020-08-12 15:28:327702 observers_.ForEachObserver(
7703 [&](WebContentsObserver* observer) { observer->MediaResized(size, id); });
peconn257951522017-06-09 18:24:597704}
7705
Michael Crousee75c7a42020-07-31 21:11:557706void WebContentsImpl::MediaBufferUnderflow(const MediaPlayerId& id) {
Alexander Timin90c20c32020-08-12 15:28:327707 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7708 observer->MediaBufferUnderflow(id);
7709 });
Michael Crousee75c7a42020-07-31 21:11:557710}
7711
Peter E Conneccb34c22017-09-08 09:37:587712void WebContentsImpl::MediaEffectivelyFullscreenChanged(bool is_fullscreen) {
Alexander Timin90c20c32020-08-12 15:28:327713 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7714 observer->MediaEffectivelyFullscreenChanged(is_fullscreen);
7715 });
Peter E Conneccb34c22017-09-08 09:37:587716}
7717
Peter Conn31c726a2017-08-17 11:07:347718base::Optional<gfx::Size> WebContentsImpl::GetFullscreenVideoSize() {
Mounir Lamouri0f5bdf52019-04-04 16:32:357719 base::Optional<MediaPlayerId> id =
Peter Conn31c726a2017-08-17 11:07:347720 media_web_contents_observer_->GetFullscreenVideoMediaPlayerId();
Jan Wilken Dörrie531be7ca2019-06-07 10:05:577721 if (id && base::Contains(cached_video_sizes_, id.value()))
Peter Conn31c726a2017-08-17 11:07:347722 return base::Optional<gfx::Size>(cached_video_sizes_[id.value()]);
Lei Zhang6410ec1a2019-01-31 21:38:587723 return base::nullopt;
peconn257951522017-06-09 18:24:597724}
7725
billorr21c005d2016-11-17 03:57:047726int WebContentsImpl::GetCurrentlyPlayingVideoCount() {
7727 return currently_playing_video_count_;
dalecurtis88c240072015-12-09 02:11:187728}
7729
Raymond Toye413650c2018-08-31 00:12:477730void WebContentsImpl::AudioContextPlaybackStarted(RenderFrameHost* host,
7731 int context_id) {
7732 WebContentsObserver::AudioContextId audio_context_id(host, context_id);
Alexander Timin90c20c32020-08-12 15:28:327733 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7734 observer->AudioContextPlaybackStarted(audio_context_id);
7735 });
Raymond Toye413650c2018-08-31 00:12:477736}
7737
7738void WebContentsImpl::AudioContextPlaybackStopped(RenderFrameHost* host,
7739 int context_id) {
7740 WebContentsObserver::AudioContextId audio_context_id(host, context_id);
Alexander Timin90c20c32020-08-12 15:28:327741 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7742 observer->AudioContextPlaybackStopped(audio_context_id);
7743 });
Raymond Toye413650c2018-08-31 00:12:477744}
7745
Chris Hamilton16ca64a2020-05-14 23:13:177746void WebContentsImpl::OnFrameAudioStateChanged(RenderFrameHost* host,
7747 bool is_audible) {
Alexander Timin90c20c32020-08-12 15:28:327748 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7749 observer->OnFrameAudioStateChanged(host, is_audible);
7750 });
Chris Hamilton16ca64a2020-05-14 23:13:177751}
7752
evliu7f736f02019-11-07 17:43:507753media::MediaMetricsProvider::RecordAggregateWatchTimeCallback
7754WebContentsImpl::GetRecordAggregateWatchTimeCallback() {
Becca Hughes53652442020-03-17 15:35:427755 if (!delegate_ || !delegate_->GetDelegateWeakPtr())
7756 return base::DoNothing();
7757
evliu7f736f02019-11-07 17:43:507758 return base::BindRepeating(
Becca Hughes53652442020-03-17 15:35:427759 [](base::WeakPtr<WebContentsDelegate> delegate, GURL last_committed_url,
7760 base::TimeDelta total_watch_time, base::TimeDelta time_stamp,
7761 bool has_video, bool has_audio) {
evliua283c9e2019-11-08 22:57:227762 content::MediaPlayerWatchTime watch_time(
7763 last_committed_url, last_committed_url.GetOrigin(),
7764 total_watch_time, time_stamp, has_video, has_audio);
evliu7f736f02019-11-07 17:43:507765
7766 // Save the watch time if the delegate is still alive.
7767 if (delegate)
7768 delegate->MediaWatchTimeChanged(watch_time);
7769 },
Becca Hughes53652442020-03-17 15:35:427770 delegate_->GetDelegateWeakPtr(), GetMainFrameLastCommittedURL());
evliu7f736f02019-11-07 17:43:507771}
7772
Ehsan Karamad1c631762019-05-13 23:04:017773RenderFrameHostImpl* WebContentsImpl::GetMainFrameForInnerDelegate(
7774 FrameTreeNode* frame_tree_node) {
7775 if (auto* web_contents = node_.GetInnerWebContentsInFrame(frame_tree_node))
7776 return web_contents->GetMainFrame();
7777 return nullptr;
7778}
7779
John Budorickee1c9512019-10-17 15:32:197780bool WebContentsImpl::IsFrameLowPriority(
7781 const RenderFrameHost* render_frame_host) {
7782 if (!delegate_)
7783 return false;
7784 return delegate_->IsFrameLowPriority(this, render_frame_host);
7785}
7786
Roger Tawa03ffdbd2020-01-16 18:12:547787void WebContentsImpl::IsClipboardPasteAllowed(
7788 const GURL& url,
7789 const ui::ClipboardFormatType& data_type,
7790 const std::string& data,
7791 IsClipboardPasteAllowedCallback callback) {
Dominique Fauteux-Chapleau99244382020-07-08 20:37:007792 ++suppress_unresponsive_renderer_count_;
Roger Tawa03ffdbd2020-01-16 18:12:547793 GetContentClient()->browser()->IsClipboardPasteAllowed(
Dominique Fauteux-Chapleau99244382020-07-08 20:37:007794 this, url, data_type, data,
7795 base::BindOnce(&WebContentsImpl::IsClipboardPasteAllowedWrapperCallback,
7796 weak_factory_.GetWeakPtr(), std::move(callback)));
7797}
7798
7799void WebContentsImpl::IsClipboardPasteAllowedWrapperCallback(
7800 IsClipboardPasteAllowedCallback callback,
7801 ClipboardPasteAllowed allowed) {
7802 std::move(callback).Run(allowed);
7803 --suppress_unresponsive_renderer_count_;
Roger Tawa03ffdbd2020-01-16 18:12:547804}
7805
Lan Weif81c6e7c2020-02-12 16:46:097806bool WebContentsImpl::HasSeenRecentScreenOrientationChange() {
7807 static constexpr base::TimeDelta kMaxInterval =
7808 base::TimeDelta::FromSeconds(1);
7809 base::TimeDelta delta =
7810 ui::EventTimeForNow() - last_screen_orientation_change_time_;
7811 // Return whether there is a screen orientation change happened in the recent
7812 // 1 second.
7813 return delta <= kMaxInterval;
7814}
7815
7816void WebContentsImpl::DidChangeScreenOrientation() {
7817 last_screen_orientation_change_time_ = ui::EventTimeForNow();
7818}
7819
Miyoung Shin8f2e1832020-04-27 09:00:027820bool WebContentsImpl::ShowPopupMenu(
Miyoung Shin4d947d22020-04-24 04:48:337821 RenderFrameHostImpl* render_frame_host,
Miyoung Shin8f2e1832020-04-27 09:00:027822 mojo::PendingRemote<blink::mojom::PopupMenuClient>* popup_client,
Miyoung Shin4d947d22020-04-24 04:48:337823 const gfx::Rect& bounds,
7824 int32_t item_height,
7825 double font_size,
7826 int32_t selected_item,
7827 std::vector<blink::mojom::MenuItemPtr>* menu_items,
7828 bool right_aligned,
7829 bool allow_multiple_selection) {
Alexander Timin90c20c32020-08-12 15:28:327830 for (auto& observer : observers_.observer_list()) {
Miyoung Shin8f2e1832020-04-27 09:00:027831 if (observer.ShowPopupMenu(render_frame_host, popup_client, bounds,
7832 item_height, font_size, selected_item,
7833 menu_items, right_aligned,
7834 allow_multiple_selection)) {
Miyoung Shin4d947d22020-04-24 04:48:337835 return true;
7836 }
7837 }
7838 return false;
7839}
7840
Francois Doraye6161152018-03-27 22:05:377841void WebContentsImpl::UpdateWebContentsVisibility(Visibility visibility) {
Francois Doray3f2afbd2018-04-06 19:18:187842 // Occlusion is disabled when |features::kWebContentsOcclusion| is disabled
7843 // (for power and speed impact assessment) or when
7844 // |switches::kDisableBackgroundingOccludedWindowsForTesting| is specified on
7845 // the command line (to avoid flakiness in browser tests).
7846 const bool occlusion_is_disabled =
7847 !base::FeatureList::IsEnabled(features::kWebContentsOcclusion) ||
Francois Doraye6161152018-03-27 22:05:377848 base::CommandLine::ForCurrentProcess()->HasSwitch(
7849 switches::kDisableBackgroundingOccludedWindowsForTesting);
7850 if (occlusion_is_disabled && visibility == Visibility::OCCLUDED)
7851 visibility = Visibility::VISIBLE;
7852
tapted65ff2ea72016-03-01 23:39:007853 if (!did_first_set_visible_) {
Francois Doraye6161152018-03-27 22:05:377854 if (visibility == Visibility::VISIBLE) {
7855 // A WebContents created with CreateParams::initially_hidden = false
7856 // starts with GetVisibility() == Visibility::VISIBLE even though it is
7857 // not really visible. Call WasShown() when it becomes visible for real as
7858 // the page load mechanism and some WebContentsObserver rely on that.
tapted65ff2ea72016-03-01 23:39:007859 WasShown();
Francois Dorayfe4a1772018-02-17 04:17:097860 did_first_set_visible_ = true;
tapted65ff2ea72016-03-01 23:39:007861 }
Francois Doraye6161152018-03-27 22:05:377862
7863 // Trust the initial visibility of the WebContents and do not switch it to
7864 // HIDDEN or OCCLUDED before it becomes VISIBLE for real. Doing so would
7865 // result in destroying resources that would immediately be recreated (e.g.
7866 // UpdateWebContents(HIDDEN) can be called when a WebContents is added to a
7867 // hidden window that is about to be shown).
7868
tapted65ff2ea72016-03-01 23:39:007869 return;
7870 }
Francois Doraye6161152018-03-27 22:05:377871
7872 if (visibility == visibility_)
tapted65ff2ea72016-03-01 23:39:007873 return;
7874
Collin Baker989e0882019-11-01 01:27:177875 UpdateVisibilityAndNotifyPageAndView(visibility);
tapted65ff2ea72016-03-01 23:39:007876}
7877
aelias5252baa2016-04-10 01:18:027878void WebContentsImpl::UpdateOverridingUserAgent() {
mlamouri5cd9ae82017-02-18 11:05:097879 NotifyPreferencesChanged();
aelias5252baa2016-04-10 01:18:027880}
7881
avid53461d2016-02-25 17:15:047882void WebContentsImpl::SetJavaScriptDialogManagerForTesting(
7883 JavaScriptDialogManager* dialog_manager) {
7884 dialog_manager_ = dialog_manager;
7885}
7886
Julie Jeongeun Kim7d0986172019-12-04 03:17:257887void WebContentsImpl::RemoveReceiverSet(const std::string& interface_name) {
7888 auto it = receiver_sets_.find(interface_name);
7889 if (it != receiver_sets_.end())
7890 receiver_sets_.erase(it);
rockotf62002a2016-09-15 00:08:597891}
7892
nzolghadrd87a308d2016-12-07 15:45:567893bool WebContentsImpl::AddDomainInfoToRapporSample(rappor::Sample* sample) {
nzolghadrbbffc6c2017-05-25 17:56:397894 // Here we associate this metric to the main frame URL regardless of what
7895 // caused it.
nzolghadrd87a308d2016-12-07 15:45:567896 sample->SetStringField("Domain", ::rappor::GetDomainAndRegistrySampleFromGURL(
7897 GetLastCommittedURL()));
nzolghadrd87a308d2016-12-07 15:45:567898 return true;
7899}
7900
falken52a56e32016-12-08 05:02:407901void WebContentsImpl::ShowInsecureLocalhostWarningIfNeeded() {
7902 bool allow_localhost = base::CommandLine::ForCurrentProcess()->HasSwitch(
7903 switches::kAllowInsecureLocalhost);
7904 if (!allow_localhost)
7905 return;
7906
7907 content::NavigationEntry* entry = GetController().GetLastCommittedEntry();
Rob Wuf79b3ba2018-01-14 01:54:317908 if (!entry || !net::IsLocalhost(entry->GetURL()))
falken52a56e32016-12-08 05:02:407909 return;
7910
7911 content::SSLStatus ssl_status = entry->GetSSL();
Matt Mueller936511442019-09-03 18:15:127912 if (!net::IsCertStatusError(ssl_status.cert_status))
falken52a56e32016-12-08 05:02:407913 return;
7914
7915 GetMainFrame()->AddMessageToConsole(
Abhijeet Kandalkara5928a0a2019-03-13 05:04:427916 blink::mojom::ConsoleMessageLevel::kWarning,
falken52a56e32016-12-08 05:02:407917 base::StringPrintf("This site does not have a valid SSL "
7918 "certificate! Without SSL, your site's and "
7919 "visitors' data is vulnerable to theft and "
7920 "tampering. Get a valid SSL certificate before"
7921 " releasing your website to the public."));
7922}
7923
ekaramadf6750aa2017-06-06 18:29:427924bool WebContentsImpl::IsShowingContextMenuOnPage() const {
7925 return showing_context_menu_;
7926}
7927
Min Qina904f3302018-02-13 23:33:347928download::DownloadUrlParameters::RequestHeadersType
7929WebContentsImpl::ParseDownloadHeaders(const std::string& headers) {
7930 download::DownloadUrlParameters::RequestHeadersType request_headers;
Megan Jablonski2f6a4c52017-07-10 23:01:257931 for (const base::StringPiece& key_value : base::SplitStringPiece(
7932 headers, "\r\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) {
7933 std::vector<std::string> pair = base::SplitString(
7934 key_value, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
7935 if (2ul == pair.size())
7936 request_headers.push_back(make_pair(pair[0], pair[1]));
7937 }
7938 return request_headers;
7939}
7940
lukasza6f8ac622017-06-06 03:10:207941void WebContentsImpl::SetOpenerForNewContents(FrameTreeNode* opener,
7942 bool opener_suppressed) {
7943 if (opener) {
7944 FrameTreeNode* new_root = GetFrameTree()->root();
7945
7946 // For the "original opener", track the opener's main frame instead, because
7947 // if the opener is a subframe, the opener tracking could be easily bypassed
7948 // by spawning from a subframe and deleting the subframe.
7949 // https://crbug.com/705316
7950 new_root->SetOriginalOpener(opener->frame_tree()->root());
7951
7952 if (!opener_suppressed) {
7953 new_root->SetOpener(opener);
7954 created_with_opener_ = true;
7955 }
7956 }
7957}
7958
Mounir Lamouri0f5bdf52019-04-04 16:32:357959void WebContentsImpl::MediaMutedStatusChanged(const MediaPlayerId& id,
7960 bool muted) {
Alexander Timin90c20c32020-08-12 15:28:327961 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7962 observer->MediaMutedStatusChanged(id, muted);
7963 });
Becca Hughes9f6fd4b82017-06-15 10:01:407964}
7965
EhsanK2075c7e2017-08-21 02:42:397966void WebContentsImpl::SetVisibilityForChildViews(bool visible) {
7967 GetMainFrame()->SetVisibilityForChildViews(visible);
7968}
7969
Alison Maher7f366dc62020-03-03 19:46:007970void WebContentsImpl::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) {
7971 DCHECK(native_theme_observer_.IsObserving(observed_theme));
7972
7973 bool using_dark_colors = observed_theme->ShouldUseDarkColors();
7974 ui::NativeTheme::PreferredColorScheme preferred_color_scheme =
7975 observed_theme->GetPreferredColorScheme();
7976 bool preferences_changed = false;
7977
7978 if (using_dark_colors_ != using_dark_colors) {
7979 using_dark_colors_ = using_dark_colors;
7980 preferences_changed = true;
7981 }
7982 if (preferred_color_scheme_ != preferred_color_scheme) {
7983 preferred_color_scheme_ = preferred_color_scheme;
7984 preferences_changed = true;
7985 }
7986
7987 if (preferences_changed)
7988 NotifyPreferencesChanged();
7989}
7990
Dave Tapuska58a099e2020-06-08 21:48:407991blink::mojom::FrameWidgetInputHandler*
7992WebContentsImpl::GetFocusedFrameWidgetInputHandler() {
7993 auto* focused_render_widget_host =
7994 GetFocusedRenderWidgetHost(GetMainFrame()->GetRenderWidgetHost());
7995 if (!focused_render_widget_host)
Dave Tapuskae782bea2019-07-09 16:21:517996 return nullptr;
Dave Tapuska58a099e2020-06-08 21:48:407997 return focused_render_widget_host->GetFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:517998}
7999
Alexander Timine3ec4192020-04-20 16:39:408000ukm::SourceId WebContentsImpl::GetCurrentPageUkmSourceId() {
8001 return GetMainFrame()->GetPageUkmSourceId();
8002}
8003
Yuzu Saijo232076f2020-05-29 07:14:028004std::set<RenderViewHostImpl*>
8005WebContentsImpl::GetRenderViewHostsIncludingBackForwardCached() {
8006 std::set<RenderViewHostImpl*> render_view_hosts;
8007
8008 // Add RenderViewHostImpls outside of BackForwardCache.
8009 for (auto& render_view_host : frame_tree_.render_view_hosts()) {
8010 render_view_hosts.insert(render_view_host.second);
8011 }
8012
8013 // Add RenderViewHostImpls in BackForwardCache.
8014 const auto& entries = GetController().GetBackForwardCache().GetEntries();
8015 for (const auto& entry : entries) {
8016 std::set<RenderViewHostImpl*> bfcached_hosts = entry->render_view_hosts;
8017 render_view_hosts.insert(bfcached_hosts.begin(), bfcached_hosts.end());
8018 }
8019
8020 return render_view_hosts;
8021}
8022
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:508023void WebContentsImpl::RenderFrameHostStateChanged(
8024 RenderFrameHost* render_frame_host,
8025 LifecycleState old_state,
8026 LifecycleState new_state) {
8027 if (render_frame_host->GetParent())
8028 return;
8029
8030 if (old_state == LifecycleState::kActive &&
8031 new_state != LifecycleState::kActive) {
8032 // TODO(sreejakshetty): Remove this reset when ColorChooser becomes
8033 // per-frame.
8034 // Close the color chooser popup when RenderFrameHost changes state from
8035 // kActive.
8036 color_chooser_.reset();
8037 }
8038}
8039
[email protected]8ff00d72012-10-23 19:12:218040} // namespace content