blob: fb9bdd764722d9ff7588f5c64997b16919b1f311 [file] [log] [blame]
[email protected]91854cd2012-01-10 19:43:571// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
[email protected]93ddb3c2012-04-11 21:44:295#include "content/browser/web_contents/web_contents_impl.h"
[email protected]39526562011-02-05 03:41:516
avib7348942015-12-25 20:57:107#include <stddef.h>
8
Avi Drissman33972942020-06-19 14:16:019#include <algorithm>
w.shackleton49bcd392016-01-06 17:38:2210#include <cmath>
Alexander Timin5fdeff22020-09-08 09:20:3711#include <memory>
[email protected]2bb171882012-03-07 02:09:4612#include <utility>
rkaplowe56a52032017-02-07 00:14:5413#include <vector>
[email protected]b75b8292010-10-01 07:28:2514
Sebastien Marchandf8cbfab2019-01-25 16:02:3015#include "base/bind.h"
[email protected]36fb2c7c2011-04-04 15:49:0816#include "base/command_line.h"
Avi Drissman33972942020-06-19 14:16:0117#include "base/containers/flat_set.h"
creisfafed882016-07-29 00:03:0918#include "base/debug/dump_without_crashing.h"
zqzhang181047e62016-07-01 13:37:1719#include "base/feature_list.h"
Marijn Kruisselbrink46fa4bd2019-07-11 18:15:4720#include "base/files/file_path.h"
[email protected]cbb1ef592013-06-05 19:49:4621#include "base/lazy_instance.h"
skyostil95082a62015-06-05 19:53:0722#include "base/location.h"
[email protected]6d636e62013-07-31 03:15:5623#include "base/logging.h"
avib7348942015-12-25 20:57:1024#include "base/macros.h"
fdorayba121422016-12-23 19:51:4825#include "base/memory/ptr_util.h"
dmazzonid95ae842016-04-12 21:17:3926#include "base/memory/ref_counted.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:2027#include "base/metrics/field_trial.h"
asvitkine8d51e9d2016-09-02 23:55:4328#include "base/metrics/histogram_macros.h"
bratell0a7406f2017-03-28 07:46:3729#include "base/metrics/user_metrics.h"
Avi Drissman4891b852018-09-25 18:12:5830#include "base/no_destructor.h"
Carlos Caballero1215f882019-10-29 15:58:4331#include "base/optional.h"
[email protected]04cbd3d2013-12-04 04:58:2032#include "base/process/process.h"
skyostil95082a62015-06-05 19:53:0733#include "base/single_thread_task_runner.h"
Arthur Sonzogni929d29f2018-09-17 14:19:4434#include "base/stl_util.h"
[email protected]348fbaac2013-06-11 06:31:5135#include "base/strings/string16.h"
36#include "base/strings/string_number_conversions.h"
Avi Drissman4891b852018-09-25 18:12:5837#include "base/strings/string_split.h"
[email protected]348fbaac2013-06-11 06:31:5138#include "base/strings/string_util.h"
[email protected]74ebfb12013-06-07 20:48:0039#include "base/strings/utf_string_conversions.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:2040#include "base/system/sys_info.h"
gab30f26df2016-05-11 19:37:5541#include "base/threading/thread_task_runner_handle.h"
[email protected]a43858f2013-06-28 15:18:3742#include "base/time/time.h"
Alexander Timin5fdeff22020-09-08 09:20:3743#include "base/trace_event/optional_trace_event.h"
44#include "base/trace_event/trace_conversion_helper.h"
ssid3e765612015-01-28 04:03:4245#include "base/trace_event/trace_event.h"
Alexander Timin5fdeff22020-09-08 09:20:3746#include "base/trace_event/traced_value.h"
avib7348942015-12-25 20:57:1047#include "build/build_config.h"
Hidehiko Abe7c68f582020-09-03 15:47:2548#include "build/chromeos_buildflags.h"
Min Qinda0ed2062018-02-23 22:00:5349#include "components/download/public/common/download_stats.h"
nzolghadrd87a308d2016-12-07 15:45:5650#include "components/rappor/public/rappor_utils.h"
rsleevi24f64dc22015-08-07 21:39:2151#include "components/url_formatter/url_formatter.h"
Abigail Kleinaa898742019-11-01 02:31:2552#include "content/browser/accessibility/accessibility_event_recorder.h"
James Wallace-Leeeafc94cb92018-07-23 21:35:0953#include "content/browser/accessibility/accessibility_tree_formatter_blink.h"
jamescookda2505812015-03-20 18:01:1854#include "content/browser/bad_message.h"
Max Morinddebb972018-09-20 10:04:1455#include "content/browser/browser_main_loop.h"
[email protected]7a846df2012-09-20 19:17:3956#include "content/browser/browser_plugin/browser_plugin_embedder.h"
57#include "content/browser/browser_plugin/browser_plugin_guest.h"
[email protected]b9535422012-02-09 01:47:5958#include "content/browser/child_process_security_policy_impl.h"
John Delaney732721e92020-02-07 23:11:2759#include "content/browser/conversions/conversion_host.h"
Pavel Feldman3c1842b2017-08-02 05:00:1660#include "content/browser/devtools/protocol/page_handler.h"
dgozmanf00c4f72016-10-19 17:45:1561#include "content/browser/devtools/render_frame_devtools_agent_host.h"
Becca Hughes3b5a43482018-07-17 22:31:5562#include "content/browser/display_cutout/display_cutout_host_impl.h"
[email protected]5f2aa722013-08-07 16:59:4163#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
[email protected]1ea3c792012-04-17 01:25:0464#include "content/browser/dom_storage/session_storage_namespace_impl.h"
[email protected]aa4f3972012-03-01 18:12:1265#include "content/browser/download/mhtml_generation_manager.h"
[email protected]a53209b2012-01-20 16:48:1666#include "content/browser/download/save_package.h"
paulmeyerc0b762b2016-04-13 11:55:1767#include "content/browser/find_request_manager.h"
Kenneth Russell954ed9ce2018-04-12 23:07:0168#include "content/browser/gpu/gpu_data_manager_impl.h"
mlamouriefdca9d2014-09-16 16:55:4069#include "content/browser/manifest/manifest_manager_host.h"
Max Morin5bc74f52018-05-09 07:00:2170#include "content/browser/media/audio_stream_broker.h"
dalecurtisbc6572e12014-09-12 19:22:3071#include "content/browser/media/audio_stream_monitor.h"
miu50f97892014-09-22 22:49:5272#include "content/browser/media/capture/web_contents_audio_muter.h"
dalecurtis88c240072015-12-09 02:11:1873#include "content/browser/media/media_web_contents_observer.h"
zqzhang1adf3cb2016-11-01 11:26:4574#include "content/browser/media/session/media_session_impl.h"
Mike Wassermandabad612020-08-13 04:26:2775#include "content/browser/permissions/permission_controller_impl.h"
Yuzu Saijoa11069a2020-04-22 10:56:5576#include "content/browser/plugin_content_origin_allowlist.h"
Kevin McNee94ea52f52020-06-23 17:42:0677#include "content/browser/portal/portal.h"
Tal Pressman5dcd2382020-08-26 07:13:0578#include "content/browser/renderer_host/agent_scheduling_group_host.h"
danakje34636e2020-09-15 22:15:0079#include "content/browser/renderer_host/cross_process_frame_connector.h"
David Black9cca3592019-11-06 23:02:2280#include "content/browser/renderer_host/frame_token_message_queue.h"
danakje34636e2020-09-15 22:15:0081#include "content/browser/renderer_host/frame_tree_node.h"
82#include "content/browser/renderer_host/navigation_entry_impl.h"
83#include "content/browser/renderer_host/navigation_request.h"
84#include "content/browser/renderer_host/navigator.h"
85#include "content/browser/renderer_host/render_frame_host_impl.h"
86#include "content/browser/renderer_host/render_frame_proxy_host.h"
[email protected]f3b1a082011-11-18 00:34:3087#include "content/browser/renderer_host/render_process_host_impl.h"
[email protected]21161032014-05-05 16:56:5088#include "content/browser/renderer_host/render_view_host_delegate_view.h"
[email protected]b3c41c0b2012-03-06 15:48:3289#include "content/browser/renderer_host/render_view_host_impl.h"
[email protected]bafe6cd2012-05-23 23:09:5090#include "content/browser/renderer_host/render_widget_host_impl.h"
kenrb2a565f82015-09-02 20:24:5991#include "content/browser/renderer_host/render_widget_host_input_event_router.h"
[email protected]cfd80b02014-05-01 17:46:4892#include "content/browser/renderer_host/render_widget_host_view_base.h"
Ken Buchanandaef006b2017-08-17 18:32:1593#include "content/browser/renderer_host/render_widget_host_view_child_frame.h"
ekaramadadd882292016-06-08 15:22:5694#include "content/browser/renderer_host/text_input_manager.h"
Mike Wassermanb213b9352020-04-16 00:32:3495#include "content/browser/screen_enumeration/screen_change_monitor.h"
leon.han552e9de2017-02-09 14:37:3096#include "content/browser/screen_orientation/screen_orientation_provider.h"
[email protected]b6583592012-01-25 19:52:3397#include "content/browser/site_instance_impl.h"
Charlie Reis96077362019-07-04 00:34:0498#include "content/browser/web_contents/javascript_dialog_navigation_deferrer.h"
lfgc740d4b22016-04-15 16:45:3399#include "content/browser/web_contents/web_contents_view_child_frame.h"
Tsuyoshi Horob0d8d902020-03-12 00:09:39100#include "content/browser/web_package/save_as_web_bundle_job.h"
[email protected]86a0a6e2013-01-28 06:33:03101#include "content/browser/webui/web_ui_controller_factory_registry.h"
[email protected]d2353452012-01-19 19:53:56102#include "content/browser/webui/web_ui_impl.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20103#include "content/common/content_switches_internal.h"
Paul Meyer0c58c3712016-11-17 22:59:51104#include "content/common/drag_messages.h"
[email protected]f114fa42013-12-06 17:06:44105#include "content/common/frame_messages.h"
[email protected]1f3fc1d2014-04-03 14:50:17106#include "content/common/input_messages.h"
lfgdb5c4ed2016-03-04 23:09:07107#include "content/common/page_messages.h"
nasko34634672016-07-29 18:46:06108#include "content/common/page_state_serialization.h"
rockot5c478a72016-09-28 23:14:18109#include "content/common/render_message_filter.mojom.h"
[email protected]2c5569662011-03-22 20:45:02110#include "content/common/view_messages.h"
Albert J. Wong3c93c182018-09-27 17:29:43111#include "content/common/widget_messages.h"
Abigail Kleinabb428332019-09-13 18:26:21112#include "content/public/browser/accessibility_tree_formatter.h"
[email protected]31a71eaf2014-03-13 01:47:36113#include "content/public/browser/ax_event_notification_details.h"
[email protected]ccb797302011-12-15 16:55:11114#include "content/public/browser/browser_context.h"
Eric Seckler8652dcd52018-09-20 10:42:28115#include "content/public/browser/browser_task_traits.h"
Gabriel Charette790754c2018-03-16 21:32:59116#include "content/public/browser/browser_thread.h"
[email protected]87f3c082011-10-19 18:07:44117#include "content/public/browser/content_browser_client.h"
Lukasz Anforowicz8c4446dc2020-03-11 22:16:42118#include "content/public/browser/context_menu_params.h"
Ken Rockotce010f02019-12-12 23:32:32119#include "content/public/browser/device_service.h"
[email protected]e582fdd2011-12-20 16:48:17120#include "content/public/browser/download_manager.h"
Kent Tamura512a27e2018-10-04 00:49:32121#include "content/public/browser/file_select_listener.h"
ekaramada110f642016-12-21 19:47:28122#include "content/public/browser/focused_node_details.h"
Danyao Wanga78f3dd22020-03-05 05:31:27123#include "content/public/browser/global_routing_id.h"
[email protected]d9083482012-01-06 00:38:46124#include "content/public/browser/invalidate_type.h"
[email protected]71a88bb2013-02-01 22:05:15125#include "content/public/browser/javascript_dialog_manager.h"
skyf65d9bb2017-03-24 02:26:39126#include "content/public/browser/keyboard_event_processing_result.h"
[email protected]09d31d52012-03-11 22:30:27127#include "content/public/browser/load_notification_details.h"
[email protected]5b96836f2011-12-22 07:39:00128#include "content/public/browser/navigation_details.h"
[email protected]375fa1b2012-05-22 22:05:37129#include "content/public/browser/notification_details.h"
[email protected]be2510c02012-05-28 14:52:14130#include "content/public/browser/notification_service.h"
scottmg011d96e32016-06-29 19:15:08131#include "content/public/browser/notification_types.h"
[email protected]95640212014-07-26 18:14:30132#include "content/public/browser/render_widget_host_iterator.h"
Lukasz Anforowicze1b954d92017-10-30 21:28:06133#include "content/public/browser/restore_type.h"
estark5ea80e52015-06-19 18:43:12134#include "content/public/browser/security_style_explanations.h"
falken52a56e32016-12-08 05:02:40135#include "content/public/browser/ssl_status.h"
[email protected]4c3a23582012-08-18 08:54:34136#include "content/public/browser/storage_partition.h"
[email protected]674bc592011-12-20 23:00:42137#include "content/public/browser/web_contents_delegate.h"
Julie Jeongeun Kim7d0986172019-12-04 03:17:25138#include "content/public/browser/web_contents_receiver_set.h"
Lei Zhangee3b63ad2018-06-06 23:25:31139#include "content/public/browser/web_ui_controller.h"
[email protected]e091df82011-10-11 18:13:21140#include "content/public/common/bindings_policy.h"
alexmosc9e76ec2016-05-16 22:59:37141#include "content/public/common/child_process_host.h"
Hans Wennborg5ffd1392019-10-16 11:00:02142#include "content/public/common/content_client.h"
[email protected]54087fe2011-10-28 22:02:48143#include "content/public/common/content_constants.h"
Francois Doray3f2afbd2018-04-06 19:18:18144#include "content/public/common/content_features.h"
[email protected]64d69de42012-02-06 00:19:54145#include "content/public/common/content_switches.h"
Lukasz Anforowicze1b954d92017-10-30 21:28:06146#include "content/public/common/page_state.h"
Leon Han963dc182018-11-06 05:41:48147#include "content/public/common/referrer_type_converters.h"
[email protected]04cbd3d2013-12-04 04:58:20148#include "content/public/common/result_codes.h"
[email protected]f16cc6782013-12-16 23:42:57149#include "content/public/common/url_utils.h"
danakjffc8baf2019-10-10 23:49:42150#include "content/public/common/use_zoom_for_dsf_policy.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20151#include "media/base/media_switches.h"
Max Morinddebb972018-09-20 10:04:14152#include "media/base/user_input_monitor.h"
wjmaclean64951902016-04-29 20:59:12153#include "net/base/url_util.h"
[email protected]8bfc8272013-09-09 20:10:53154#include "net/http/http_cache.h"
155#include "net/http/http_transaction_factory.h"
David Van Clevef99881632020-07-16 19:41:13156#include "net/http/http_util.h"
rhalavati0fbaeef32017-06-01 15:56:30157#include "net/traffic_annotation/network_traffic_annotation.h"
Scott Violet02e38b92018-03-27 23:42:14158#include "ppapi/buildflags/buildflags.h"
Mounir Lamourifd9dcefa2017-07-06 10:26:55159#include "services/metrics/public/cpp/ukm_recorder.h"
John Abd-El-Malekb175a612018-12-03 20:11:58160#include "services/network/public/cpp/features.h"
arthursonzognib93a4472020-04-10 07:38:00161#include "services/network/public/cpp/web_sandbox_flags.h"
162#include "services/network/public/mojom/web_sandbox_flags.mojom.h"
rockot734fb662016-10-15 16:41:30163#include "services/service_manager/public/cpp/interface_provider.h"
Becca Hughes6daf5662018-06-27 16:50:54164#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
Blink Reformata30d4232018-04-07 15:31:06165#include "third_party/blink/public/common/mime_util/mime_util.h"
danakj938b37a62019-09-24 18:35:54166#include "third_party/blink/public/common/page/page_zoom.h"
Sergio Villar Senin9d9d4f52019-10-15 10:57:57167#include "third_party/blink/public/common/security/security_style.h"
Gyuyoung Kim1ac4ca782020-09-11 03:32:51168#include "third_party/blink/public/common/web_preferences/web_preferences.h"
Abhijeet Kandalkarde7348e2020-01-13 06:06:54169#include "third_party/blink/public/mojom/frame/frame.mojom.h"
Dave Tapuskaa4189512019-10-15 20:27:34170#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
Takuto Ikutaaa3b796c2019-02-06 02:54:56171#include "third_party/blink/public/mojom/loader/pause_subresource_loading_handle.mojom.h"
Antonio Gomes0d42960a2019-06-05 12:35:51172#include "third_party/blink/public/mojom/mediastream/media_stream.mojom-shared.h"
halton.huoca2eabd2015-07-06 08:17:40173#include "third_party/skia/include/core/SkBitmap.h"
dmazzonid95ae842016-04-12 21:17:39174#include "ui/accessibility/ax_tree_combiner.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20175#include "ui/base/device_form_factor.h"
Mugdha Lakhani0a0d7862020-07-29 09:58:45176#if defined(USE_AURA)
177#include "ui/aura/window.h"
178#endif
[email protected]a08412b62012-05-29 21:28:56179#include "ui/base/layout.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20180#include "ui/base/ui_base_features.h"
181#include "ui/base/ui_base_switches.h"
182#include "ui/display/screen.h"
Daniel Cheng90196c82018-04-25 21:49:14183#include "ui/events/base_event_utils.h"
chongz4a9751942016-08-17 17:49:39184#include "ui/events/blink/web_input_event_traits.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20185#include "ui/gfx/animation/animation.h"
[email protected]66bd5512012-08-01 02:02:52186#include "ui/gl/gl_switches.h"
[email protected]3c733bde2010-12-21 19:56:31187
ekaramada110f642016-12-21 19:47:28188#if defined(OS_WIN)
189#include "content/browser/renderer_host/dip_util.h"
190#include "ui/gfx/geometry/dip_util.h"
191#endif
192
[email protected]583418cc2013-01-17 14:01:10193#if defined(OS_ANDROID)
mfomitchev2b8b066a2016-01-28 19:23:15194#include "content/browser/android/date_time_chooser_android.h"
sammcf5f1b0f2016-09-20 23:05:11195#include "content/browser/android/java_interfaces_impl.h"
Leon Hanccb985f2019-08-26 02:43:24196#include "content/browser/android/nfc_host.h"
[email protected]155c7f22013-12-09 17:07:18197#include "content/browser/web_contents/web_contents_android.h"
Ke He31d0bb02018-02-24 07:16:24198#include "services/device/public/mojom/nfc.mojom.h"
Mugdha Lakhani0a0d7862020-07-29 09:58:45199#include "ui/android/view_android.h"
mcnee336ea2c2017-05-23 22:50:59200#else // !OS_ANDROID
201#include "content/browser/host_zoom_map_impl.h"
mfomitchev2b8b066a2016-01-28 19:23:15202#endif // OS_ANDROID
[email protected]583418cc2013-01-17 14:01:10203
brettw4b461082016-11-19 18:55:16204#if BUILDFLAG(ENABLE_PLUGINS)
zqzhang181047e62016-07-01 13:37:17205#include "content/browser/media/session/pepper_playback_observer.h"
Lei Zhangebcc6302018-01-12 19:46:45206#endif
zqzhang181047e62016-07-01 13:37:17207
[email protected]8ff00d72012-10-23 19:12:21208namespace content {
Abigail Kleinaa898742019-11-01 02:31:25209
210using AccessibilityEventCallback =
211 base::RepeatingCallback<void(const std::string&)>;
212
[email protected]420ae012009-04-24 05:16:32213namespace {
214
[email protected]960b0372014-05-19 18:01:00215const int kMinimumDelayBetweenLoadingUpdatesMS = 100;
[email protected]82114f52012-03-20 22:53:41216const char kDotGoogleDotCom[] = ".google.com";
[email protected]ca406032011-07-19 21:53:05217
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:50218using LifecycleState = RenderFrameHostImpl::LifecycleState;
219
Alexander Timin33bd754c02020-03-10 22:50:18220// TODO(crbug.com/1059903): Clean up after the initial investigation.
221constexpr base::Feature kCheckWebContentsAccessFromNonCurrentFrame{
222 "CheckWebContentsAccessFromNonCurrentFrame",
223 base::FEATURE_DISABLED_BY_DEFAULT};
224
Avi Drissmana9114822018-03-23 18:25:55225base::LazyInstance<std::vector<
226 WebContentsImpl::FriendWrapper::CreatedCallback>>::DestructorAtExit
227 g_created_callbacks = LAZY_INSTANCE_INITIALIZER;
[email protected]cbb1ef592013-06-05 19:49:46228
dcheng57e39e22016-01-21 00:25:38229bool HasMatchingProcess(FrameTree* tree, int render_process_id) {
230 for (FrameTreeNode* node : tree->Nodes()) {
231 if (node->current_frame_host()->GetProcess()->GetID() == render_process_id)
232 return true;
alexmos4cf2aa32015-07-15 23:40:43233 }
dcheng57e39e22016-01-21 00:25:38234 return false;
[email protected]95640212014-07-26 18:14:30235}
236
kenrb19221852016-04-29 17:21:40237bool HasMatchingWidgetHost(FrameTree* tree, RenderWidgetHost* host) {
238 // This method scans the frame tree rather than checking whether
239 // host->delegate() == this, which allows it to return false when the host
240 // for a frame that is pending or pending deletion.
241 if (!host)
242 return false;
243
244 for (FrameTreeNode* node : tree->Nodes()) {
245 if (node->current_frame_host()->GetRenderWidgetHost() == host)
246 return true;
247 }
248 return false;
249}
250
dmazzonif8a31042016-12-03 00:52:13251void UpdateAccessibilityModeOnFrame(RenderFrameHost* frame_host) {
252 static_cast<RenderFrameHostImpl*>(frame_host)->UpdateAccessibilityMode();
[email protected]95640212014-07-26 18:14:30253}
254
dtseng0dd3fa12015-07-22 19:00:52255void ResetAccessibility(RenderFrameHost* rfh) {
256 static_cast<RenderFrameHostImpl*>(rfh)->AccessibilityReset();
257}
258
Ian Clelland5cbaaf82017-11-27 22:00:03259RenderFrameHostImpl* FindOpenerRFH(const WebContents::CreateParams& params) {
260 RenderFrameHostImpl* opener_rfh = nullptr;
alexmose201c7cd2015-06-10 17:14:21261 if (params.opener_render_frame_id != MSG_ROUTING_NONE) {
Ian Clelland5cbaaf82017-11-27 22:00:03262 opener_rfh = RenderFrameHostImpl::FromID(params.opener_render_process_id,
263 params.opener_render_frame_id);
alexmose201c7cd2015-06-10 17:14:21264 }
Ian Clelland5cbaaf82017-11-27 22:00:03265 return opener_rfh;
lukasza6f8ac622017-06-06 03:10:20266}
267
Dominick Ng37a15052018-07-17 23:56:35268// Returns |true| if |type| is the kind of user input that should trigger the
269// user interaction observers.
270bool IsUserInteractionInputType(blink::WebInputEvent::Type type) {
271 // Ideally, this list would be based more off of
272 // https://whatwg.org/C/interaction.html#triggered-by-user-activation.
Dave Tapuska347d60a2020-04-21 23:55:47273 return type == blink::WebInputEvent::Type::kMouseDown ||
274 type == blink::WebInputEvent::Type::kGestureScrollBegin ||
275 type == blink::WebInputEvent::Type::kTouchStart ||
276 type == blink::WebInputEvent::Type::kRawKeyDown;
Dominick Ng37a15052018-07-17 23:56:35277}
278
Pavel Feldman3c1842b2017-08-02 05:00:16279// Ensures that OnDialogClosed is only called once.
280class CloseDialogCallbackWrapper
281 : public base::RefCountedThreadSafe<CloseDialogCallbackWrapper> {
282 public:
Avi Drissmane04d3992017-10-05 15:11:36283 using CloseCallback =
284 base::OnceCallback<void(bool, bool, const base::string16&)>;
285
286 explicit CloseDialogCallbackWrapper(CloseCallback callback)
287 : callback_(std::move(callback)) {}
Pavel Feldman3c1842b2017-08-02 05:00:16288
289 void Run(bool dialog_was_suppressed,
290 bool success,
291 const base::string16& user_input) {
Avi Drissmane04d3992017-10-05 15:11:36292 if (callback_.is_null())
Pavel Feldman3c1842b2017-08-02 05:00:16293 return;
Avi Drissmane04d3992017-10-05 15:11:36294 std::move(callback_).Run(dialog_was_suppressed, success, user_input);
Pavel Feldman3c1842b2017-08-02 05:00:16295 }
296
297 private:
298 friend class base::RefCountedThreadSafe<CloseDialogCallbackWrapper>;
Fergal Daly55b6d722020-09-11 07:56:33299 ~CloseDialogCallbackWrapper() = default;
Avi Drissmane04d3992017-10-05 15:11:36300
301 CloseCallback callback_;
Pavel Feldman3c1842b2017-08-02 05:00:16302};
303
Arthur Sonzogni929d29f2018-09-17 14:19:44304bool FrameCompareDepth(RenderFrameHostImpl* a, RenderFrameHostImpl* b) {
305 return a->frame_tree_node()->depth() < b->frame_tree_node()->depth();
306}
307
Raymes Khoury58373df2019-08-06 06:29:20308bool AreValidRegisterProtocolHandlerArguments(const std::string& protocol,
309 const GURL& url,
310 const url::Origin& origin) {
311 ChildProcessSecurityPolicyImpl* policy =
312 ChildProcessSecurityPolicyImpl::GetInstance();
313 if (policy->IsPseudoScheme(protocol))
314 return false;
315
316 url::Origin url_origin = url::Origin::Create(url);
317 if (url_origin.opaque())
318 return false;
319
320 if (!url_origin.IsSameOriginWith(origin))
321 return false;
322
323 return true;
324}
325
yilkal796e89e2019-10-02 23:58:28326void RecordMaxFrameCountUMA(size_t max_frame_count) {
327 UMA_HISTOGRAM_COUNTS_10000("Navigation.MainFrame.MaxFrameCount",
328 max_frame_count);
329}
330
Jeremy Roman03ce13ce2020-05-29 22:16:57331// Returns whether the condition provided applies to any inner contents.
332// This check is not recursive (however, the predicate provided may itself
333// recurse each contents' own inner contents).
334//
335// For example, if this is used to aggregate state from inner contents to outer
336// contents, then that propagation will gather transitive descendants without
337// need for this helper to do so. In fact, in such cases recursing on inner
338// contents here would make that operation quadratic rather than linear.
339template <typename Functor>
340bool AnyInnerWebContents(WebContents* web_contents, const Functor& f) {
341 const auto& inner_contents = web_contents->GetInnerWebContents();
342 return std::any_of(inner_contents.begin(), inner_contents.end(), f);
343}
344
Xuehui Xieb2300ae42020-06-09 20:25:05345std::vector<RenderFrameHost*> GetAllFramesImpl(FrameTree& frame_tree,
346 bool include_pending) {
347 std::vector<RenderFrameHost*> frame_hosts;
348 for (FrameTreeNode* node : frame_tree.Nodes()) {
349 frame_hosts.push_back(node->current_frame_host());
350 if (include_pending) {
351 RenderFrameHostImpl* pending_frame_host =
352 node->render_manager()->speculative_frame_host();
353 if (pending_frame_host)
354 frame_hosts.push_back(pending_frame_host);
355 }
356 }
357 return frame_hosts;
358}
359
360int SendToAllFramesImpl(FrameTree& frame_tree,
361 bool include_pending,
362 IPC::Message* message) {
363 int number_of_messages = 0;
364 std::vector<RenderFrameHost*> frame_hosts =
365 GetAllFramesImpl(frame_tree, include_pending);
366 for (RenderFrameHost* rfh : frame_hosts) {
367 if (!rfh->IsRenderFrameLive())
368 continue;
369
370 ++number_of_messages;
371 IPC::Message* message_copy = new IPC::Message(*message);
372 message_copy->set_routing_id(rfh->GetRoutingID());
373 rfh->Send(message_copy);
374 }
375 delete message;
376 return number_of_messages;
377}
378
Avi Drissman33972942020-06-19 14:16:01379// Returns the set of all WebContentses that are reachable from |web_contents|
380// by applying some combination of WebContents::GetOriginalOpener() and
381// WebContents::GetOuterWebContents(). The |web_contents| parameter will be
382// included in the returned set.
383base::flat_set<WebContentsImpl*> GetAllOpeningWebContents(
384 WebContentsImpl* web_contents) {
385 base::flat_set<WebContentsImpl*> result;
386 base::flat_set<WebContentsImpl*> current;
387
388 current.insert(web_contents);
389
390 while (!current.empty()) {
391 WebContentsImpl* current_contents = *current.begin();
392 current.erase(current.begin());
393 auto insert_result = result.insert(current_contents);
394
395 if (insert_result.second) {
396 RenderFrameHostImpl* opener_rfh = current_contents->GetOriginalOpener();
397 if (opener_rfh) {
398 current.insert(static_cast<WebContentsImpl*>(
399 WebContents::FromRenderFrameHost(opener_rfh)));
400 }
401
402 WebContentsImpl* outer_contents = current_contents->GetOuterWebContents();
403 if (outer_contents)
404 current.insert(outer_contents);
405 }
406 }
407
408 return result;
409}
410
Rakina Zata Amni4029b6d2020-07-28 02:36:20411#if defined(OS_ANDROID)
412float GetDeviceScaleAdjustment(int min_width) {
413 static const float kMinFSM = 1.05f;
414 static const int kWidthForMinFSM = 320;
415 static const float kMaxFSM = 1.3f;
416 static const int kWidthForMaxFSM = 800;
417
418 if (min_width <= kWidthForMinFSM)
419 return kMinFSM;
420 if (min_width >= kWidthForMaxFSM)
421 return kMaxFSM;
422
423 // The font scale multiplier varies linearly between kMinFSM and kMaxFSM.
424 float ratio = static_cast<float>(min_width - kWidthForMinFSM) /
425 (kWidthForMaxFSM - kWidthForMinFSM);
426 return ratio * (kMaxFSM - kMinFSM) + kMinFSM;
427}
428#endif
429
Avi Drissman33972942020-06-19 14:16:01430// Used to attach the "set of fullscreen contents" to a browser context. Storing
431// sets of WebContents on their browser context is done for two reasons. One,
432// related WebContentses must necessarily share a browser context, so this saves
433// lookup time by restricting to one specific browser context. Two, separating
434// by browser context is preemptive paranoia about keeping things separate.
435class FullscreenContentsHolder : public base::SupportsUserData::Data {
436 public:
437 FullscreenContentsHolder() = default;
438 ~FullscreenContentsHolder() override = default;
439
440 FullscreenContentsHolder(const FullscreenContentsHolder&) = delete;
441 FullscreenContentsHolder& operator=(const FullscreenContentsHolder&) = delete;
442
443 base::flat_set<WebContentsImpl*>* set() { return &set_; }
444
445 private:
446 base::flat_set<WebContentsImpl*> set_;
447};
448
449const char kFullscreenContentsSet[] = "fullscreen-contents";
450
451base::flat_set<WebContentsImpl*>* FullscreenContentsSet(
452 BrowserContext* browser_context) {
453 auto* set_holder = static_cast<FullscreenContentsHolder*>(
454 browser_context->GetUserData(kFullscreenContentsSet));
455 if (!set_holder) {
456 auto new_holder = std::make_unique<FullscreenContentsHolder>();
457 set_holder = new_holder.get();
458 browser_context->SetUserData(kFullscreenContentsSet, std::move(new_holder));
459 }
460
461 return set_holder->set();
462}
463
Mike Wasserman5b7d3bf2020-08-21 21:52:26464// Returns true if |host| has the Window Placement permission granted.
465bool WindowPlacementGranted(RenderFrameHost* host) {
466 auto* controller =
467 PermissionControllerImpl::FromBrowserContext(host->GetBrowserContext());
468 return controller && controller->GetPermissionStatusForFrame(
469 PermissionType::WINDOW_PLACEMENT, host,
470 host->GetLastCommittedURL()) ==
471 blink::mojom::PermissionStatus::GRANTED;
472}
473
Mike Wassermanb6bc0152020-08-25 22:46:20474// Adjust the requested |bounds| for opening or placing a window and return the
475// id of the display where the window will be placed. The bounds may not extend
476// outside a single screen's work area, and the |host| requires permission to
477// specify bounds on a screen other than its current screen.
Mike Wassermandabad612020-08-13 04:26:27478// TODO(crbug.com/897300): These adjustments are inaccurate for window.open(),
479// which specifies the inner content size, and for window.moveTo, resizeTo, etc.
480// calls on newly created windows, which may pass empty sizes or positions to
481// indicate uninitialized placement information in the renderer. Constraints
482// enforced later should resolve most inaccuracies, but this early enforcement
483// is needed to ensure bounds indicate the appropriate display.
Mike Wassermanb6bc0152020-08-25 22:46:20484int64_t AdjustRequestedWindowBounds(gfx::Rect* bounds, RenderFrameHost* host) {
Mike Wassermandabad612020-08-13 04:26:27485 auto* screen = display::Screen::GetScreen();
Mike Wassermanb6bc0152020-08-25 22:46:20486 auto display = screen->GetDisplayMatching(*bounds);
Mike Wassermandabad612020-08-13 04:26:27487
488 // Check, but do not prompt, for permission to place windows on other screens.
489 // Sites generally need permission to get such bounds in the first place.
490 // Also clamp offscreen bounds to the window's current screen.
Mike Wassermanb6bc0152020-08-25 22:46:20491 if (!bounds->Intersects(display.bounds()) || !WindowPlacementGranted(host))
Mike Wassermandabad612020-08-13 04:26:27492 display = screen->GetDisplayNearestView(host->GetNativeView());
Mike Wassermandabad612020-08-13 04:26:27493
Mike Wassermanb6bc0152020-08-25 22:46:20494 bounds->AdjustToFit(display.work_area());
495 return display.id();
Mike Wassermandabad612020-08-13 04:26:27496}
497
lukasza6f8ac622017-06-06 03:10:20498} // namespace
499
Joel Hockey8c2011b22020-04-30 05:07:19500CreatedWindow::CreatedWindow() = default;
501CreatedWindow::CreatedWindow(std::unique_ptr<WebContentsImpl> contents,
502 GURL target_url)
503 : contents(std::move(contents)), target_url(std::move(target_url)) {}
504CreatedWindow::~CreatedWindow() = default;
505CreatedWindow::CreatedWindow(CreatedWindow&&) = default;
506CreatedWindow& CreatedWindow::operator=(CreatedWindow&&) = default;
507
Erik Chenbb8e738e2018-04-28 14:10:43508std::unique_ptr<WebContents> WebContents::Create(
509 const WebContents::CreateParams& params) {
Albert J. Wong65fe64d2019-09-20 02:48:14510 return WebContentsImpl::Create(params);
511}
512
513std::unique_ptr<WebContentsImpl> WebContentsImpl::Create(
514 const CreateParams& params) {
515 return CreateWithOpener(params, FindOpenerRFH(params));
[email protected]d1198fd2012-08-13 22:50:19516}
517
erikchenade1fef2018-05-02 22:07:57518std::unique_ptr<WebContents> WebContents::CreateWithSessionStorage(
[email protected]54944cde2012-12-09 09:24:59519 const WebContents::CreateParams& params,
[email protected]fdac6ade2013-07-20 01:06:30520 const SessionStorageNamespaceMap& session_storage_namespace_map) {
Alexander Timin5fdeff22020-09-08 09:20:37521 OPTIONAL_TRACE_EVENT0("content", "WebContents::CreateWithSessionStorage");
erikchenade1fef2018-05-02 22:07:57522 std::unique_ptr<WebContentsImpl> new_contents(
523 new WebContentsImpl(params.browser_context));
Ian Clelland5cbaaf82017-11-27 22:00:03524 RenderFrameHostImpl* opener_rfh = FindOpenerRFH(params);
525 FrameTreeNode* opener = nullptr;
526 if (opener_rfh)
527 opener = opener_rfh->frame_tree_node();
528 new_contents->SetOpenerForNewContents(opener, params.opener_suppressed);
[email protected]fdac6ade2013-07-20 01:06:30529
Fergal Daly55b6d722020-09-11 07:56:33530 for (const auto& it : session_storage_namespace_map) {
531 new_contents->GetController().SetSessionStorageNamespace(it.first,
532 it.second.get());
[email protected]fdac6ade2013-07-20 01:06:30533 }
534
Sean Toppingbbc4a2bd2019-01-30 02:16:14535 WebContentsImpl* outer_web_contents = nullptr;
Sam McNally69a33772018-06-27 16:54:12536 if (params.guest_delegate) {
537 // This makes |new_contents| act as a guest.
538 // For more info, see comment above class BrowserPluginGuest.
Albert J. Wongc55cc64d2018-10-12 02:50:04539 BrowserPluginGuest::CreateInWebContents(new_contents.get(),
540 params.guest_delegate);
Sean Toppingbbc4a2bd2019-01-30 02:16:14541 outer_web_contents = static_cast<WebContentsImpl*>(
542 params.guest_delegate->GetOwnerWebContents());
Sam McNally69a33772018-06-27 16:54:12543 }
544
[email protected]54944cde2012-12-09 09:24:59545 new_contents->Init(params);
Sean Toppingbbc4a2bd2019-01-30 02:16:14546 if (outer_web_contents)
547 outer_web_contents->InnerWebContentsCreated(new_contents.get());
[email protected]d1198fd2012-08-13 22:50:19548 return new_contents;
[email protected]a81343d232011-12-27 07:39:20549}
[email protected]746d3052012-05-22 15:15:47550
benwells5e7260d2017-03-20 23:36:33551void WebContentsImpl::FriendWrapper::AddCreatedCallbackForTesting(
nickf9acfbe2014-12-23 19:12:37552 const CreatedCallback& callback) {
[email protected]cbb1ef592013-06-05 19:49:46553 g_created_callbacks.Get().push_back(callback);
554}
555
benwells5e7260d2017-03-20 23:36:33556void WebContentsImpl::FriendWrapper::RemoveCreatedCallbackForTesting(
nickf9acfbe2014-12-23 19:12:37557 const CreatedCallback& callback) {
[email protected]cbb1ef592013-06-05 19:49:46558 for (size_t i = 0; i < g_created_callbacks.Get().size(); ++i) {
Robert Liao1db5a352019-06-05 20:57:34559 if (g_created_callbacks.Get().at(i) == callback) {
[email protected]cbb1ef592013-06-05 19:49:46560 g_created_callbacks.Get().erase(g_created_callbacks.Get().begin() + i);
561 return;
562 }
563 }
564}
565
avidf38c952015-10-27 13:45:13566WebContents* WebContents::FromRenderViewHost(RenderViewHost* rvh) {
Alexander Timin5fdeff22020-09-08 09:20:37567 OPTIONAL_TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
568 "WebContents::FromRenderViewHost", "render_view_host",
569 rvh);
avidf38c952015-10-27 13:45:13570 if (!rvh)
571 return nullptr;
[email protected]746d3052012-05-22 15:15:47572 return rvh->GetDelegate()->GetAsWebContents();
573}
574
[email protected]a86c0e962013-12-17 17:10:39575WebContents* WebContents::FromRenderFrameHost(RenderFrameHost* rfh) {
Alexander Timin5fdeff22020-09-08 09:20:37576 OPTIONAL_TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
577 "WebContents::FromRenderFrameHost", "render_frame_host",
578 base::trace_event::ToTracedValue(rfh));
avidf38c952015-10-27 13:45:13579 if (!rfh)
580 return nullptr;
Alexander Timin33bd754c02020-03-10 22:50:18581 if (!rfh->IsCurrent() && base::FeatureList::IsEnabled(
582 kCheckWebContentsAccessFromNonCurrentFrame)) {
583 // TODO(crbug.com/1059903): return nullptr here eventually.
584 base::debug::DumpWithoutCrashing();
585 }
avidf38c952015-10-27 13:45:13586 return static_cast<RenderFrameHostImpl*>(rfh)->delegate()->GetAsWebContents();
[email protected]a86c0e962013-12-17 17:10:39587}
588
ananta4b7467a52016-09-23 01:42:38589WebContents* WebContents::FromFrameTreeNodeId(int frame_tree_node_id) {
Alexander Timin5fdeff22020-09-08 09:20:37590 OPTIONAL_TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
591 "WebContents::FromFrameTreeNodeId",
592 "frame_tree_node_id", frame_tree_node_id);
ananta4b7467a52016-09-23 01:42:38593 FrameTreeNode* frame_tree_node =
594 FrameTreeNode::GloballyFindByID(frame_tree_node_id);
anantab8cfa3b2016-10-14 22:43:19595 if (!frame_tree_node)
596 return nullptr;
jam8c4edd02017-05-06 18:50:33597 return WebContentsImpl::FromFrameTreeNode(frame_tree_node);
ananta4b7467a52016-09-23 01:42:38598}
599
leon.han552e9de2017-02-09 14:37:30600void WebContents::SetScreenOrientationDelegate(
601 ScreenOrientationDelegate* delegate) {
602 ScreenOrientationProvider::SetDelegate(delegate);
603}
604
[email protected]7fff43e2013-05-21 20:21:10605// WebContentsImpl::DestructionObserver ----------------------------------------
606
607class WebContentsImpl::DestructionObserver : public WebContentsObserver {
608 public:
609 DestructionObserver(WebContentsImpl* owner, WebContents* watched_contents)
Fergal Daly09d6c762020-05-29 02:05:18610 : WebContentsObserver(watched_contents), owner_(owner) {}
[email protected]7fff43e2013-05-21 20:21:10611
612 // WebContentsObserver:
dchengc2282aa2014-10-21 12:07:58613 void WebContentsDestroyed() override {
[email protected]12a46832014-05-09 13:35:58614 owner_->OnWebContentsDestroyed(
615 static_cast<WebContentsImpl*>(web_contents()));
[email protected]7fff43e2013-05-21 20:21:10616 }
617
618 private:
619 WebContentsImpl* owner_;
620
621 DISALLOW_COPY_AND_ASSIGN(DestructionObserver);
622};
623
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:50624// TODO(sreejakshetty): Make |WebContentsImpl::ColorChooser| per-frame instead
625// of WebContents-owned.
Joel Hockey85b379d2017-12-11 10:42:13626// WebContentsImpl::ColorChooser ----------------------------------------------
Joel Hockey163835a2017-12-20 11:51:57627class WebContentsImpl::ColorChooser : public blink::mojom::ColorChooser {
Joel Hockey85b379d2017-12-11 10:42:13628 public:
629 ColorChooser(content::ColorChooser* chooser,
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20630 mojo::PendingReceiver<blink::mojom::ColorChooser> receiver,
631 mojo::PendingRemote<blink::mojom::ColorChooserClient> client)
Joel Hockey85b379d2017-12-11 10:42:13632 : chooser_(chooser),
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20633 receiver_(this, std::move(receiver)),
Joel Hockey85b379d2017-12-11 10:42:13634 client_(std::move(client)) {
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20635 receiver_.set_disconnect_handler(
Joel Hockey85b379d2017-12-11 10:42:13636 base::BindOnce([](content::ColorChooser* chooser) { chooser->End(); },
637 base::Unretained(chooser)));
638 }
[email protected]8ed16472014-04-11 19:02:48639
Joel Hockey85b379d2017-12-11 10:42:13640 ~ColorChooser() override { chooser_->End(); }
[email protected]8ed16472014-04-11 19:02:48641
Joel Hockey85b379d2017-12-11 10:42:13642 void SetSelectedColor(SkColor color) override {
Alexander Timin5fdeff22020-09-08 09:20:37643 OPTIONAL_TRACE_EVENT0("content",
644 "WebContentsImpl::ColorChooser::SetSelectedColor");
Joel Hockey85b379d2017-12-11 10:42:13645 chooser_->SetSelectedColor(color);
646 }
647
648 void DidChooseColorInColorChooser(SkColor color) {
Alexander Timin5fdeff22020-09-08 09:20:37649 OPTIONAL_TRACE_EVENT0(
650 "content",
651 "WebContentsImpl::ColorChooser::DidChooseColorInColorChooser");
Joel Hockey85b379d2017-12-11 10:42:13652 client_->DidChooseColor(color);
653 }
654
655 private:
656 // Color chooser that was opened by this tab.
657 std::unique_ptr<content::ColorChooser> chooser_;
658
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20659 // mojo receiver.
660 mojo::Receiver<blink::mojom::ColorChooser> receiver_;
Joel Hockey85b379d2017-12-11 10:42:13661
662 // mojo renderer client.
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20663 mojo::Remote<blink::mojom::ColorChooserClient> client_;
Joel Hockey85b379d2017-12-11 10:42:13664};
nicka0ac8382016-12-15 23:59:23665
lazyboy6ec48b2a2015-06-29 15:18:14666// WebContentsImpl::WebContentsTreeNode ----------------------------------------
lfg601233692017-03-06 22:45:44667WebContentsImpl::WebContentsTreeNode::WebContentsTreeNode(
668 WebContentsImpl* current_web_contents)
669 : current_web_contents_(current_web_contents),
670 outer_web_contents_(nullptr),
lazyboy6ec48b2a2015-06-29 15:18:14671 outer_contents_frame_tree_node_id_(
avallee0206f782016-07-28 18:55:33672 FrameTreeNode::kFrameTreeNodeInvalidId),
lfg601233692017-03-06 22:45:44673 focused_web_contents_(current_web_contents) {}
lazyboy6ec48b2a2015-06-29 15:18:14674
Fergal Daly55b6d722020-09-11 07:56:33675WebContentsImpl::WebContentsTreeNode::~WebContentsTreeNode() = default;
lazyboy6ec48b2a2015-06-29 15:18:14676
Lucas Furukawa Gadani99125822019-01-03 15:41:49677std::unique_ptr<WebContents>
678WebContentsImpl::WebContentsTreeNode::DisconnectFromOuterWebContents() {
Alexander Timin5fdeff22020-09-08 09:20:37679 OPTIONAL_TRACE_EVENT0("content",
680 "WebContentsTreeNode::DisconnectFromOuterWebContents");
Lucas Furukawa Gadani99125822019-01-03 15:41:49681 std::unique_ptr<WebContents> inner_contents =
682 outer_web_contents_->node_.DetachInnerWebContents(current_web_contents_);
683 OuterContentsFrameTreeNode()->RemoveObserver(this);
684 outer_contents_frame_tree_node_id_ = FrameTreeNode::kFrameTreeNodeInvalidId;
685 outer_web_contents_ = nullptr;
686 return inner_contents;
687}
688
paulmeyerfeafc2d2017-04-25 21:46:40689void WebContentsImpl::WebContentsTreeNode::AttachInnerWebContents(
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:50690 std::unique_ptr<WebContents> inner_web_contents,
691 RenderFrameHostImpl* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:37692 OPTIONAL_TRACE_EVENT0("content",
693 "WebContentsTreeNode::AttachInnerWebContents");
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:50694 WebContentsImpl* inner_web_contents_impl =
695 static_cast<WebContentsImpl*>(inner_web_contents.get());
696 WebContentsTreeNode& inner_web_contents_node = inner_web_contents_impl->node_;
697
698 inner_web_contents_node.focused_web_contents_ = nullptr;
699 inner_web_contents_node.outer_web_contents_ = current_web_contents_;
700 inner_web_contents_node.outer_contents_frame_tree_node_id_ =
701 render_frame_host->frame_tree_node()->frame_tree_node_id();
702
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18703 inner_web_contents_.push_back(std::move(inner_web_contents));
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:50704
705 render_frame_host->frame_tree_node()->AddObserver(&inner_web_contents_node);
Jeremy Roman03ce13ce2020-05-29 22:16:57706 current_web_contents_->InnerWebContentsAttached(inner_web_contents_impl);
paulmeyerfeafc2d2017-04-25 21:46:40707}
708
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18709std::unique_ptr<WebContents>
710WebContentsImpl::WebContentsTreeNode::DetachInnerWebContents(
paulmeyerfeafc2d2017-04-25 21:46:40711 WebContentsImpl* inner_web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:37712 OPTIONAL_TRACE_EVENT0(
713 "content",
714 "WebContentsImpl::WebContentsTreeNode::DetachInnerWebContents");
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18715 std::unique_ptr<WebContents> detached_contents;
716 for (std::unique_ptr<WebContents>& web_contents : inner_web_contents_) {
717 if (web_contents.get() == inner_web_contents) {
718 detached_contents = std::move(web_contents);
719 std::swap(web_contents, inner_web_contents_.back());
720 inner_web_contents_.pop_back();
Jeremy Roman03ce13ce2020-05-29 22:16:57721 current_web_contents_->InnerWebContentsDetached(inner_web_contents);
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18722 return detached_contents;
723 }
724 }
725
726 NOTREACHED();
727 return nullptr;
paulmeyerfeafc2d2017-04-25 21:46:40728}
729
lfga3e2bdc2017-03-07 20:44:01730FrameTreeNode*
731WebContentsImpl::WebContentsTreeNode::OuterContentsFrameTreeNode() const {
732 return FrameTreeNode::GloballyFindByID(outer_contents_frame_tree_node_id_);
lfg601233692017-03-06 22:45:44733}
734
lfga3e2bdc2017-03-07 20:44:01735void WebContentsImpl::WebContentsTreeNode::OnFrameTreeNodeDestroyed(
736 FrameTreeNode* node) {
Alexander Timin5fdeff22020-09-08 09:20:37737 OPTIONAL_TRACE_EVENT0("content",
738 "WebContentsTreeNode::OnFrameTreeNodeDestroyed");
lfga3e2bdc2017-03-07 20:44:01739 DCHECK_EQ(outer_contents_frame_tree_node_id_, node->frame_tree_node_id())
740 << "WebContentsTreeNode should only receive notifications for the "
741 "FrameTreeNode in its outer WebContents that hosts it.";
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18742
743 // Deletes |this| too.
744 outer_web_contents_->node_.DetachInnerWebContents(current_web_contents_);
lazyboy6ec48b2a2015-06-29 15:18:14745}
746
avallee0206f782016-07-28 18:55:33747void WebContentsImpl::WebContentsTreeNode::SetFocusedWebContents(
748 WebContentsImpl* web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:37749 OPTIONAL_TRACE_EVENT0("content",
750 "WebContentsTreeNode::SetFocusedWebContents");
avallee0206f782016-07-28 18:55:33751 DCHECK(!outer_web_contents())
752 << "Only the outermost WebContents tracks focus.";
753 focused_web_contents_ = web_contents;
754}
755
paulmeyerfeafc2d2017-04-25 21:46:40756WebContentsImpl*
757WebContentsImpl::WebContentsTreeNode::GetInnerWebContentsInFrame(
758 const FrameTreeNode* frame) {
759 auto ftn_id = frame->frame_tree_node_id();
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18760 for (auto& contents : inner_web_contents_) {
761 WebContentsImpl* impl = static_cast<WebContentsImpl*>(contents.get());
762 if (impl->node_.outer_contents_frame_tree_node_id() == ftn_id) {
763 return impl;
paulmeyerfeafc2d2017-04-25 21:46:40764 }
765 }
766 return nullptr;
767}
768
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18769std::vector<WebContentsImpl*>
770WebContentsImpl::WebContentsTreeNode::GetInnerWebContents() const {
771 std::vector<WebContentsImpl*> inner_web_contents;
772 for (auto& contents : inner_web_contents_)
773 inner_web_contents.push_back(static_cast<WebContentsImpl*>(contents.get()));
774
775 return inner_web_contents;
paulmeyerfeafc2d2017-04-25 21:46:40776}
777
Alexander Timin90c20c32020-08-12 15:28:32778// WebContentsObserverList -----------------------------------------------------
779WebContentsImpl::WebContentsObserverList::WebContentsObserverList() = default;
780WebContentsImpl::WebContentsObserverList::~WebContentsObserverList() = default;
781
782void WebContentsImpl::WebContentsObserverList::AddObserver(
783 WebContentsObserver* observer) {
784 observers_.AddObserver(observer);
785}
786
787void WebContentsImpl::WebContentsObserverList::RemoveObserver(
788 WebContentsObserver* observer) {
789 observers_.RemoveObserver(observer);
790}
791
[email protected]b172aee2012-04-10 17:05:26792// WebContentsImpl -------------------------------------------------------------
[email protected]420ae012009-04-24 05:16:32793
alexmose201c7cd2015-06-10 17:14:21794WebContentsImpl::WebContentsImpl(BrowserContext* browser_context)
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28795 : delegate_(nullptr),
[email protected]69e797f2013-04-30 01:10:22796 controller_(this, browser_context),
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28797 render_view_host_delegate_view_(nullptr),
alexmose201c7cd2015-06-10 17:14:21798 created_with_opener_(false),
Lucas Furukawa Gadani99125822019-01-03 15:41:49799 node_(this),
Fergal Daly09d6c762020-05-29 02:05:18800 frame_tree_(&controller_, this, this, this, this, this),
[email protected]6dfed692014-05-22 04:18:03801 is_load_to_different_document_(false),
[email protected]443b80e2010-12-14 00:42:23802 crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING),
803 crashed_error_code_(0),
[email protected]d5f942ba2008-09-26 19:30:34804 waiting_for_response_(false),
[email protected]fcf75d42013-12-03 20:11:26805 load_state_(net::LOAD_STATE_IDLE, base::string16()),
[email protected]094e5b22009-09-25 04:23:56806 upload_size_(0),
807 upload_position_(0),
dfalcantarae6b7b46752015-07-10 18:14:16808 is_resume_pending_(false),
[email protected]b4c84012014-04-28 19:51:10809 has_accessed_initial_document_(false),
Collin Bakerc5259962019-11-14 17:51:58810 visible_capturer_count_(0),
811 hidden_capturer_count_(0),
[email protected]fdd61c62009-04-22 19:22:57812 is_being_destroyed_(false),
813 notify_disconnection_(false),
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28814 dialog_manager_(nullptr),
[email protected]7ab1e7d62009-10-14 23:32:01815 is_showing_before_unload_dialog_(false),
gab0dccfef2015-05-20 18:43:39816 last_active_time_(base::TimeTicks::Now()),
[email protected]ebf40a72010-07-22 01:46:38817 closed_by_user_gesture_(false),
danakj938b37a62019-09-24 18:35:54818 minimum_zoom_percent_(
819 static_cast<int>(blink::kMinimumPageZoomFactor * 100)),
820 maximum_zoom_percent_(
821 static_cast<int>(blink::kMaximumPageZoomFactor * 100)),
w.shackleton49bcd392016-01-06 17:38:22822 zoom_scroll_remainder_(0),
alexmosc9e76ec2016-05-16 22:59:37823 fullscreen_widget_process_id_(ChildProcessHost::kInvalidUniqueID),
[email protected]5dcaf8e2013-12-28 01:31:42824 fullscreen_widget_routing_id_(MSG_ROUTING_NONE),
[email protected]0b431992014-06-24 00:08:03825 fullscreen_widget_had_focus_at_shutdown_(false),
[email protected]34ff1cfc2014-08-20 06:16:05826 force_disable_overscroll_content_(false),
[email protected]95640212014-07-26 18:14:30827 last_dialog_suppressed_(false),
waffles1c12bf402016-02-10 17:45:48828 accessibility_mode_(
Dominic Mazzoni21fb0282019-02-13 18:32:47829 GetContentClient()->browser()->GetAXModeForBrowserContext(
830 browser_context)),
avayvodcc85bbd2015-08-28 19:11:15831 audio_stream_monitor_(this),
Thomas Guilbert882c4cec2019-02-14 05:55:45832 media_web_contents_observer_(
833 std::make_unique<MediaWebContentsObserver>(this)),
mcnee336ea2c2017-05-23 22:50:59834#if !defined(OS_ANDROID)
mcnee432e47d2015-11-09 19:37:46835 page_scale_factor_is_one_(true),
mcnee336ea2c2017-05-23 22:50:59836#endif // !defined(OS_ANDROID)
qinmin72e8bd02016-10-21 19:35:37837 is_overlay_content_(false),
ekaramadf6750aa2017-06-06 18:29:42838 showing_context_menu_(false),
W. James MacLean62198672019-06-04 16:46:10839 text_autosizer_page_info_({0, 0, 1.f}),
shivanigithubcceeacf2020-03-06 20:00:27840 native_theme_observer_(this) {
Alexander Timin5fdeff22020-09-08 09:20:37841 TRACE_EVENT0("content", "WebContentsImpl::WebContentsImpl");
danakjf4b9e942019-11-29 15:43:04842 frame_tree_.SetFrameRemoveListener(base::BindRepeating(
843 &WebContentsImpl::OnFrameRemoved, base::Unretained(this)));
brettw4b461082016-11-19 18:55:16844#if BUILDFLAG(ENABLE_PLUGINS)
Fergal Daly55b6d722020-09-11 07:56:33845 pepper_playback_observer_ = std::make_unique<PepperPlaybackObserver>(this);
zqzhang181047e62016-07-01 13:37:17846#endif
blundelle75a8f92017-03-27 08:11:17847
Becca Hughes86334622018-07-09 21:29:38848#if defined(OS_ANDROID)
Elly Fong-Jonescdd7ae82019-02-20 23:26:33849 display_cutout_host_impl_ = std::make_unique<DisplayCutoutHostImpl>(this);
Becca Hughes86334622018-07-09 21:29:38850#endif
John Delaney732721e92020-02-07 23:11:27851
Alison Maher7f366dc62020-03-03 19:46:00852 ui::NativeTheme* native_theme = ui::NativeTheme::GetInstanceForWeb();
853 native_theme_observer_.Add(native_theme);
854 using_dark_colors_ = native_theme->ShouldUseDarkColors();
855 preferred_color_scheme_ = native_theme->GetPreferredColorScheme();
856
Mike Wassermanb213b9352020-04-16 00:32:34857 screen_change_monitor_ =
858 std::make_unique<ScreenChangeMonitor>(base::BindRepeating(
859 &WebContentsImpl::OnScreensChange, base::Unretained(this)));
860
John Delaney732721e92020-02-07 23:11:27861 // ConversionHost takes a weak ref on |this|, so it must be created outside of
862 // the initializer list.
Charlie Harrison405f6212020-04-14 21:57:32863 if (base::FeatureList::IsEnabled(features::kConversionMeasurement)) {
864 conversion_host_ = std::make_unique<ConversionHost>(this);
865 }
[email protected]332af7732009-03-11 13:21:35866}
initial.commit09911bf2008-07-26 23:55:29867
[email protected]b172aee2012-04-10 17:05:26868WebContentsImpl::~WebContentsImpl() {
Alexander Timin5fdeff22020-09-08 09:20:37869 TRACE_EVENT0("content", "WebContentsImpl::~WebContentsImpl");
870
creisba91ba82017-05-12 22:56:19871 // Imperfect sanity check against double free, given some crashes unexpectedly
872 // observed in the wild.
873 CHECK(!is_being_destroyed_);
874
875 // We generally keep track of is_being_destroyed_ to let other features know
876 // to avoid certain actions during destruction.
[email protected]420ae012009-04-24 05:16:32877 is_being_destroyed_ = true;
878
creis97867aa2017-02-17 18:39:45879 // A WebContents should never be deleted while it is notifying observers,
creisba91ba82017-05-12 22:56:19880 // since this will lead to a use-after-free as it continues to notify later
creis97867aa2017-02-17 18:39:45881 // observers.
Alexander Timin90c20c32020-08-12 15:28:32882 CHECK(!observers_.is_notifying_observers());
creis97867aa2017-02-17 18:39:45883
Avi Drissman33972942020-06-19 14:16:01884 FullscreenContentsSet(GetBrowserContext())->erase(this);
885
kenrb2a565f82015-09-02 20:24:59886 rwh_input_event_router_.reset();
887
Julie Jeongeun Kim7d0986172019-12-04 03:17:25888 for (auto& entry : receiver_sets_)
889 entry.second->CloseAllReceivers();
rockotf62002a2016-09-15 00:08:59890
avallee0206f782016-07-28 18:55:33891 WebContentsImpl* outermost = GetOutermostWebContents();
avallee9993fca2016-11-17 06:16:50892 if (this != outermost && ContainsOrIsFocusedWebContents()) {
avallee0206f782016-07-28 18:55:33893 // If the current WebContents is in focus, unset it.
avallee9993fca2016-11-17 06:16:50894 outermost->SetAsFocusedWebContentsIfNecessary();
avallee0206f782016-07-28 18:55:33895 }
896
Nick Carterd73635b2018-03-13 18:31:41897 if (mouse_lock_widget_)
James Hollyerd5c9de462020-03-10 19:02:45898 mouse_lock_widget_->RejectMouseLockOrUnlockIfNecessary(
899 blink::mojom::PointerLockResult::kElementDestroyed);
Nick Carterd73635b2018-03-13 18:31:41900
dcheng72be33c2016-01-21 04:11:31901 for (FrameTreeNode* node : frame_tree_.Nodes()) {
902 // Delete all RFHs pending shutdown, which will lead the corresponding RVHs
903 // to be shutdown and be deleted as well.
dcheng57e39e22016-01-21 00:25:38904 node->render_manager()->ClearRFHsPendingShutdown();
dcheng57e39e22016-01-21 00:25:38905 node->render_manager()->ClearWebUIInstances();
dcheng72be33c2016-01-21 04:11:31906 }
carlosk35f35af2015-12-01 10:55:40907
dcheng57e39e22016-01-21 00:25:38908 for (RenderWidgetHostImpl* widget : created_widgets_)
909 widget->DetachDelegate();
[email protected]b24b68a2012-09-24 21:57:26910 created_widgets_.clear();
911
[email protected]3ab9cb82011-06-03 18:02:07912 // Clear out any JavaScript state.
avi5d3b8692016-10-12 22:00:46913 if (dialog_manager_) {
avi6879fcf2017-01-21 05:27:53914 dialog_manager_->CancelDialogs(this, /*reset_state=*/true);
avi5d3b8692016-10-12 22:00:46915 }
[email protected]3ab9cb82011-06-03 18:02:07916
Joel Hockey85b379d2017-12-11 10:42:13917 color_chooser_.reset();
Rakina Zata Amni16196122018-11-14 02:14:00918 find_request_manager_.reset();
[email protected]da8543762012-03-20 08:52:20919
[email protected]420ae012009-04-24 05:16:32920 NotifyDisconnected();
[email protected]420ae012009-04-24 05:16:32921
[email protected]ca13a442012-04-17 14:00:12922 // Notify any observer that have a reference on this WebContents.
[email protected]8ff00d72012-10-23 19:12:21923 NotificationService::current()->Notify(
924 NOTIFICATION_WEB_CONTENTS_DESTROYED,
925 Source<WebContents>(this),
926 NotificationService::NoDetails());
[email protected]420ae012009-04-24 05:16:32927
Arthur Sonzogni5a9a88c2018-10-18 13:16:00928 // Destroy all subframes now. This notifies observers.
929 GetMainFrame()->ResetChildren();
[email protected]df0c843f2014-05-23 20:37:23930 GetRenderManager()->ResetProxyHosts();
[email protected]c06c58c2014-03-12 20:31:59931
clamy0e119882015-07-31 16:12:33932 // Manually call the observer methods for the root frame tree node. It is
933 // necessary to manually delete all objects tracking navigations
934 // (NavigationHandle, NavigationRequest) for observers to be properly
935 // notified of these navigations stopping before the WebContents is
936 // destroyed.
[email protected]df0c843f2014-05-23 20:37:23937 RenderFrameHostManager* root = GetRenderManager();
naskob21fe4872015-02-24 14:15:56938
Lowell Manners20250112019-10-18 15:06:15939 GetController().GetBackForwardCache().Shutdown();
940
naskob21fe4872015-02-24 14:15:56941 root->current_frame_host()->SetRenderFrameCreated(false);
clamyfc3850d2018-02-23 14:35:28942 root->current_frame_host()->ResetNavigationRequests();
clamy0e119882015-07-31 16:12:33943
Arthur Hemeryc3380172018-01-22 14:00:17944 // Do not update state as the WebContents is being destroyed.
Arthur Hemery241b9392019-10-24 11:08:41945 frame_tree_.root()->ResetNavigationRequest(true);
Arthur Hemeryc3380172018-01-22 14:00:17946 if (root->speculative_frame_host()) {
danakjf2342432019-05-15 21:46:09947 root->speculative_frame_host()->DeleteRenderFrame(
948 FrameDeleteIntention::kSpeculativeMainFrameForShutdown);
Arthur Hemeryc3380172018-01-22 14:00:17949 root->speculative_frame_host()->SetRenderFrameCreated(false);
clamyfc3850d2018-02-23 14:35:28950 root->speculative_frame_host()->ResetNavigationRequests();
clamy0e119882015-07-31 16:12:33951 }
[email protected]f273ee52013-10-18 16:05:27952
brettw4b461082016-11-19 18:55:16953#if BUILDFLAG(ENABLE_PLUGINS)
zqzhang181047e62016-07-01 13:37:17954 // Call this before WebContentsDestroyed() is broadcasted since
955 // AudioFocusManager will be destroyed after that.
956 pepper_playback_observer_.reset();
957#endif // defined(ENABLED_PLUGINS)
958
Chris Hamiltondf0d72cd2018-05-29 16:23:53959 // If audio is playing then notify external observers of the audio stream
960 // disappearing.
961 if (is_currently_audible_) {
962 is_currently_audible_ = false;
Alexander Timin90c20c32020-08-12 15:28:32963 observers_.ForEachObserver([&](WebContentsObserver* observer) {
964 observer->OnAudioStateChanged(false);
965 });
Chris Hamiltondf0d72cd2018-05-29 16:23:53966 if (GetOuterWebContents())
967 GetOuterWebContents()->OnAudioStateChanged();
968 }
969
Alexander Timin90c20c32020-08-12 15:28:32970 observers_.ForEachObserver([&](WebContentsObserver* observer) {
971 observer->FrameDeleted(root->current_frame_host());
972 });
973 observers_.ForEachObserver([&](WebContentsObserver* observer) {
974 observer->RenderViewDeleted(root->current_host());
975 });
Kevin McNee576bb5d82019-05-29 16:47:51976#if defined(OS_ANDROID)
977 // For simplicity, destroy the Java WebContents before we notify of the
978 // destruction of the WebContents.
979 ClearWebContentsAndroid();
980#endif
981
Alexander Timin90c20c32020-08-12 15:28:32982 observers_.ForEachObserver(
983 [&](WebContentsObserver* observer) { observer->WebContentsDestroyed(); });
Becca Hughesd11d6502018-07-31 17:01:28984 if (display_cutout_host_impl_)
985 display_cutout_host_impl_->WebContentsDestroyed();
986
Alexander Timin90c20c32020-08-12 15:28:32987 observers_.ForEachObserver(
988 [&](WebContentsObserver* observer) { observer->ResetWebContents(); });
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28989 SetDelegate(nullptr);
[email protected]b5a1d11c2011-02-17 03:09:42990}
991
erikchen50735fd2018-05-05 15:08:33992std::unique_ptr<WebContentsImpl> WebContentsImpl::CreateWithOpener(
[email protected]54944cde2012-12-09 09:24:59993 const WebContents::CreateParams& params,
Ian Clelland5cbaaf82017-11-27 22:00:03994 RenderFrameHostImpl* opener_rfh) {
Alexander Timin5fdeff22020-09-08 09:20:37995 OPTIONAL_TRACE_EVENT1("browser", "WebContentsImpl::CreateWithOpener",
996 "opener", base::trace_event::ToTracedValue(opener_rfh));
Ian Clelland5cbaaf82017-11-27 22:00:03997 FrameTreeNode* opener = nullptr;
998 if (opener_rfh)
999 opener = opener_rfh->frame_tree_node();
erikchen50735fd2018-05-05 15:08:331000 std::unique_ptr<WebContentsImpl> new_contents(
1001 new WebContentsImpl(params.browser_context));
lukasza6f8ac622017-06-06 03:10:201002 new_contents->SetOpenerForNewContents(opener, params.opener_suppressed);
alexmose201c7cd2015-06-10 17:14:211003
alexmosaedfc6f2016-01-21 23:57:381004 // If the opener is sandboxed, a new popup must inherit the opener's sandbox
1005 // flags, and these flags take effect immediately. An exception is if the
1006 // opener's sandbox flags lack the PropagatesToAuxiliaryBrowsingContexts
1007 // bit (which is controlled by the "allow-popups-to-escape-sandbox" token).
1008 // See https://html.spec.whatwg.org/#attr-iframe-sandbox.
lukasza6f8ac622017-06-06 03:10:201009 FrameTreeNode* new_root = new_contents->GetFrameTree()->root();
alexmosaedfc6f2016-01-21 23:57:381010 if (opener) {
arthursonzognib93a4472020-04-10 07:38:001011 network::mojom::WebSandboxFlags opener_flags =
Antonio Gomes7096ac02020-02-14 14:29:541012 opener_rfh->active_sandbox_flags();
arthursonzognib93a4472020-04-10 07:38:001013 const network::mojom::WebSandboxFlags inherit_flag =
1014 network::mojom::WebSandboxFlags::kPropagatesToAuxiliaryBrowsingContexts;
Ehsan Karamad39407082019-02-19 23:38:191015 bool sandbox_propagates_to_auxilary_context =
1016 (opener_flags & inherit_flag) == inherit_flag;
1017 if (sandbox_propagates_to_auxilary_context)
Charlie Hue1b77ac2019-12-13 21:30:171018 new_root->SetPendingFramePolicy({opener_flags,
1019 {} /* container_policy */,
1020 {} /* required_document_policy */});
arthursonzognib93a4472020-04-10 07:38:001021 if (opener_flags == network::mojom::WebSandboxFlags::kNone ||
Ehsan Karamad39407082019-02-19 23:38:191022 sandbox_propagates_to_auxilary_context) {
1023 // TODO(ekaramad, iclelland): Do not propagate feature policies from non-
1024 // sandboxed disowned openers (rel=noopener).
1025 // If the current page is not sandboxed, or if the sandbox is to propagate
1026 // to the popups then opener's feature policy will apply to the new popup
1027 // as well.
1028 new_root->SetOpenerFeaturePolicyState(
Ehsan Karamad34d10682019-02-26 20:55:041029 opener_rfh->feature_policy()->GetFeatureState());
alexmosaedfc6f2016-01-21 23:57:381030 }
1031 }
1032
mark a. foltzef394fce2017-10-21 09:11:021033 // Apply starting sandbox flags.
Luna Luc3fdacdf2017-11-08 04:48:531034 blink::FramePolicy frame_policy(new_root->pending_frame_policy());
mark a. foltzef394fce2017-10-21 09:11:021035 frame_policy.sandbox_flags |= params.starting_sandbox_flags;
1036 new_root->SetPendingFramePolicy(frame_policy);
Charlie Hu5ffc0152019-12-06 15:59:531037 new_root->CommitFramePolicy(frame_policy);
mark a. foltzef394fce2017-10-21 09:11:021038
alexmose201c7cd2015-06-10 17:14:211039 // This may be true even when opener is null, such as when opening blocked
1040 // popups.
alexmos090fae8e2015-05-28 17:09:281041 if (params.created_with_opener)
1042 new_contents->created_with_opener_ = true;
1043
Sean Toppingbbc4a2bd2019-01-30 02:16:141044 WebContentsImpl* outer_web_contents = nullptr;
[email protected]4858e432014-06-23 18:14:171045 if (params.guest_delegate) {
[email protected]83100cd2014-05-10 11:50:061046 // This makes |new_contents| act as a guest.
1047 // For more info, see comment above class BrowserPluginGuest.
Albert J. Wongc55cc64d2018-10-12 02:50:041048 BrowserPluginGuest::CreateInWebContents(new_contents.get(),
1049 params.guest_delegate);
Sean Toppingbbc4a2bd2019-01-30 02:16:141050 outer_web_contents = static_cast<WebContentsImpl*>(
1051 params.guest_delegate->GetOwnerWebContents());
[email protected]83100cd2014-05-10 11:50:061052 }
mark a. foltzef394fce2017-10-21 09:11:021053
[email protected]54944cde2012-12-09 09:24:591054 new_contents->Init(params);
Sean Toppingbbc4a2bd2019-01-30 02:16:141055 if (outer_web_contents)
1056 outer_web_contents->InnerWebContentsCreated(new_contents.get());
[email protected]d1198fd2012-08-13 22:50:191057 return new_contents;
1058}
1059
[email protected]95640212014-07-26 18:14:301060// static
1061std::vector<WebContentsImpl*> WebContentsImpl::GetAllWebContents() {
Alexander Timin5fdeff22020-09-08 09:20:371062 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1063 "WebContentsImpl::GetAllWebContents");
[email protected]95640212014-07-26 18:14:301064 std::vector<WebContentsImpl*> result;
dcheng59716272016-04-09 05:19:081065 std::unique_ptr<RenderWidgetHostIterator> widgets(
[email protected]95640212014-07-26 18:14:301066 RenderWidgetHostImpl::GetRenderWidgetHosts());
[email protected]95640212014-07-26 18:14:301067 while (RenderWidgetHost* rwh = widgets->GetNextHost()) {
[email protected]95640212014-07-26 18:14:301068 RenderViewHost* rvh = RenderViewHost::From(rwh);
1069 if (!rvh)
1070 continue;
1071 WebContents* web_contents = WebContents::FromRenderViewHost(rvh);
1072 if (!web_contents)
1073 continue;
avidf38c952015-10-27 13:45:131074 if (web_contents->GetRenderViewHost() != rvh)
1075 continue;
1076 // Because a WebContents can only have one current RVH at a time, there will
1077 // be no duplicate WebContents here.
1078 result.push_back(static_cast<WebContentsImpl*>(web_contents));
[email protected]95640212014-07-26 18:14:301079 }
1080 return result;
1081}
1082
clamya16aa8172015-05-26 13:07:251083// static
1084WebContentsImpl* WebContentsImpl::FromFrameTreeNode(
paulmeyerfeafc2d2017-04-25 21:46:401085 const FrameTreeNode* frame_tree_node) {
Alexander Timin5fdeff22020-09-08 09:20:371086 OPTIONAL_TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1087 "WebContentsImpl::FromFrameTreeNode", "frame_tree_node",
1088 frame_tree_node);
clamya16aa8172015-05-26 13:07:251089 return static_cast<WebContentsImpl*>(
1090 WebContents::FromRenderFrameHost(frame_tree_node->current_frame_host()));
1091}
1092
clamy0d32d6d2015-11-24 11:16:261093// static
Patrick Monette275a6f92b2020-01-09 21:05:041094WebContents* WebContentsImpl::FromRenderFrameHostID(
1095 GlobalFrameRoutingId render_frame_host_id) {
Alexander Timin5fdeff22020-09-08 09:20:371096 OPTIONAL_TRACE_EVENT2(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1097 "WebContentsImpl::FromRenderFrameHostID", "process_id",
1098 render_frame_host_id.child_id, "frame_id",
1099 render_frame_host_id.frame_routing_id);
Patrick Monette275a6f92b2020-01-09 21:05:041100 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI) ||
1101 !BrowserThread::IsThreadInitialized(BrowserThread::UI));
Patrick Monette7364e6972020-01-09 22:56:021102 RenderFrameHost* render_frame_host =
1103 RenderFrameHost::FromID(render_frame_host_id);
1104 if (!render_frame_host)
1105 return nullptr;
1106
1107 return WebContents::FromRenderFrameHost(render_frame_host);
Patrick Monette275a6f92b2020-01-09 21:05:041108}
1109
1110// static
clamy0d32d6d2015-11-24 11:16:261111WebContents* WebContentsImpl::FromRenderFrameHostID(int render_process_host_id,
1112 int render_frame_host_id) {
Patrick Monette7364e6972020-01-09 22:56:021113 return FromRenderFrameHostID(
1114 GlobalFrameRoutingId(render_process_host_id, render_frame_host_id));
clamy0d32d6d2015-11-24 11:16:261115}
1116
paulmeyerfeafc2d2017-04-25 21:46:401117// static
1118WebContentsImpl* WebContentsImpl::FromOuterFrameTreeNode(
1119 const FrameTreeNode* frame_tree_node) {
Alexander Timin5fdeff22020-09-08 09:20:371120 OPTIONAL_TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1121 "WebContentsImpl::FromOuterFrameTreeNode",
1122 "frame_tree_node", frame_tree_node);
paulmeyerfeafc2d2017-04-25 21:46:401123 return WebContentsImpl::FromFrameTreeNode(frame_tree_node)
1124 ->node_.GetInnerWebContentsInFrame(frame_tree_node);
1125}
1126
[email protected]b0936d22013-11-28 06:47:361127RenderFrameHostManager* WebContentsImpl::GetRenderManagerForTesting() {
[email protected]fa944cb82013-11-15 17:51:211128 return GetRenderManager();
[email protected]765187182012-01-11 23:59:281129}
1130
nicka0ac8382016-12-15 23:59:231131bool WebContentsImpl::OnMessageReceived(RenderViewHostImpl* render_view_host,
[email protected]7bb761892012-07-20 09:32:471132 const IPC::Message& message) {
Alexander Timin5fdeff22020-09-08 09:20:371133 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnMessageReceived",
1134 "render_view_host", render_view_host);
Alexander Timin90c20c32020-08-12 15:28:321135 for (auto& observer : observers_.observer_list()) {
Lukasz Anforowicz89f2c1b2017-08-30 21:36:461136 // TODO(nick, creis): https://crbug.com/758026: Replace all uses of this
1137 // variant of OnMessageReceived with the version that takes a
1138 // RenderFrameHost, and then delete it.
nicka0ac8382016-12-15 23:59:231139 if (observer.OnMessageReceived(message))
1140 return true;
[email protected]64ffefa2014-05-10 12:06:331141 }
[email protected]403415a2011-01-10 18:57:531142
Henrique Ferreiroba535472020-04-21 11:38:361143#if BUILDFLAG(ENABLE_PLUGINS)
[email protected]724159a2010-12-30 01:11:181144 bool handled = true;
nicka0ac8382016-12-15 23:59:231145 IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(WebContentsImpl, message, render_view_host)
nicka0ac8382016-12-15 23:59:231146 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission,
1147 OnRequestPpapiBrokerPermission)
nicka0ac8382016-12-15 23:59:231148 IPC_MESSAGE_UNHANDLED(handled = false)
1149 IPC_END_MESSAGE_MAP()
nicka0ac8382016-12-15 23:59:231150 return handled;
Henrique Ferreiroba535472020-04-21 11:38:361151#else
1152 return false;
1153#endif
nicka0ac8382016-12-15 23:59:231154}
1155
1156bool WebContentsImpl::OnMessageReceived(RenderFrameHostImpl* render_frame_host,
1157 const IPC::Message& message) {
Alexander Timin5fdeff22020-09-08 09:20:371158 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnMessageReceived",
1159 "render_frame_host",
1160 base::trace_event::ToTracedValue(render_frame_host));
1161
Alexander Timin90c20c32020-08-12 15:28:321162 for (auto& observer : observers_.observer_list()) {
nicka0ac8382016-12-15 23:59:231163 if (observer.OnMessageReceived(message, render_frame_host))
1164 return true;
1165 }
1166
1167 bool handled = true;
brettw4b461082016-11-19 18:55:161168#if BUILDFLAG(ENABLE_PLUGINS)
Hiroki Nakagawa761b9b02020-07-13 11:12:021169 IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(WebContentsImpl, message, render_frame_host)
emaxxe70f5e12015-05-29 11:26:001170 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceCreated,
1171 OnPepperInstanceCreated)
1172 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceDeleted,
1173 OnPepperInstanceDeleted)
tommyclie6633ca72014-10-31 00:40:421174 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung, OnPepperPluginHung)
zqzhang181047e62016-07-01 13:37:171175 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperStartsPlayback,
1176 OnPepperStartsPlayback)
1177 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperStopsPlayback,
1178 OnPepperStopsPlayback)
tommyclie6633ca72014-10-31 00:40:421179 IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed, OnPluginCrashed)
[email protected]724159a2010-12-30 01:11:181180 IPC_MESSAGE_UNHANDLED(handled = false)
[email protected]e44d1342014-05-16 21:29:331181 IPC_END_MESSAGE_MAP()
Hiroki Nakagawa761b9b02020-07-13 11:12:021182#else
1183 handled = false;
1184#endif
[email protected]724159a2010-12-30 01:11:181185
[email protected]724159a2010-12-30 01:11:181186 return handled;
1187}
1188
[email protected]d1198fd2012-08-13 22:50:191189NavigationControllerImpl& WebContentsImpl::GetController() {
[email protected]f5fa20e2011-12-21 22:35:561190 return controller_;
1191}
1192
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411193BrowserContext* WebContentsImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:551194 return controller_.GetBrowserContext();
[email protected]627e0512011-12-21 22:55:301195}
1196
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411197const GURL& WebContentsImpl::GetURL() {
Peter Boström101d7672018-12-15 00:43:591198 return GetVisibleURL();
[email protected]be1f56ab2011-12-22 06:55:311199}
1200
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411201const GURL& WebContentsImpl::GetVisibleURL() {
[email protected]c854a7e2013-05-21 16:42:241202 // We may not have a navigation entry yet.
[email protected]59167c22013-06-03 18:07:321203 NavigationEntry* entry = controller_.GetVisibleEntry();
[email protected]c854a7e2013-05-21 16:42:241204 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
1205}
1206
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411207const GURL& WebContentsImpl::GetLastCommittedURL() {
[email protected]c854a7e2013-05-21 16:42:241208 // We may not have a navigation entry yet.
1209 NavigationEntry* entry = controller_.GetLastCommittedEntry();
1210 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
1211}
1212
[email protected]8ff00d72012-10-23 19:12:211213WebContentsDelegate* WebContentsImpl::GetDelegate() {
[email protected]be1f56ab2011-12-22 06:55:311214 return delegate_;
1215}
1216
[email protected]8ff00d72012-10-23 19:12:211217void WebContentsImpl::SetDelegate(WebContentsDelegate* delegate) {
Alexander Timin5fdeff22020-09-08 09:20:371218 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetDelegate", "delegate",
1219 delegate);
[email protected]be1f56ab2011-12-22 06:55:311220 // TODO(cbentzel): remove this debugging code?
1221 if (delegate == delegate_)
1222 return;
1223 if (delegate_)
1224 delegate_->Detach(this);
1225 delegate_ = delegate;
[email protected]a6b73c62013-02-11 23:05:081226 if (delegate_) {
[email protected]be1f56ab2011-12-22 06:55:311227 delegate_->Attach(this);
[email protected]a6b73c62013-02-11 23:05:081228 // Ensure the visible RVH reflects the new delegate's preferences.
[email protected]86f98a22013-03-20 14:35:001229 if (view_)
[email protected]e85165c642014-06-10 14:34:311230 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
Joel Einbinder848001c2017-09-19 21:39:311231 if (GetRenderViewHost())
1232 RenderFrameDevToolsAgentHost::WebContentsCreated(this);
[email protected]a6b73c62013-02-11 23:05:081233 }
[email protected]be1f56ab2011-12-22 06:55:311234}
1235
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411236RenderFrameHostImpl* WebContentsImpl::GetMainFrame() {
[email protected]94d0cc12013-12-18 00:07:411237 return frame_tree_.root()->current_frame_host();
[email protected]60eca4eb2013-12-06 00:02:161238}
1239
nick53d5cbf2015-04-23 22:50:141240RenderFrameHostImpl* WebContentsImpl::GetFocusedFrame() {
1241 FrameTreeNode* focused_node = frame_tree_.GetFocusedFrame();
1242 if (!focused_node)
1243 return nullptr;
1244 return focused_node->current_frame_host();
[email protected]9c9343b2014-03-08 02:56:071245}
1246
rob3e2a0732016-01-06 21:22:091247RenderFrameHostImpl* WebContentsImpl::FindFrameByFrameTreeNodeId(
creisf71a2632017-05-04 19:03:501248 int frame_tree_node_id,
1249 int process_id) {
Alexander Timin5fdeff22020-09-08 09:20:371250 OPTIONAL_TRACE_EVENT2(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1251 "WebContentsImpl::FindFrameByFrameTreeNodeId",
1252 "frame_tree_node_id", frame_tree_node_id, "process_id",
1253 process_id);
creisf71a2632017-05-04 19:03:501254 FrameTreeNode* frame = frame_tree_.FindByID(frame_tree_node_id);
1255
1256 // Sanity check that this is in the caller's expected process. Otherwise a
1257 // recent cross-process navigation may have led to a privilege change that the
1258 // caller is not expecting.
1259 if (!frame ||
1260 frame->current_frame_host()->GetProcess()->GetID() != process_id)
1261 return nullptr;
1262
1263 return frame->current_frame_host();
1264}
1265
1266RenderFrameHostImpl* WebContentsImpl::UnsafeFindFrameByFrameTreeNodeId(
rob3e2a0732016-01-06 21:22:091267 int frame_tree_node_id) {
Alexander Timin5fdeff22020-09-08 09:20:371268 OPTIONAL_TRACE_EVENT1("content",
1269 "WebContentsImpl::UnsafeFindFrameByFrameTreeNodeId",
1270 "frame_tree_node_id", frame_tree_node_id);
creisf71a2632017-05-04 19:03:501271 // Beware using this! The RenderFrameHost may have changed since the caller
1272 // obtained frame_tree_node_id.
rob3e2a0732016-01-06 21:22:091273 FrameTreeNode* frame = frame_tree_.FindByID(frame_tree_node_id);
1274 return frame ? frame->current_frame_host() : nullptr;
1275}
1276
[email protected]a86c0e962013-12-17 17:10:391277void WebContentsImpl::ForEachFrame(
Lei Zhangebcc6302018-01-12 19:46:451278 const base::RepeatingCallback<void(RenderFrameHost*)>& on_frame) {
Alexander Timin5fdeff22020-09-08 09:20:371279 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1280 "WebContentsImpl::ForEachFrame");
dcheng57e39e22016-01-21 00:25:381281 for (FrameTreeNode* node : frame_tree_.Nodes()) {
1282 on_frame.Run(node->current_frame_host());
1283 }
[email protected]a86c0e962013-12-17 17:10:391284}
1285
dchengafb53e22016-02-04 08:11:081286std::vector<RenderFrameHost*> WebContentsImpl::GetAllFrames() {
Xuehui Xieb2300ae42020-06-09 20:25:051287 return GetAllFramesImpl(frame_tree_, /*include_pending=*/false);
1288}
1289
1290std::vector<RenderFrameHost*> WebContentsImpl::GetAllFramesIncludingPending() {
1291 return GetAllFramesImpl(frame_tree_, /*include_pending=*/true);
dchengafb53e22016-02-04 08:11:081292}
1293
lukaszacbdf52e2016-01-15 21:19:511294int WebContentsImpl::SendToAllFrames(IPC::Message* message) {
Alexander Timin5fdeff22020-09-08 09:20:371295 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SendToAllFrames");
Xuehui Xieb2300ae42020-06-09 20:25:051296 return SendToAllFramesImpl(frame_tree_, /*include_pending=*/false, message);
1297}
lukasza1a9ab2422016-03-02 18:47:251298
Xuehui Xieb2300ae42020-06-09 20:25:051299int WebContentsImpl::SendToAllFramesIncludingPending(IPC::Message* message) {
Alexander Timin5fdeff22020-09-08 09:20:371300 OPTIONAL_TRACE_EVENT0("content",
1301 "WebContentsImpl::SentToAllFramesIncludingPending");
Xuehui Xieb2300ae42020-06-09 20:25:051302 return SendToAllFramesImpl(frame_tree_, /*include_pending=*/true, message);
[email protected]a86c0e962013-12-17 17:10:391303}
1304
lfgdb5c4ed2016-03-04 23:09:071305void WebContentsImpl::SendPageMessage(IPC::Message* msg) {
Alexander Timin5fdeff22020-09-08 09:20:371306 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SendPageMessage");
alexmos136fd6e62016-08-15 20:58:411307 frame_tree_.root()->render_manager()->SendPageMessage(msg, nullptr);
lfgdb5c4ed2016-03-04 23:09:071308}
1309
Gyuyoung Kim877e86d2020-07-21 04:01:021310void WebContentsImpl::ExecutePageBroadcastMethod(
1311 PageBroadcastMethodCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:371312 OPTIONAL_TRACE_EVENT0("content",
1313 "WebContentsImpl::ExecutePageBroadcastMethod");
Gyuyoung Kim877e86d2020-07-21 04:01:021314 frame_tree_.root()->render_manager()->ExecutePageBroadcastMethod(callback);
1315}
1316
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411317RenderViewHostImpl* WebContentsImpl::GetRenderViewHost() {
[email protected]fa944cb82013-11-15 17:51:211318 return GetRenderManager()->current_host();
[email protected]be1f56ab2011-12-22 06:55:311319}
1320
creis89a0f782015-05-27 16:13:171321void WebContentsImpl::CancelActiveAndPendingDialogs() {
Alexander Timin5fdeff22020-09-08 09:20:371322 OPTIONAL_TRACE_EVENT0("content",
1323 "WebContentsImpl::CancelActiveAndPendingDialogs");
Evan Stade753fc202020-07-13 18:09:541324 if (dialog_manager_) {
avi6879fcf2017-01-21 05:27:531325 dialog_manager_->CancelDialogs(this, /*reset_state=*/false);
Evan Stade753fc202020-07-13 18:09:541326 }
creis89a0f782015-05-27 16:13:171327 if (browser_plugin_embedder_)
1328 browser_plugin_embedder_->CancelGuestDialogs();
1329}
1330
naskoc0fceff2015-04-30 15:53:521331void WebContentsImpl::ClosePage() {
Alexander Timin5fdeff22020-09-08 09:20:371332 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ClosePage");
naskoc0fceff2015-04-30 15:53:521333 GetRenderViewHost()->ClosePage();
1334}
1335
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411336RenderWidgetHostView* WebContentsImpl::GetRenderWidgetHostView() {
[email protected]fa944cb82013-11-15 17:51:211337 return GetRenderManager()->GetRenderWidgetHostView();
[email protected]be1f56ab2011-12-22 06:55:311338}
1339
lfg265a2672016-04-23 03:11:021340RenderWidgetHostView* WebContentsImpl::GetTopLevelRenderWidgetHostView() {
1341 if (GetOuterWebContents())
1342 return GetOuterWebContents()->GetTopLevelRenderWidgetHostView();
1343 return GetRenderManager()->GetRenderWidgetHostView();
1344}
1345
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411346RenderWidgetHostView* WebContentsImpl::GetFullscreenRenderWidgetHostView() {
vmpstr6d9996c82017-02-23 00:43:251347 if (auto* widget_host = GetFullscreenRenderWidgetHost())
ekaramadaeb3c5c2016-11-09 03:22:351348 return widget_host->GetView();
1349 return nullptr;
[email protected]4aebbca2013-09-17 22:26:491350}
1351
[email protected]8ff00d72012-10-23 19:12:211352WebContentsView* WebContentsImpl::GetView() const {
[email protected]be1f56ab2011-12-22 06:55:311353 return view_.get();
1354}
1355
Mike Wasserman5a3cc61d2020-08-27 21:12:031356void WebContentsImpl::OnScreensChange(bool is_multi_screen_changed) {
Alexander Timin5fdeff22020-09-08 09:20:371357 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnScreensChange",
1358 "is_multi_screen_changed", is_multi_screen_changed);
Mike Wasserman5a3cc61d2020-08-27 21:12:031359 // Send |is_multi_screen_changed| events to all visible frames, but limit
1360 // other events to frames with the Window Placement permission. This obviates
1361 // the most pressing need for sites to poll isMultiScreen(), which is exposed
1362 // without explicit permission, while also protecting privacy.
1363 // TODO(crbug.com/1109989): Postpone events; refine utility/privacy balance.
Mike Wassermanb213b9352020-04-16 00:32:341364 for (FrameTreeNode* node : frame_tree_.Nodes()) {
1365 RenderFrameHostImpl* rfh = node->current_frame_host();
Mike Wasserman5a3cc61d2020-08-27 21:12:031366 if ((is_multi_screen_changed &&
1367 rfh->GetVisibilityState() == PageVisibilityState::kVisible) ||
1368 WindowPlacementGranted(rfh)) {
1369 rfh->GetAssociatedLocalFrame()->OnScreensChange();
1370 }
Mike Wassermanb213b9352020-04-16 00:32:341371 }
1372}
1373
leon.han552e9de2017-02-09 14:37:301374void WebContentsImpl::OnScreenOrientationChange() {
Alexander Timin5fdeff22020-09-08 09:20:371375 OPTIONAL_TRACE_EVENT0("content",
1376 "WebContentsImpl::OnScreenOrientationChange");
leon.han552e9de2017-02-09 14:37:301377 DCHECK(screen_orientation_provider_);
Lan Weif81c6e7c2020-02-12 16:46:091378 DidChangeScreenOrientation();
Becca Hughese9e27952018-06-25 17:08:271379 screen_orientation_provider_->OnOrientationChange();
leon.hane4db177a2017-02-07 14:19:161380}
1381
Alan Cutter92d59252019-03-29 02:32:331382base::Optional<SkColor> WebContentsImpl::GetThemeColor() {
Carlos Caballero1215f882019-10-29 15:58:431383 return GetRenderViewHost()->theme_color();
yusufod41c5f92015-03-06 00:14:281384}
1385
Alan Cutterd73a15d92020-08-21 07:12:451386base::Optional<SkColor> WebContentsImpl::GetBackgroundColor() {
1387 return GetRenderViewHost()->background_color();
1388}
1389
Doug Turner63f3c7b2017-07-29 05:10:011390void WebContentsImpl::SetAccessibilityMode(ui::AXMode mode) {
Alexander Timin5fdeff22020-09-08 09:20:371391 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetAccessibilityMode",
1392 "mode", mode.ToString(), "previous_mode",
1393 accessibility_mode_.ToString());
1394
[email protected]95640212014-07-26 18:14:301395 if (mode == accessibility_mode_)
1396 return;
1397
dmazzonif8a31042016-12-03 00:52:131398 // Don't allow accessibility to be enabled for WebContents that are never
danakj77eb7e82020-01-09 19:38:461399 // user-visible, like background pages.
1400 if (IsNeverComposited())
dmazzonif8a31042016-12-03 00:52:131401 return;
1402
[email protected]95640212014-07-26 18:14:301403 accessibility_mode_ = mode;
dcheng57e39e22016-01-21 00:25:381404
1405 for (FrameTreeNode* node : frame_tree_.Nodes()) {
dmazzonif8a31042016-12-03 00:52:131406 UpdateAccessibilityModeOnFrame(node->current_frame_host());
clamy610c63b32017-12-22 15:05:181407 // Also update accessibility mode on the speculative RenderFrameHost for
1408 // this FrameTreeNode, if one exists.
Alex Moshchuk3d8a1f392017-10-24 19:01:261409 RenderFrameHost* speculative_frame_host =
1410 node->render_manager()->speculative_frame_host();
1411 if (speculative_frame_host)
1412 UpdateAccessibilityModeOnFrame(speculative_frame_host);
dcheng57e39e22016-01-21 00:25:381413 }
[email protected]95640212014-07-26 18:14:301414}
1415
Doug Turner63f3c7b2017-07-29 05:10:011416void WebContentsImpl::AddAccessibilityMode(ui::AXMode mode) {
1417 ui::AXMode new_mode(accessibility_mode_);
dougtcd3dad732017-03-14 03:26:231418 new_mode |= mode;
1419 SetAccessibilityMode(new_mode);
[email protected]95640212014-07-26 18:14:301420}
1421
Avi Drissman1e620f32018-03-16 13:57:291422// Helper class used by WebContentsImpl::RequestAXTreeSnapshot.
1423// Handles the callbacks from parallel snapshot requests to each frame,
1424// and feeds the results to an AXTreeCombiner, which converts them into a
1425// single combined accessibility tree.
1426class WebContentsImpl::AXTreeSnapshotCombiner
1427 : public base::RefCounted<AXTreeSnapshotCombiner> {
1428 public:
1429 explicit AXTreeSnapshotCombiner(AXTreeSnapshotCallback callback)
1430 : callback_(std::move(callback)) {}
1431
1432 AXTreeSnapshotCallback AddFrame(bool is_root) {
1433 // Adds a reference to |this|.
1434 return base::BindOnce(&AXTreeSnapshotCombiner::ReceiveSnapshot, this,
1435 is_root);
1436 }
1437
1438 void ReceiveSnapshot(bool is_root, const ui::AXTreeUpdate& snapshot) {
1439 combiner_.AddTree(snapshot, is_root);
1440 }
1441
1442 private:
1443 friend class base::RefCounted<AXTreeSnapshotCombiner>;
1444
1445 // This is called automatically after the last call to ReceiveSnapshot
1446 // when there are no more references to this object.
1447 ~AXTreeSnapshotCombiner() {
1448 combiner_.Combine();
1449 std::move(callback_).Run(combiner_.combined());
1450 }
1451
1452 ui::AXTreeCombiner combiner_;
1453 AXTreeSnapshotCallback callback_;
1454};
1455
1456void WebContentsImpl::RequestAXTreeSnapshot(AXTreeSnapshotCallback callback,
1457 ui::AXMode ax_mode) {
Alexander Timin5fdeff22020-09-08 09:20:371458 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RequestAXTreeSnapshot",
1459 "mode", ax_mode.ToString());
dmazzonid95ae842016-04-12 21:17:391460 // Send a request to each of the frames in parallel. Each one will return
1461 // an accessibility tree snapshot, and AXTreeSnapshotCombiner will combine
1462 // them into a single tree and call |callback| with that result, then
1463 // delete |combiner|.
Avi Drissman1e620f32018-03-16 13:57:291464 FrameTreeNode* root_node = frame_tree_.root();
tzik58faa742018-08-01 10:54:181465 auto combiner =
1466 base::MakeRefCounted<AXTreeSnapshotCombiner>(std::move(callback));
Avi Drissman1e620f32018-03-16 13:57:291467
tzik58faa742018-08-01 10:54:181468 RecursiveRequestAXTreeSnapshotOnFrame(root_node, combiner.get(), ax_mode);
Avi Drissman1e620f32018-03-16 13:57:291469}
1470
1471void WebContentsImpl::RecursiveRequestAXTreeSnapshotOnFrame(
1472 FrameTreeNode* root_node,
1473 AXTreeSnapshotCombiner* combiner,
1474 ui::AXMode ax_mode) {
Alexander Timin5fdeff22020-09-08 09:20:371475 OPTIONAL_TRACE_EVENT0(
1476 "content", "WebContentsImpl::RecursiveRequestAXTreeSnapshotOnFrame");
dmazzonid95ae842016-04-12 21:17:391477 for (FrameTreeNode* frame_tree_node : frame_tree_.Nodes()) {
Avi Drissman1e620f32018-03-16 13:57:291478 WebContentsImpl* inner_contents =
1479 node_.GetInnerWebContentsInFrame(frame_tree_node);
1480 if (inner_contents) {
1481 inner_contents->RecursiveRequestAXTreeSnapshotOnFrame(root_node, combiner,
1482 ax_mode);
1483 } else {
1484 bool is_root = frame_tree_node == root_node;
1485 frame_tree_node->current_frame_host()->RequestAXTreeSnapshot(
1486 combiner->AddFrame(is_root), ax_mode);
1487 }
dmazzonid95ae842016-04-12 21:17:391488 }
dmazzoni83ba5c82015-04-14 07:11:511489}
1490
Becca Hughes3b5a43482018-07-17 22:31:551491void WebContentsImpl::NotifyViewportFitChanged(
1492 blink::mojom::ViewportFit value) {
Alexander Timin5fdeff22020-09-08 09:20:371493 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::NotifyViewportFitChanged",
1494 "value", static_cast<int>(value));
Alexander Timin90c20c32020-08-12 15:28:321495 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1496 observer->ViewportFitChanged(value);
1497 });
Becca Hughes3b5a43482018-07-17 22:31:551498}
1499
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411500FindRequestManager* WebContentsImpl::GetFindRequestManagerForTesting() {
Ehsan Karamad6beb2ea2018-11-25 18:15:131501 return GetFindRequestManager();
1502}
1503
mcnee336ea2c2017-05-23 22:50:591504#if !defined(OS_ANDROID)
akabac6bd1212018-06-25 20:10:481505void WebContentsImpl::UpdateZoom() {
Alexander Timin5fdeff22020-09-08 09:20:371506 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::UpdateZoom");
akabac6bd1212018-06-25 20:10:481507 RenderWidgetHostImpl* rwh = GetRenderViewHost()->GetWidget();
1508 if (rwh->GetView())
1509 rwh->SynchronizeVisualProperties();
wjmaclean64951902016-04-29 20:59:121510}
1511
wjmaclean64951902016-04-29 20:59:121512
1513void WebContentsImpl::UpdateZoomIfNecessary(const std::string& scheme,
akabac6bd1212018-06-25 20:10:481514 const std::string& host) {
Alexander Timin5fdeff22020-09-08 09:20:371515 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::UpdateZoomIfNecessary",
1516 "scheme", scheme, "host", host);
wjmaclean64951902016-04-29 20:59:121517 NavigationEntry* entry = GetController().GetLastCommittedEntry();
1518 if (!entry)
1519 return;
1520
1521 GURL url = HostZoomMap::GetURLFromEntry(entry);
1522 if (host != net::GetHostOrSpecFromURL(url) ||
1523 (!scheme.empty() && !url.SchemeIs(scheme))) {
1524 return;
1525 }
1526
akabac6bd1212018-06-25 20:10:481527 UpdateZoom();
wjmaclean64951902016-04-29 20:59:121528}
mcnee336ea2c2017-05-23 22:50:591529#endif // !defined(OS_ANDROID)
wjmaclean64951902016-04-29 20:59:121530
Julie Jeongeun Kim7d0986172019-12-04 03:17:251531base::OnceClosure WebContentsImpl::AddReceiverSet(
rockotf62002a2016-09-15 00:08:591532 const std::string& interface_name,
Julie Jeongeun Kim7d0986172019-12-04 03:17:251533 WebContentsReceiverSet* receiver_set) {
Alexander Timin5fdeff22020-09-08 09:20:371534 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::AddReceiverSet",
1535 "interface_name", interface_name);
rockotf62002a2016-09-15 00:08:591536 auto result =
Julie Jeongeun Kim7d0986172019-12-04 03:17:251537 receiver_sets_.insert(std::make_pair(interface_name, receiver_set));
rockotf62002a2016-09-15 00:08:591538 DCHECK(result.second);
Julie Jeongeun Kim7d0986172019-12-04 03:17:251539 return base::BindOnce(&WebContentsImpl::RemoveReceiverSet,
danakjf4b9e942019-11-29 15:43:041540 weak_factory_.GetWeakPtr(), interface_name);
rockotf62002a2016-09-15 00:08:591541}
1542
Julie Jeongeun Kim7d0986172019-12-04 03:17:251543WebContentsReceiverSet* WebContentsImpl::GetReceiverSet(
rockot8bbad222017-03-22 04:34:051544 const std::string& interface_name) {
Julie Jeongeun Kim7d0986172019-12-04 03:17:251545 auto it = receiver_sets_.find(interface_name);
1546 if (it == receiver_sets_.end())
rockot8bbad222017-03-22 04:34:051547 return nullptr;
1548 return it->second;
1549}
1550
John Delaney732721e92020-02-07 23:11:271551void WebContentsImpl::RemoveReceiverSetForTesting(
1552 const std::string& interface_name) {
Alexander Timin5fdeff22020-09-08 09:20:371553 OPTIONAL_TRACE_EVENT1("content",
1554 "WebContentsImpl::RemoveReceiverSetForTesting",
1555 "interface_name", interface_name);
John Delaney732721e92020-02-07 23:11:271556 RemoveReceiverSet(interface_name);
1557}
1558
paulmeyerfeafc2d2017-04-25 21:46:401559std::vector<WebContentsImpl*> WebContentsImpl::GetWebContentsAndAllInner() {
1560 std::vector<WebContentsImpl*> all_contents(1, this);
1561
1562 for (size_t i = 0; i != all_contents.size(); ++i) {
1563 for (auto* inner_contents : all_contents[i]->GetInnerWebContents()) {
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:161564 all_contents.push_back(static_cast<WebContentsImpl*>(inner_contents));
paulmeyerfeafc2d2017-04-25 21:46:401565 }
1566 }
1567
1568 return all_contents;
1569}
1570
Sam McNally145fb172017-05-10 00:13:231571void WebContentsImpl::NotifyManifestUrlChanged(
Yuzu Saijo0c263c702020-06-08 03:41:241572 RenderFrameHost* rfh,
Sam McNally145fb172017-05-10 00:13:231573 const base::Optional<GURL>& manifest_url) {
Alexander Timin5fdeff22020-09-08 09:20:371574 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::NotifyManifestUrlChanged",
1575 "render_frame_host",
1576 base::trace_event::ToTracedValue(rfh), "manifest_url",
1577 base::trace_event::ValueToString(manifest_url));
Alexander Timin90c20c32020-08-12 15:28:321578 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1579 observer->DidUpdateWebManifestURL(rfh, manifest_url);
1580 });
Sam McNally145fb172017-05-10 00:13:231581}
1582
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411583WebUI* WebContentsImpl::GetWebUI() {
Nasko Oskov2f7d2112019-10-29 03:26:571584 WebUI* committed_web_ui = GetCommittedWebUI();
1585 if (committed_web_ui)
1586 return committed_web_ui;
1587
1588 if (GetRenderManager()->speculative_frame_host())
1589 return GetRenderManager()->speculative_frame_host()->web_ui();
1590
1591 return nullptr;
[email protected]be1f56ab2011-12-22 06:55:311592}
1593
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411594WebUI* WebContentsImpl::GetCommittedWebUI() {
carlosk35f35af2015-12-01 10:55:401595 return frame_tree_.root()->current_frame_host()->web_ui();
[email protected]d5f942ba2008-09-26 19:30:341596}
1597
Maks Orlovich73f374d2020-04-02 12:46:131598void WebContentsImpl::SetUserAgentOverride(
1599 const blink::UserAgentOverride& ua_override,
1600 bool override_in_new_tabs) {
Alexander Timin5fdeff22020-09-08 09:20:371601 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetUserAgentOverride",
1602 "ua_override", ua_override.ua_string_override,
1603 "override_in_new_tabs", override_in_new_tabs);
Maks Orlovich73f374d2020-04-02 12:46:131604 DCHECK(!ua_override.ua_metadata_override.has_value() ||
1605 !ua_override.ua_string_override.empty());
1606
1607 if (GetUserAgentOverride() == ua_override)
[email protected]bf70edce2012-06-20 22:32:221608 return;
1609
Changwan Ryuc1134a82018-03-07 02:10:141610 should_override_user_agent_in_new_tabs_ = override_in_new_tabs;
1611
Maks Orlovich73f374d2020-04-02 12:46:131612 renderer_preferences_.user_agent_override = ua_override;
[email protected]bf70edce2012-06-20 22:32:221613
Bruce Long1e3e1f542019-10-16 17:56:281614 // Send the new override string to all renderers in the current page.
1615 SyncRendererPrefs();
[email protected]bf70edce2012-06-20 22:32:221616
1617 // Reload the page if a load is currently in progress to avoid having
1618 // different parts of the page loaded using different user agents.
Scott Violete1d58cc2020-04-28 23:07:171619 // No need to reload if the current entry matches that of the
1620 // NavigationRequest supplied to DidStartNavigation() as NavigationRequest
1621 // handles it.
[email protected]6286a372013-10-09 04:03:271622 NavigationEntry* entry = controller_.GetVisibleEntry();
Scott Violete1d58cc2020-04-28 23:07:171623 if (IsLoading() && entry != nullptr && entry->GetIsOverridingUserAgent() &&
1624 (!frame_tree_.root()->navigation_request() ||
1625 frame_tree_.root()->navigation_request()->ua_change_requires_reload())) {
toyoshim6142d96f2016-12-19 09:07:251626 controller_.Reload(ReloadType::BYPASSING_CACHE, true);
Scott Violete1d58cc2020-04-28 23:07:171627 }
[email protected]8d0f3312012-08-18 01:47:531628
Alexander Timin90c20c32020-08-12 15:28:321629 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1630 observer->UserAgentOverrideSet(ua_override);
1631 });
[email protected]86ef6a392012-05-11 22:03:111632}
1633
Scott Violet2a6c5bff2020-04-29 23:59:061634void WebContentsImpl::SetRendererInitiatedUserAgentOverrideOption(
1635 NavigationController::UserAgentOverrideOption option) {
Alexander Timin5fdeff22020-09-08 09:20:371636 OPTIONAL_TRACE_EVENT0(
1637 "content",
1638 "WebContentsImpl::SetRendererInitiatedUserAgentOverrideOption");
Scott Violet2a6c5bff2020-04-29 23:59:061639 renderer_initiated_user_agent_override_option_ = option;
1640}
1641
Maks Orlovich73f374d2020-04-02 12:46:131642const blink::UserAgentOverride& WebContentsImpl::GetUserAgentOverride() {
[email protected]bf70edce2012-06-20 22:32:221643 return renderer_preferences_.user_agent_override;
[email protected]86ef6a392012-05-11 22:03:111644}
1645
Scott Violet2a6c5bff2020-04-29 23:59:061646bool WebContentsImpl::ShouldOverrideUserAgentForRendererInitiatedNavigation() {
1647 NavigationEntryImpl* current_entry = controller_.GetLastCommittedEntry();
1648 if (!current_entry)
1649 return should_override_user_agent_in_new_tabs_;
1650
1651 switch (renderer_initiated_user_agent_override_option_) {
1652 case NavigationController::UA_OVERRIDE_INHERIT:
1653 return current_entry->GetIsOverridingUserAgent();
1654 case NavigationController::UA_OVERRIDE_TRUE:
1655 return true;
1656 case NavigationController::UA_OVERRIDE_FALSE:
1657 return false;
1658 default:
1659 break;
1660 }
1661 return false;
Changwan Ryuc1134a82018-03-07 02:10:141662}
1663
dmazzonidd3d51a72016-12-14 18:41:011664void WebContentsImpl::EnableWebContentsOnlyAccessibilityMode() {
Alexander Timin5fdeff22020-09-08 09:20:371665 OPTIONAL_TRACE_EVENT0(
1666 "content", "WebContentsImpl::EnableWebContentsOnlyAccessibilityMode");
Dominic Mazzonid9fda172019-03-07 17:12:071667 // If accessibility is already enabled, we'll need to force a reset
1668 // in order to ensure new observers of accessibility events get the
1669 // full accessibility tree from scratch.
1670 bool need_reset = GetAccessibilityMode().has_mode(ui::AXMode::kWebContents);
1671
1672 ui::AXMode desired_mode =
1673 GetContentClient()->browser()->GetAXModeForBrowserContext(
1674 GetBrowserContext());
1675 desired_mode |= ui::kAXModeWebContentsOnly;
1676 AddAccessibilityMode(desired_mode);
1677
1678 if (need_reset) {
dchengafb53e22016-02-04 08:11:081679 for (RenderFrameHost* rfh : GetAllFrames())
1680 ResetAccessibility(rfh);
dchengafb53e22016-02-04 08:11:081681 }
[email protected]95640212014-07-26 18:14:301682}
1683
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411684bool WebContentsImpl::IsWebContentsOnlyAccessibilityModeForTesting() {
Doug Turner63f3c7b2017-07-29 05:10:011685 return accessibility_mode_ == ui::kAXModeWebContentsOnly;
[email protected]95640212014-07-26 18:14:301686}
1687
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411688bool WebContentsImpl::IsFullAccessibilityModeForTesting() {
Doug Turner63f3c7b2017-07-29 05:10:011689 return accessibility_mode_ == ui::kAXModeComplete;
[email protected]95640212014-07-26 18:14:301690}
1691
Becca Hughes6daf5662018-06-27 16:50:541692#if defined(OS_ANDROID)
1693
1694void WebContentsImpl::SetDisplayCutoutSafeArea(gfx::Insets insets) {
Alexander Timin5fdeff22020-09-08 09:20:371695 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetDisplayCutoutSafeArea");
Becca Hughes86334622018-07-09 21:29:381696 if (display_cutout_host_impl_)
1697 display_cutout_host_impl_->SetDisplayCutoutSafeArea(insets);
Becca Hughes6daf5662018-06-27 16:50:541698}
1699
1700#endif
1701
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411702const base::string16& WebContentsImpl::GetTitle() {
Nasko Oskov2f7d2112019-10-29 03:26:571703 WebUI* our_web_ui =
1704 GetRenderManager()->speculative_frame_host()
1705 ? GetRenderManager()->speculative_frame_host()->web_ui()
1706 : GetRenderManager()->current_frame_host()->web_ui();
[email protected]7ade2732011-02-10 00:13:581707 if (our_web_ui) {
[email protected]96d185d2009-04-24 03:28:541708 // Don't override the title in view source mode.
Carlos IL4dea8902020-05-26 15:14:291709 NavigationEntry* entry = controller_.GetVisibleEntry();
[email protected]96d185d2009-04-24 03:28:541710 if (!(entry && entry->IsViewSourceMode())) {
[email protected]e0112912011-02-02 22:54:351711 // Give the Web UI the chance to override our title.
[email protected]fcf75d42013-12-03 20:11:261712 const base::string16& title = our_web_ui->GetOverriddenTitle();
[email protected]96d185d2009-04-24 03:28:541713 if (!title.empty())
1714 return title;
1715 }
1716 }
1717
1718 // We use the title for the last committed entry rather than a pending
1719 // navigation entry. For example, when the user types in a URL, we want to
1720 // keep the old page's title until the new load has committed and we get a new
1721 // title.
Carlos IL4dea8902020-05-26 15:14:291722 NavigationEntry* entry = controller_.GetLastCommittedEntry();
[email protected]59167c22013-06-03 18:07:321723
creis072b61f2015-09-28 20:52:241724 // We make an exception for initial navigations. We only want to use the title
1725 // from the visible entry if:
1726 // 1. The pending entry has been explicitly assigned a title to display.
1727 // 2. The user is doing a history navigation in a new tab (e.g., Ctrl+Back),
1728 // which case there is a pending entry index other than -1.
1729 //
1730 // Otherwise, we want to stick with the last committed entry's title during
1731 // new navigations, which have pending entries at index -1 with no title.
1732 if (controller_.IsInitialNavigation() &&
1733 ((controller_.GetVisibleEntry() &&
1734 !controller_.GetVisibleEntry()->GetTitle().empty()) ||
1735 controller_.GetPendingEntryIndex() != -1)) {
1736 entry = controller_.GetVisibleEntry();
[email protected]9eeafc012013-11-25 23:49:471737 }
[email protected]59167c22013-06-03 18:07:321738
[email protected]45d0ef7f2011-01-05 13:46:231739 if (entry) {
jshin1fb76462016-04-05 22:13:031740 return entry->GetTitleForDisplay();
[email protected]45d0ef7f2011-01-05 13:46:231741 }
[email protected]987fc3a2011-05-26 14:18:091742
1743 // |page_title_when_no_navigation_entry_| is finally used
1744 // if no title cannot be retrieved.
1745 return page_title_when_no_navigation_entry_;
[email protected]96d185d2009-04-24 03:28:541746}
1747
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411748SiteInstanceImpl* WebContentsImpl::GetSiteInstance() {
[email protected]fa944cb82013-11-15 17:51:211749 return GetRenderManager()->current_host()->GetSiteInstance();
[email protected]96d185d2009-04-24 03:28:541750}
1751
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411752bool WebContentsImpl::IsLoading() {
Carlos ILd51e7702020-05-07 18:51:391753 return frame_tree_.IsLoading();
[email protected]3c9e1872010-11-18 16:17:491754}
1755
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411756double WebContentsImpl::GetLoadProgress() {
Peter Boström18a40fa2018-10-31 19:03:501757 return frame_tree_.load_progress();
1758}
1759
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411760bool WebContentsImpl::IsLoadingToDifferentDocument() {
clamy44e84ce2016-02-22 15:38:251761 return IsLoading() && is_load_to_different_document_;
[email protected]6dfed692014-05-22 04:18:031762}
1763
Alexander Timindd0fa0c52019-11-06 13:03:371764bool WebContentsImpl::IsDocumentOnLoadCompletedInMainFrame() {
1765 return GetRenderViewHost()->IsDocumentOnLoadCompletedInMainFrame();
1766}
1767
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411768bool WebContentsImpl::IsWaitingForResponse() {
Peter Boströma9a27f6e2018-11-21 13:12:191769 NavigationRequest* ongoing_navigation_request =
1770 frame_tree_.root()->navigation_request();
1771
1772 // An ongoing navigation request means we're waiting for a response.
1773 return ongoing_navigation_request != nullptr;
[email protected]be1f56ab2011-12-22 06:55:311774}
1775
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411776const net::LoadStateWithParam& WebContentsImpl::GetLoadState() {
[email protected]be1f56ab2011-12-22 06:55:311777 return load_state_;
1778}
1779
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411780const base::string16& WebContentsImpl::GetLoadStateHost() {
[email protected]be1f56ab2011-12-22 06:55:311781 return load_state_host_;
1782}
1783
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411784uint64_t WebContentsImpl::GetUploadSize() {
[email protected]be1f56ab2011-12-22 06:55:311785 return upload_size_;
1786}
1787
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411788uint64_t WebContentsImpl::GetUploadPosition() {
[email protected]be1f56ab2011-12-22 06:55:311789 return upload_position_;
1790}
1791
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411792const std::string& WebContentsImpl::GetEncoding() {
Alexander Timine5f20e22019-10-09 23:22:351793 return GetMainFrame()->GetEncoding();
[email protected]be1f56ab2011-12-22 06:55:311794}
1795
Charles Zhaod72f99d2018-09-17 14:18:271796bool WebContentsImpl::WasDiscarded() {
1797 return GetFrameTree()->root()->was_discarded();
1798}
1799
Shubhie Panickerddf2a4e2018-03-06 00:09:061800void WebContentsImpl::SetWasDiscarded(bool was_discarded) {
1801 GetFrameTree()->root()->set_was_discarded();
1802}
1803
Collin Bakerc5259962019-11-14 17:51:581804void WebContentsImpl::IncrementCapturerCount(const gfx::Size& capture_size,
1805 bool stay_hidden) {
Alexander Timin5fdeff22020-09-08 09:20:371806 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::IncrementCapturerCount");
[email protected]5a652232013-02-12 06:15:251807 DCHECK(!is_being_destroyed_);
Xianzhu Wang724e08f2020-09-01 21:35:071808 if (stay_hidden) {
1809 // A hidden capture should not have side effect on the web contents, so it
1810 // should not pass a non-empty |capture_size| which will cause side effect.
1811 DCHECK(capture_size.IsEmpty());
Collin Bakerc5259962019-11-14 17:51:581812 ++hidden_capturer_count_;
Xianzhu Wang724e08f2020-09-01 21:35:071813 } else {
Collin Bakerc5259962019-11-14 17:51:581814 ++visible_capturer_count_;
Xianzhu Wang724e08f2020-09-01 21:35:071815 }
[email protected]222f5822014-02-05 23:40:491816
1817 // Note: This provides a hint to upstream code to size the views optimally
1818 // for quality (e.g., to avoid scaling).
1819 if (!capture_size.IsEmpty() && preferred_size_for_capture_.IsEmpty()) {
1820 preferred_size_for_capture_ = capture_size;
1821 OnPreferredSizeChanged(preferred_size_);
1822 }
ccameron8807c38f2015-01-17 00:29:191823
Collin Bakerc5259962019-11-14 17:51:581824 UpdateVisibilityAndNotifyPageAndView(GetVisibility());
[email protected]54597982013-02-06 01:59:551825}
1826
Collin Bakerc5259962019-11-14 17:51:581827void WebContentsImpl::DecrementCapturerCount(bool stay_hidden) {
Alexander Timin5fdeff22020-09-08 09:20:371828 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DecrementCapturerCount");
Collin Bakerc5259962019-11-14 17:51:581829 if (stay_hidden)
1830 --hidden_capturer_count_;
1831 else
1832 --visible_capturer_count_;
1833 DCHECK_GE(hidden_capturer_count_, 0);
1834 DCHECK_GE(visible_capturer_count_, 0);
[email protected]54597982013-02-06 01:59:551835
[email protected]5a652232013-02-12 06:15:251836 if (is_being_destroyed_)
1837 return;
1838
Francois Doray24fc62c2017-12-11 17:27:331839 if (!IsBeingCaptured()) {
[email protected]222f5822014-02-05 23:40:491840 const gfx::Size old_size = preferred_size_for_capture_;
1841 preferred_size_for_capture_ = gfx::Size();
1842 OnPreferredSizeChanged(old_size);
[email protected]54597982013-02-06 01:59:551843 }
Collin Bakerc5259962019-11-14 17:51:581844
1845 UpdateVisibilityAndNotifyPageAndView(GetVisibility());
[email protected]be1f56ab2011-12-22 06:55:311846}
1847
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411848bool WebContentsImpl::IsBeingCaptured() {
Collin Bakerc5259962019-11-14 17:51:581849 return visible_capturer_count_ + hidden_capturer_count_ > 0;
[email protected]f2bd40812013-07-20 04:30:441850}
1851
Xianzhu Wangc61434c2020-08-21 19:17:301852bool WebContentsImpl::IsBeingVisiblyCaptured() {
1853 return visible_capturer_count_ > 0;
1854}
1855
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411856bool WebContentsImpl::IsAudioMuted() {
Guido Urdanetaf8372942019-11-15 09:47:211857 return audio_stream_factory_ && audio_stream_factory_->IsMuted();
miu50f97892014-09-22 22:49:521858}
1859
1860void WebContentsImpl::SetAudioMuted(bool mute) {
Alexander Timin5fdeff22020-09-08 09:20:371861 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetAudioMuted", "mute",
1862 mute);
miu50f97892014-09-22 22:49:521863 DVLOG(1) << "SetAudioMuted(mute=" << mute << "), was " << IsAudioMuted()
1864 << " for WebContentsImpl@" << this;
1865
1866 if (mute == IsAudioMuted())
1867 return;
1868
Guido Urdanetaf8372942019-11-15 09:47:211869 GetAudioStreamFactory()->SetMuted(mute);
miu50f97892014-09-22 22:49:521870
Alexander Timin90c20c32020-08-12 15:28:321871 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1872 observer->DidUpdateAudioMutingState(mute);
1873 });
Jan Rucka442c83f2017-08-08 13:27:541874 // Notification for UI updates in response to the changed muting state.
Collin Bakeraf540cf2019-09-20 20:54:161875 NotifyNavigationStateChanged(INVALIDATE_TYPE_AUDIO);
Jan Rucka442c83f2017-08-08 13:27:541876}
1877
1878bool WebContentsImpl::IsCurrentlyAudible() {
Chris Hamiltondf0d72cd2018-05-29 16:23:531879 return is_currently_audible_;
miu50f97892014-09-22 22:49:521880}
1881
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411882bool WebContentsImpl::IsConnectedToBluetoothDevice() {
ortunodf4d7982016-04-08 02:33:351883 return bluetooth_connected_device_count_ > 0;
ortuno32e7db3c2016-03-29 16:14:201884}
1885
Ovidio Henriquez76696f62020-07-08 03:06:591886bool WebContentsImpl::IsScanningForBluetoothDevices() {
1887 return bluetooth_scanning_sessions_count_ > 0;
1888}
1889
Lucas Furukawa Gadani4b4eed02019-06-04 23:12:041890bool WebContentsImpl::IsConnectedToSerialPort() {
Reilly Grant5e7c79b22019-04-09 17:26:201891 return serial_active_frame_count_ > 0;
1892}
1893
Matt Reynoldse8c6c1f2019-11-02 09:53:531894bool WebContentsImpl::IsConnectedToHidDevice() {
1895 return hid_active_frame_count_ > 0;
1896}
1897
Marijn Kruisselbrink29051042019-08-06 22:56:551898bool WebContentsImpl::HasNativeFileSystemHandles() {
1899 return native_file_system_handle_count_ > 0;
1900}
Marijn Kruisselbrinkf1714aa22019-07-02 03:45:331901
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411902bool WebContentsImpl::HasPictureInPictureVideo() {
sawtellea7333a82018-05-31 02:36:361903 return has_picture_in_picture_video_;
1904}
1905
1906void WebContentsImpl::SetHasPictureInPictureVideo(
1907 bool has_picture_in_picture_video) {
Alexander Timin5fdeff22020-09-08 09:20:371908 OPTIONAL_TRACE_EVENT1("content",
1909 "WebContentsImpl::SetHasPictureInPictureVideo",
1910 "has_pip_video", has_picture_in_picture_video);
sawtellea7333a82018-05-31 02:36:361911 // If status of |this| is already accurate, there is no need to update.
1912 if (has_picture_in_picture_video == has_picture_in_picture_video_)
1913 return;
1914 has_picture_in_picture_video_ = has_picture_in_picture_video;
1915 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
Alexander Timin90c20c32020-08-12 15:28:321916 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1917 observer->MediaPictureInPictureChanged(has_picture_in_picture_video_);
1918 });
sawtellea7333a82018-05-31 02:36:361919}
1920
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411921bool WebContentsImpl::IsCrashed() {
Dominic Mazzoni73a48322018-05-25 18:14:071922 switch (crashed_status_) {
1923 case base::TERMINATION_STATUS_PROCESS_CRASHED:
1924 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
1925 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED:
1926 case base::TERMINATION_STATUS_OOM:
1927 case base::TERMINATION_STATUS_LAUNCH_FAILED:
Darin Fisher6cf20e782020-08-07 22:25:361928#if defined(OS_CHROMEOS) || BUILDFLAG(IS_LACROS)
Dominic Mazzoni73a48322018-05-25 18:14:071929 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM:
oshima620225722015-06-04 19:45:271930#endif
Dominic Mazzoni73a48322018-05-25 18:14:071931#if defined(OS_ANDROID)
1932 case base::TERMINATION_STATUS_OOM_PROTECTED:
1933#endif
Will Harris07925d12019-10-31 03:03:051934#if defined(OS_WIN)
1935 case base::TERMINATION_STATUS_INTEGRITY_FAILURE:
1936#endif
Dominic Mazzoni73a48322018-05-25 18:14:071937 return true;
1938 case base::TERMINATION_STATUS_NORMAL_TERMINATION:
1939 case base::TERMINATION_STATUS_STILL_RUNNING:
1940 return false;
1941 case base::TERMINATION_STATUS_MAX_ENUM:
1942 NOTREACHED();
1943 return false;
1944 }
1945
1946 NOTREACHED();
1947 return false;
[email protected]3c9e1872010-11-18 16:17:491948}
1949
[email protected]b172aee2012-04-10 17:05:261950void WebContentsImpl::SetIsCrashed(base::TerminationStatus status,
1951 int error_code) {
Alexander Timin5fdeff22020-09-08 09:20:371952 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetIsCrashed", "status",
1953 static_cast<int>(status), "old_status",
1954 static_cast<int>(crashed_status_));
[email protected]443b80e2010-12-14 00:42:231955 if (status == crashed_status_)
[email protected]d5f942ba2008-09-26 19:30:341956 return;
1957
[email protected]443b80e2010-12-14 00:42:231958 crashed_status_ = status;
1959 crashed_error_code_ = error_code;
[email protected]8ff00d72012-10-23 19:12:211960 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
[email protected]d5f942ba2008-09-26 19:30:341961}
1962
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411963base::TerminationStatus WebContentsImpl::GetCrashedStatus() {
[email protected]be1f56ab2011-12-22 06:55:311964 return crashed_status_;
1965}
1966
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411967int WebContentsImpl::GetCrashedErrorCode() {
afakhry98241832016-03-11 19:27:471968 return crashed_error_code_;
1969}
1970
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411971bool WebContentsImpl::IsBeingDestroyed() {
[email protected]be1f56ab2011-12-22 06:55:311972 return is_being_destroyed_;
1973}
1974
[email protected]7f924832014-08-09 05:57:221975void WebContentsImpl::NotifyNavigationStateChanged(
1976 InvalidateTypes changed_flags) {
Alexander Timin5fdeff22020-09-08 09:20:371977 TRACE_EVENT1("content,navigation",
1978 "WebContentsImpl::NotifyNavigationStateChanged", "changed_flags",
1979 static_cast<int>(changed_flags));
dalecurtis88c240072015-12-09 02:11:181980 // Notify the media observer of potential audibility changes.
Collin Bakeraf540cf2019-09-20 20:54:161981 if (changed_flags & INVALIDATE_TYPE_AUDIO) {
mlamouri44e4ef42016-01-20 18:42:271982 media_web_contents_observer_->MaybeUpdateAudibleState();
dalecurtisbc6572e12014-09-12 19:22:301983 }
1984
[email protected]d5f942ba2008-09-26 19:30:341985 if (delegate_)
1986 delegate_->NavigationStateChanged(this, changed_flags);
wjmaclean1dabf3e32016-05-13 23:34:441987
1988 if (GetOuterWebContents())
1989 GetOuterWebContents()->NotifyNavigationStateChanged(changed_flags);
[email protected]d5f942ba2008-09-26 19:30:341990}
1991
W. James MacLean6f34b042019-07-12 19:25:301992RenderFrameHostImpl* WebContentsImpl::GetFocusedFrameFromFocusedDelegate() {
1993 FrameTreeNode* focused_node =
1994 GetFocusedWebContents()->frame_tree_.GetFocusedFrame();
1995 return focused_node ? focused_node->current_frame_host() : nullptr;
1996}
1997
David Black9cca3592019-11-06 23:02:221998void WebContentsImpl::OnVerticalScrollDirectionChanged(
1999 viz::VerticalScrollDirection scroll_direction) {
Alexander Timin5fdeff22020-09-08 09:20:372000 OPTIONAL_TRACE_EVENT1("content",
2001 "WebContentsImpl::OnVerticalScrollDirectionChanged",
2002 "scroll_direction", static_cast<int>(scroll_direction));
Alexander Timin90c20c32020-08-12 15:28:322003 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2004 observer->DidChangeVerticalScrollDirection(scroll_direction);
2005 });
David Black9cca3592019-11-06 23:02:222006}
2007
Chris Hamiltondf0d72cd2018-05-29 16:23:532008void WebContentsImpl::OnAudioStateChanged() {
2009 // This notification can come from any embedded contents or from this
2010 // WebContents' stream monitor. Aggregate these signals to get the actual
2011 // state.
Jeremy Roman03ce13ce2020-05-29 22:16:572012 //
2013 // Note that guests may not be attached as inner contents, and so may need to
2014 // be checked separately.
Chris Hamiltondf0d72cd2018-05-29 16:23:532015 bool is_currently_audible =
2016 audio_stream_monitor_.IsCurrentlyAudible() ||
2017 (browser_plugin_embedder_ &&
Jeremy Roman03ce13ce2020-05-29 22:16:572018 browser_plugin_embedder_->AreAnyGuestsCurrentlyAudible()) ||
2019 AnyInnerWebContents(this, [](WebContents* inner_contents) {
2020 return inner_contents->IsCurrentlyAudible();
2021 });
Alexander Timin5fdeff22020-09-08 09:20:372022 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnAudioStateChanged",
2023 "is_currently_audible", is_currently_audible,
2024 "was_audible", is_currently_audible_);
Chris Hamiltondf0d72cd2018-05-29 16:23:532025 if (is_currently_audible == is_currently_audible_)
2026 return;
2027
2028 // Update internal state.
2029 is_currently_audible_ = is_currently_audible;
2030 was_ever_audible_ = was_ever_audible_ || is_currently_audible_;
2031
Gyuyoung Kim877e86d2020-07-21 04:01:022032 ExecutePageBroadcastMethod(base::BindRepeating(
2033 [](bool is_currently_audible, RenderViewHostImpl* rvh) {
2034 if (auto& broadcast = rvh->GetAssociatedPageBroadcast())
2035 broadcast->AudioStateChanged(is_currently_audible);
2036 },
2037 is_currently_audible_));
altimind8bd26c2016-11-04 11:44:542038
altiminec87fd1f2016-11-17 20:22:492039 // Notification for UI updates in response to the changed audio state.
Collin Bakeraf540cf2019-09-20 20:54:162040 NotifyNavigationStateChanged(INVALIDATE_TYPE_AUDIO);
Jan Rucka442c83f2017-08-08 13:27:542041
Chris Hamiltondf0d72cd2018-05-29 16:23:532042 // Ensure that audio state changes propagate from innermost to outermost
2043 // WebContents.
2044 if (GetOuterWebContents())
2045 GetOuterWebContents()->OnAudioStateChanged();
Tommy Steimel18360512017-11-01 00:38:192046
Alexander Timin90c20c32020-08-12 15:28:322047 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2048 observer->OnAudioStateChanged(is_currently_audible_);
2049 });
altimind8bd26c2016-11-04 11:44:542050}
2051
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:412052base::TimeTicks WebContentsImpl::GetLastActiveTime() {
[email protected]9a890452014-02-13 22:21:022053 return last_active_time_;
[email protected]3e324142012-06-25 18:26:332054}
2055
[email protected]9e2e4632012-07-27 16:38:412056void WebContentsImpl::WasShown() {
Alexander Timin5fdeff22020-09-08 09:20:372057 TRACE_EVENT0("content", "WebContentsImpl::WasShown");
Collin Baker989e0882019-11-01 01:27:172058 UpdateVisibilityAndNotifyPageAndView(Visibility::VISIBLE);
[email protected]be1f56ab2011-12-22 06:55:312059}
2060
[email protected]b172aee2012-04-10 17:05:262061void WebContentsImpl::WasHidden() {
Alexander Timin5fdeff22020-09-08 09:20:372062 TRACE_EVENT0("content", "WebContentsImpl::WasHidden");
Collin Baker989e0882019-11-01 01:27:172063 UpdateVisibilityAndNotifyPageAndView(Visibility::HIDDEN);
[email protected]375fa1b2012-05-22 22:05:372064}
2065
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:412066bool WebContentsImpl::HasRecentInteractiveInputEvent() {
Daniel Cheng90196c82018-04-25 21:49:142067 static constexpr base::TimeDelta kMaxInterval =
2068 base::TimeDelta::FromSeconds(5);
2069 base::TimeDelta delta =
2070 ui::EventTimeForNow() - last_interactive_input_event_time_;
2071 // Note: the expectation is that the caller is typically expecting an input
2072 // event, e.g. validating that a WebUI message that requires a gesture is
Daniel Chenge81030b32019-07-17 20:20:232073 // actually attached to a gesture.
Daniel Cheng90196c82018-04-25 21:49:142074 return delta <= kMaxInterval;
2075}
2076
Avi Drissman738ea192018-08-29 20:24:162077void WebContentsImpl::SetIgnoreInputEvents(bool ignore_input_events) {
Alexander Timin5fdeff22020-09-08 09:20:372078 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetIgnoreInputEvents",
2079 "ignore_input_events", ignore_input_events);
Avi Drissman738ea192018-08-29 20:24:162080 ignore_input_events_ = ignore_input_events;
2081}
2082
Bo Liu168c8642017-08-28 18:26:022083#if defined(OS_ANDROID)
Bo Liu16dd7b8322018-05-02 21:19:502084void WebContentsImpl::SetMainFrameImportance(
2085 ChildProcessImportance importance) {
Alexander Timin5fdeff22020-09-08 09:20:372086 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetMainFrameImportance",
2087 "importance", static_cast<int>(importance));
Bo Liu16dd7b8322018-05-02 21:19:502088 GetMainFrame()->GetRenderWidgetHost()->SetImportance(importance);
Bo Liu7c6779e92017-08-16 02:02:282089}
Bo Liu168c8642017-08-28 18:26:022090#endif
Bo Liu7c6779e92017-08-16 02:02:282091
ccameron8807c38f2015-01-17 00:29:192092void WebContentsImpl::WasOccluded() {
Alexander Timin5fdeff22020-09-08 09:20:372093 TRACE_EVENT0("content", "WebContentsImpl::WasOccluded");
Collin Baker989e0882019-11-01 01:27:172094 UpdateVisibilityAndNotifyPageAndView(Visibility::OCCLUDED);
ccameron8807c38f2015-01-17 00:29:192095}
2096
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:412097Visibility WebContentsImpl::GetVisibility() {
Francois Doraye6161152018-03-27 22:05:372098 return visibility_;
Francois Dorayfe4a1772018-02-17 04:17:092099}
2100
Rakina Zata Amni26e8d8a2020-08-05 06:06:062101bool WebContentsImpl::NeedToFireBeforeUnloadOrUnloadEvents() {
Alexander Timinc7bee322020-05-19 17:54:342102 if (!notify_disconnection_)
Alex Moshchuk6fcaca752018-07-14 02:13:592103 return false;
2104
2105 // Don't fire if the main frame's RenderViewHost indicates that beforeunload
2106 // and unload have already executed (e.g., after receiving a ClosePage ACK)
2107 // or should be ignored.
2108 if (GetRenderViewHost()->SuddenTerminationAllowed())
2109 return false;
2110
Alex Moshchukc78dbc722019-10-31 20:00:502111 // Check whether any frame in the frame tree needs to run beforeunload or
Rakina Zata Amni26e8d8a2020-08-05 06:06:062112 // unload-time event handlers.
Alex Moshchukc78dbc722019-10-31 20:00:502113 for (FrameTreeNode* node : frame_tree_.Nodes()) {
2114 RenderFrameHostImpl* rfh = node->current_frame_host();
2115
Rakina Zata Amni26e8d8a2020-08-05 06:06:062116 // No need to run beforeunload/unload-time events if the RenderFrame isn't
2117 // live.
Alex Moshchukc78dbc722019-10-31 20:00:502118 if (!rfh->IsRenderFrameLive())
2119 continue;
Rakina Zata Amni26e8d8a2020-08-05 06:06:062120 bool should_run_before_unload_handler =
Dave Tapuska97d22ab2019-12-03 17:56:362121 rfh->GetSuddenTerminationDisablerState(
Rakina Zata Amni26e8d8a2020-08-05 06:06:062122 blink::mojom::SuddenTerminationDisablerType::kBeforeUnloadHandler);
2123 bool should_run_unload_handler = rfh->GetSuddenTerminationDisablerState(
2124 blink::mojom::SuddenTerminationDisablerType::kUnloadHandler);
2125 bool should_run_page_hide_handler = rfh->GetSuddenTerminationDisablerState(
2126 blink::mojom::SuddenTerminationDisablerType::kPageHideHandler);
2127 auto* rvh = static_cast<RenderViewHostImpl*>(rfh->GetRenderViewHost());
2128 // If the tab is already hidden, we should not run visibilitychange
2129 // handlers.
2130 bool is_page_visible = rvh->GetPageLifecycleStateManager()
2131 ->CalculatePageLifecycleState()
2132 ->visibility == PageVisibilityState::kVisible;
2133
2134 bool should_run_visibility_change_handler =
2135 is_page_visible && rfh->GetSuddenTerminationDisablerState(
2136 blink::mojom::SuddenTerminationDisablerType::
2137 kVisibilityChangeHandler);
2138 if (should_run_before_unload_handler || should_run_unload_handler ||
2139 should_run_page_hide_handler || should_run_visibility_change_handler) {
Alex Moshchukc78dbc722019-10-31 20:00:502140 return true;
2141 }
Aditya Keerthi34f37e62019-03-08 15:54:532142 }
Alex Moshchuk6fcaca752018-07-14 02:13:592143
Alex Moshchukc78dbc722019-10-31 20:00:502144 return false;
[email protected]be1f56ab2011-12-22 06:55:312145}
2146
Chris Hamilton3b3e315d2018-09-19 13:16:212147void WebContentsImpl::DispatchBeforeUnload(bool auto_cancel) {
Alexander Timin5fdeff22020-09-08 09:20:372148 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DispatchBeforeUnload",
2149 "auto_cancel", auto_cancel);
Chris Hamilton3b3e315d2018-09-19 13:16:212150 auto before_unload_type =
2151 auto_cancel ? RenderFrameHostImpl::BeforeUnloadType::DISCARD
2152 : RenderFrameHostImpl::BeforeUnloadType::TAB_CLOSE;
2153 GetMainFrame()->DispatchBeforeUnload(before_unload_type, false);
[email protected]1c3f80bd2014-04-08 23:02:062154}
2155
W. James MacLean2539adb32019-12-13 00:40:442156bool WebContentsImpl::IsInnerWebContentsForGuest() {
2157 return !!browser_plugin_guest_;
2158}
2159
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502160void WebContentsImpl::AttachInnerWebContents(
2161 std::unique_ptr<WebContents> inner_web_contents,
W. James MacLean62883982019-11-12 20:39:002162 RenderFrameHost* render_frame_host,
2163 bool is_full_page) {
Alexander Timin5fdeff22020-09-08 09:20:372164 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::AttachInnerWebContents",
2165 "inner_web_contents", inner_web_contents.get(),
2166 "is_full_page", is_full_page);
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502167 WebContentsImpl* inner_web_contents_impl =
2168 static_cast<WebContentsImpl*>(inner_web_contents.get());
2169 DCHECK(!inner_web_contents_impl->node_.outer_web_contents());
2170 auto* render_frame_host_impl =
2171 static_cast<RenderFrameHostImpl*>(render_frame_host);
Fergal Daly445af932020-06-02 06:37:232172 DCHECK_EQ(&frame_tree_, render_frame_host_impl->frame_tree());
Lucas Furukawa Gadani105de1e812018-05-31 19:38:392173
Yuzu Saijo3f86fb22020-06-11 03:51:102174 // Mark |render_frame_host_impl| as outer delegate frame.
2175 render_frame_host_impl->SetIsOuterDelegateFrame(true);
2176
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502177 RenderFrameHostManager* inner_render_manager =
2178 inner_web_contents_impl->GetRenderManager();
2179 RenderFrameHostImpl* inner_main_frame =
2180 inner_render_manager->current_frame_host();
2181 RenderViewHostImpl* inner_render_view_host =
2182 inner_render_manager->current_host();
2183 auto* outer_render_manager =
2184 render_frame_host_impl->frame_tree_node()->render_manager();
lfg91a79e12016-04-01 23:52:192185
Lucas Furukawa Gadani105de1e812018-05-31 19:38:392186 // When attaching a WebContents as an inner WebContents, we need to replace
2187 // the Webcontents' view with a WebContentsViewChildFrame.
Fergal Daly55b6d722020-09-11 07:56:332188 inner_web_contents_impl->view_ = std::make_unique<WebContentsViewChildFrame>(
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502189 inner_web_contents_impl,
2190 GetContentClient()->browser()->GetWebContentsViewDelegate(
2191 inner_web_contents_impl),
Fergal Daly55b6d722020-09-11 07:56:332192 &inner_web_contents_impl->render_view_host_delegate_view_);
Lucas Furukawa Gadani105de1e812018-05-31 19:38:392193
lfg91a79e12016-04-01 23:52:192194 // When the WebContents being initialized has an opener, the browser side
2195 // Render{View,Frame}Host must be initialized and the RenderWidgetHostView
2196 // created. This is needed because the usual initialization happens during
2197 // the first navigation, but when attaching a new window we don't navigate
2198 // before attaching. If the browser side is already initialized, the calls
2199 // below will just early return.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502200 inner_render_manager->InitRenderView(inner_render_view_host, nullptr);
2201 inner_main_frame->Init();
2202 if (!inner_render_manager->GetRenderWidgetHostView()) {
2203 inner_web_contents_impl->CreateRenderWidgetHostViewForRenderManager(
2204 inner_render_view_host);
2205 }
lfg91a79e12016-04-01 23:52:192206
Adithya Srinivasane6e7f842019-12-16 18:41:362207 inner_web_contents_impl->RecursivelyUnregisterFrameSinkIds();
2208
lazyboy6ec48b2a2015-06-29 15:18:142209 // Create a link to our outer WebContents.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502210 node_.AttachInnerWebContents(std::move(inner_web_contents),
2211 render_frame_host_impl);
lazyboy6ec48b2a2015-06-29 15:18:142212
lazyboy6ec48b2a2015-06-29 15:18:142213 // Create a proxy in top-level RenderFrameHostManager, pointing to the
2214 // SiteInstance of the outer WebContents. The proxy will be used to send
2215 // postMessage to the inner WebContents.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502216 auto* proxy = inner_render_manager->CreateOuterDelegateProxy(
2217 render_frame_host_impl->GetSiteInstance());
lazyboy6ec48b2a2015-06-29 15:18:142218
Lucas Furukawa Gadani99125822019-01-03 15:41:492219 // When attaching a GuestView as an inner WebContents, there should already be
2220 // a live RenderFrame, which has to be swapped. When attaching a portal, there
2221 // will not be a live RenderFrame before creating the proxy.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502222 if (render_frame_host_impl->IsRenderFrameLive()) {
2223 inner_render_manager->SwapOuterDelegateFrame(render_frame_host_impl, proxy);
Lucas Furukawa Gadani99125822019-01-03 15:41:492224
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502225 inner_web_contents_impl->ReattachToOuterWebContentsFrame();
Lucas Furukawa Gadani99125822019-01-03 15:41:492226 }
ekaramadadd882292016-06-08 15:22:562227
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502228 if (frame_tree_.GetFocusedFrame() ==
2229 render_frame_host_impl->frame_tree_node()) {
2230 inner_web_contents_impl->SetFocusedFrame(
2231 inner_web_contents_impl->frame_tree_.root(),
2232 render_frame_host_impl->GetSiteInstance());
avallee7529b2a2017-04-26 11:37:512233 }
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502234 outer_render_manager->set_attach_complete();
W. James MacLean62883982019-11-12 20:39:002235
2236 // If the inner WebContents is full frame, give it focus.
2237 if (is_full_page) {
2238 // There should only ever be one inner WebContents when |is_full_page| is
2239 // true, and it is the one we just attached.
2240 DCHECK_EQ(1u, node_.GetInnerWebContents().size());
2241 inner_web_contents_impl->SetAsFocusedWebContentsIfNecessary();
2242 }
Chris Hamilton16b5d1d2020-06-04 00:08:122243
Alexander Timin90c20c32020-08-12 15:28:322244 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2245 observer->InnerWebContentsAttached(inner_web_contents_impl,
2246 render_frame_host, is_full_page);
2247 });
lazyboy6ec48b2a2015-06-29 15:18:142248}
2249
Lucas Furukawa Gadani99125822019-01-03 15:41:492250std::unique_ptr<WebContents> WebContentsImpl::DetachFromOuterWebContents() {
Alexander Timin5fdeff22020-09-08 09:20:372251 OPTIONAL_TRACE_EVENT0("content",
2252 "WebContentsImpl::DetachFromOuterWebContents");
Chris Hamilton16b5d1d2020-06-04 00:08:122253 auto* outer_web_contents = GetOuterWebContents();
2254 DCHECK(outer_web_contents);
Yuzu Saijo3f86fb22020-06-11 03:51:102255 GetMainFrame()->ParentOrOuterDelegateFrame()->SetIsOuterDelegateFrame(false);
Chris Hamilton16b5d1d2020-06-04 00:08:122256
Adithya Srinivasane6e7f842019-12-16 18:41:362257 RecursivelyUnregisterFrameSinkIds();
Lucas Gadanid29952582020-06-09 21:24:002258
2259 // Each RenderViewHost has a RenderWidgetHost which can have a
2260 // RenderWidgetHostView, and it needs to be re-created with the appropriate
2261 // platform view. It is important to re-create all child views, not only the
2262 // current one, since the view can be swapped due to a cross-origin
2263 // navigation.
2264 std::set<RenderViewHostImpl*> render_view_hosts;
2265 for (auto& render_view_host : GetFrameTree()->render_view_hosts()) {
2266 if (render_view_host.second->GetWidget() &&
2267 render_view_host.second->GetWidget()->GetView()) {
2268 DCHECK(render_view_host.second->GetWidget()
2269 ->GetView()
2270 ->IsRenderWidgetHostViewChildFrame());
2271 render_view_hosts.insert(render_view_host.second);
Kevin McNee6471a702020-01-27 18:23:072272 }
2273 }
Lucas Gadanid29952582020-06-09 21:24:002274
2275 for (auto* render_view_host : render_view_hosts)
2276 render_view_host->GetWidget()->GetView()->Destroy();
2277
Lucas Furukawa Gadani99125822019-01-03 15:41:492278 GetRenderManager()->DeleteOuterDelegateProxy(
2279 node_.OuterContentsFrameTreeNode()
2280 ->current_frame_host()
2281 ->GetSiteInstance());
2282 view_.reset(CreateWebContentsView(
2283 this, GetContentClient()->browser()->GetWebContentsViewDelegate(this),
2284 &render_view_host_delegate_view_));
danakjfc5184932019-09-12 18:08:322285 view_->CreateView(nullptr);
Lucas Furukawa Gadani99125822019-01-03 15:41:492286 std::unique_ptr<WebContents> web_contents =
2287 node_.DisconnectFromOuterWebContents();
2288 DCHECK_EQ(web_contents.get(), this);
2289 node_.SetFocusedWebContents(this);
Lucas Gadanid29952582020-06-09 21:24:002290
2291 for (auto* render_view_host : render_view_hosts)
2292 CreateRenderWidgetHostViewForRenderManager(render_view_host);
2293
Adithya Srinivasane6e7f842019-12-16 18:41:362294 RecursivelyRegisterFrameSinkIds();
Adithya Srinivasan6f0f67b2019-12-19 01:26:462295 // TODO(adithyas): |browser_plugin_embedder_ax_tree_id| should either not be
2296 // used for portals, or it should get a different name.
2297 GetMainFrame()->set_browser_plugin_embedder_ax_tree_id(ui::AXTreeIDUnknown());
2298 GetMainFrame()->UpdateAXTreeData();
Chris Hamilton16b5d1d2020-06-04 00:08:122299
2300 // Invoke on the *outer* web contents observers for symmetry.
Alexander Timin90c20c32020-08-12 15:28:322301 outer_web_contents->observers_.ForEachObserver(
2302 [&](WebContentsObserver* observer) {
2303 observer->InnerWebContentsDetached(this);
2304 });
Chris Hamilton16b5d1d2020-06-04 00:08:122305
Lucas Furukawa Gadani99125822019-01-03 15:41:492306 return web_contents;
2307}
2308
W. James MacLean2dc75ed42019-03-06 14:31:092309void WebContentsImpl::RecursivelyRegisterFrameSinkIds() {
Alexander Timin5fdeff22020-09-08 09:20:372310 OPTIONAL_TRACE_EVENT0("content",
2311 "WebContentsImpl::RecursivelyRegisterFrameSinkIds");
Adithya Srinivasane6e7f842019-12-16 18:41:362312 for (auto* view : GetRenderWidgetHostViewsInWebContentsTree()) {
2313 auto* rwhvb = static_cast<RenderWidgetHostViewBase*>(view);
2314 if (rwhvb->IsRenderWidgetHostViewChildFrame())
2315 static_cast<RenderWidgetHostViewChildFrame*>(view)->RegisterFrameSinkId();
2316 }
2317}
W. James MacLean2dc75ed42019-03-06 14:31:092318
Adithya Srinivasane6e7f842019-12-16 18:41:362319void WebContentsImpl::RecursivelyUnregisterFrameSinkIds() {
Alexander Timin5fdeff22020-09-08 09:20:372320 OPTIONAL_TRACE_EVENT0("content",
2321 "WebContentsImpl::RecursivelyUnregisterFrameSinkIds");
Adithya Srinivasane6e7f842019-12-16 18:41:362322 for (auto* view : GetRenderWidgetHostViewsInWebContentsTree()) {
2323 auto* rwhvb = static_cast<RenderWidgetHostViewBase*>(view);
2324 if (rwhvb->IsRenderWidgetHostViewChildFrame()) {
2325 static_cast<RenderWidgetHostViewChildFrame*>(view)
2326 ->UnregisterFrameSinkId();
2327 }
W. James MacLean2dc75ed42019-03-06 14:31:092328 }
2329}
2330
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:142331void WebContentsImpl::ReattachToOuterWebContentsFrame() {
Alexander Timin5fdeff22020-09-08 09:20:372332 OPTIONAL_TRACE_EVENT0("content",
2333 "WebContentsImpl::ReattachToOuterWebContentsFrame");
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:142334 DCHECK(node_.outer_web_contents());
2335 auto* render_manager = GetRenderManager();
2336 auto* parent_frame =
2337 node_.OuterContentsFrameTreeNode()->current_frame_host()->GetParent();
2338 render_manager->SetRWHViewForInnerContents(
2339 render_manager->GetRenderWidgetHostView());
2340
W. James MacLean2dc75ed42019-03-06 14:31:092341 RecursivelyRegisterFrameSinkIds();
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:142342
2343 // Set up the the guest's AX tree to point back at the embedder's AX tree.
2344 GetMainFrame()->set_browser_plugin_embedder_ax_tree_id(
2345 parent_frame->GetAXTreeID());
2346 GetMainFrame()->UpdateAXTreeData();
2347}
2348
Lucas Gadani972985622020-05-28 20:52:512349void WebContentsImpl::DidActivatePortal(
2350 WebContentsImpl* predecessor_web_contents,
2351 base::TimeTicks activation_time) {
Alexander Timin5fdeff22020-09-08 09:20:372352 TRACE_EVENT2("content", "WebContentsImpl::DidActivatePortal", "predecessor",
2353 predecessor_web_contents, "activation_time", activation_time);
Lucas Gadani972985622020-05-28 20:52:512354 DCHECK(predecessor_web_contents);
Kevin McNeef8eb64c2020-04-21 21:36:062355 NotifyInsidePortal(false);
Alexander Timin90c20c32020-08-12 15:28:322356 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2357 observer->DidActivatePortal(predecessor_web_contents, activation_time);
2358 });
Lucas Gadani972985622020-05-28 20:52:512359 GetDelegate()->WebContentsBecamePortal(predecessor_web_contents);
Kevin McNeef8eb64c2020-04-21 21:36:062360}
2361
Adithya Srinivasan11af2c52019-12-16 22:52:552362void WebContentsImpl::NotifyInsidePortal(bool inside_portal) {
Alexander Timin5fdeff22020-09-08 09:20:372363 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::NotifyInsidePortal",
2364 "inside_portal", inside_portal);
Gyuyoung Kim1c029712020-07-22 09:21:062365 ExecutePageBroadcastMethod(base::BindRepeating(
2366 [](bool inside_portal, RenderViewHostImpl* rvh) {
2367 if (auto& broadcast = rvh->GetAssociatedPageBroadcast())
2368 broadcast->SetInsidePortal(inside_portal);
2369 },
2370 inside_portal));
Adithya Srinivasan11af2c52019-12-16 22:52:552371}
2372
dalecurtis6c58ed02016-10-28 23:02:372373void WebContentsImpl::DidChangeVisibleSecurityState() {
Alexander Timin5fdeff22020-09-08 09:20:372374 OPTIONAL_TRACE_EVENT0("content",
2375 "WebContentsImpl::DidChangeVisibleSecurityState");
Emily Starkc663b0242019-04-26 19:34:452376 if (delegate_)
dalecurtis6c58ed02016-10-28 23:02:372377 delegate_->VisibleSecurityStateChanged(this);
Alexander Timin90c20c32020-08-12 15:28:322378 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2379 observer->DidChangeVisibleSecurityState();
2380 });
dalecurtis6c58ed02016-10-28 23:02:372381}
2382
Gyuyoung Kim1ac4ca782020-09-11 03:32:512383const blink::web_pref::WebPreferences WebContentsImpl::ComputeWebPreferences() {
Alexander Timin5fdeff22020-09-08 09:20:372384 OPTIONAL_TRACE_EVENT0("browser", "WebContentsImpl::ComputeWebPreferences");
2385
Gyuyoung Kim1ac4ca782020-09-11 03:32:512386 blink::web_pref::WebPreferences prefs;
Rakina Zata Amni4029b6d2020-07-28 02:36:202387
2388 const base::CommandLine& command_line =
2389 *base::CommandLine::ForCurrentProcess();
2390
2391 SetSlowWebPreferences(command_line, &prefs);
2392
2393 prefs.web_security_enabled =
2394 !command_line.HasSwitch(switches::kDisableWebSecurity);
2395
2396 prefs.remote_fonts_enabled =
2397 !command_line.HasSwitch(switches::kDisableRemoteFonts);
2398 prefs.application_cache_enabled =
2399 base::FeatureList::IsEnabled(blink::features::kAppCache);
2400 prefs.local_storage_enabled =
2401 !command_line.HasSwitch(switches::kDisableLocalStorage);
2402 prefs.databases_enabled =
2403 !command_line.HasSwitch(switches::kDisableDatabases);
2404
2405 prefs.webgl1_enabled = !command_line.HasSwitch(switches::kDisable3DAPIs) &&
2406 !command_line.HasSwitch(switches::kDisableWebGL);
2407 prefs.webgl2_enabled = !command_line.HasSwitch(switches::kDisable3DAPIs) &&
2408 !command_line.HasSwitch(switches::kDisableWebGL) &&
2409 !command_line.HasSwitch(switches::kDisableWebGL2);
2410
2411 prefs.pepper_3d_enabled = !command_line.HasSwitch(switches::kDisablePepper3d);
2412
2413 prefs.flash_3d_enabled = !command_line.HasSwitch(switches::kDisableFlash3d);
2414 prefs.flash_stage3d_enabled =
2415 !command_line.HasSwitch(switches::kDisableFlashStage3d);
2416 prefs.flash_stage3d_baseline_enabled =
2417 !command_line.HasSwitch(switches::kDisableFlashStage3d);
2418
2419 prefs.allow_file_access_from_file_urls =
2420 command_line.HasSwitch(switches::kAllowFileAccessFromFiles);
2421
2422 prefs.accelerated_2d_canvas_enabled =
2423 !command_line.HasSwitch(switches::kDisableAccelerated2dCanvas);
2424 prefs.new_canvas_2d_api_enabled =
Rakina Zata Amniea8d0c22020-07-30 17:22:502425 command_line.HasSwitch(switches::kEnableNewCanvas2DAPI) ||
2426 base::FeatureList::IsEnabled(features::kEnableNewCanvas2DAPI);
Rakina Zata Amni4029b6d2020-07-28 02:36:202427 prefs.antialiased_2d_canvas_disabled =
2428 command_line.HasSwitch(switches::kDisable2dCanvasAntialiasing);
2429 prefs.antialiased_clips_2d_canvas_enabled =
2430 !command_line.HasSwitch(switches::kDisable2dCanvasClipAntialiasing);
2431
2432 prefs.disable_ipc_flooding_protection =
2433 command_line.HasSwitch(switches::kDisableIpcFloodingProtection) ||
2434 command_line.HasSwitch(switches::kDisablePushStateThrottle);
2435
2436 prefs.accelerated_video_decode_enabled =
2437 !command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode);
2438
2439 std::string autoplay_policy = media::GetEffectiveAutoplayPolicy(command_line);
2440 if (autoplay_policy == switches::autoplay::kNoUserGestureRequiredPolicy) {
Gyuyoung Kim1ac4ca782020-09-11 03:32:512441 prefs.autoplay_policy =
2442 blink::web_pref::AutoplayPolicy::kNoUserGestureRequired;
Rakina Zata Amni4029b6d2020-07-28 02:36:202443 } else if (autoplay_policy ==
2444 switches::autoplay::kUserGestureRequiredPolicy) {
Gyuyoung Kim1ac4ca782020-09-11 03:32:512445 prefs.autoplay_policy =
2446 blink::web_pref::AutoplayPolicy::kUserGestureRequired;
Rakina Zata Amni4029b6d2020-07-28 02:36:202447 } else if (autoplay_policy ==
2448 switches::autoplay::kDocumentUserActivationRequiredPolicy) {
Gyuyoung Kim1ac4ca782020-09-11 03:32:512449 prefs.autoplay_policy =
2450 blink::web_pref::AutoplayPolicy::kDocumentUserActivationRequired;
Rakina Zata Amni4029b6d2020-07-28 02:36:202451 } else {
2452 NOTREACHED();
2453 }
2454
2455 prefs.dont_send_key_events_to_javascript =
2456 base::FeatureList::IsEnabled(features::kDontSendKeyEventsToJavascript);
2457
2458// TODO(dtapuska): Enable barrel button selection drag support on Android.
2459// crbug.com/758042
2460#if defined(OS_WIN)
2461 prefs.barrel_button_for_drag_enabled =
2462 base::FeatureList::IsEnabled(features::kDirectManipulationStylus);
2463#endif // defined(OS_WIN)
2464
Rakina Zata Amni4029b6d2020-07-28 02:36:202465 prefs.enable_scroll_animator =
2466 command_line.HasSwitch(switches::kEnableSmoothScrolling) ||
2467 (!command_line.HasSwitch(switches::kDisableSmoothScrolling) &&
2468 gfx::Animation::ScrollAnimationsEnabledBySystem());
2469
2470 prefs.prefers_reduced_motion = gfx::Animation::PrefersReducedMotion();
2471
2472 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
2473 GetRenderViewHost()->GetProcess()->GetID())) {
2474 prefs.loads_images_automatically = true;
2475 prefs.javascript_enabled = true;
2476 }
2477
2478 prefs.viewport_enabled = command_line.HasSwitch(switches::kEnableViewport);
2479
2480 if (IsOverridingUserAgent())
2481 prefs.viewport_meta_enabled = false;
2482
2483 prefs.main_frame_resizes_are_orientation_changes =
2484 command_line.HasSwitch(switches::kMainFrameResizesAreOrientationChanges);
2485
2486 prefs.spatial_navigation_enabled =
2487 command_line.HasSwitch(switches::kEnableSpatialNavigation);
2488
2489 if (IsSpatialNavigationDisabled())
2490 prefs.spatial_navigation_enabled = false;
2491
Rakina Zata Amni4029b6d2020-07-28 02:36:202492 prefs.disable_reading_from_canvas =
2493 command_line.HasSwitch(switches::kDisableReadingFromCanvas);
2494
2495 prefs.strict_mixed_content_checking =
2496 command_line.HasSwitch(switches::kEnableStrictMixedContentChecking);
2497
2498 prefs.strict_powerful_feature_restrictions = command_line.HasSwitch(
2499 switches::kEnableStrictPowerfulFeatureRestrictions);
2500
2501 const std::string blockable_mixed_content_group =
2502 base::FieldTrialList::FindFullName("BlockableMixedContent");
2503 prefs.strictly_block_blockable_mixed_content =
2504 blockable_mixed_content_group == "StrictlyBlockBlockableMixedContent";
2505
2506 const std::string plugin_mixed_content_status =
2507 base::FieldTrialList::FindFullName("PluginMixedContentStatus");
2508 prefs.block_mixed_plugin_content =
2509 plugin_mixed_content_status == "BlockableMixedContent";
2510
2511 prefs.v8_cache_options = GetV8CacheOptions();
2512
2513 prefs.user_gesture_required_for_presentation = !command_line.HasSwitch(
2514 switches::kDisableGestureRequirementForPresentation);
2515
2516 if (HideDownloadUI())
2517 prefs.hide_download_ui = true;
2518
2519 // `media_controls_enabled` is `true` by default.
2520 if (HasPersistentVideo())
2521 prefs.media_controls_enabled = false;
2522
2523#if defined(OS_ANDROID)
2524 display::Display display = display::Screen::GetScreen()->GetPrimaryDisplay();
2525 gfx::Size size = display.GetSizeInPixel();
2526 int min_width = size.width() < size.height() ? size.width() : size.height();
2527 prefs.device_scale_adjustment = GetDeviceScaleAdjustment(
2528 static_cast<int>(min_width / display.device_scale_factor()));
2529#endif // OS_ANDROID
2530
2531 GetContentClient()->browser()->OverrideWebkitPrefs(GetRenderViewHost(),
2532 &prefs);
2533 return prefs;
2534}
2535
2536void WebContentsImpl::SetSlowWebPreferences(
2537 const base::CommandLine& command_line,
Gyuyoung Kim1ac4ca782020-09-11 03:32:512538 blink::web_pref::WebPreferences* prefs) {
Alexander Timin5fdeff22020-09-08 09:20:372539 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetSlowWebPreferences");
2540
Rakina Zata Amni4029b6d2020-07-28 02:36:202541 if (web_preferences_.get()) {
2542#define SET_FROM_CACHE(prefs, field) prefs->field = web_preferences_->field
2543
2544 SET_FROM_CACHE(prefs, touch_event_feature_detection_enabled);
2545 SET_FROM_CACHE(prefs, available_pointer_types);
2546 SET_FROM_CACHE(prefs, available_hover_types);
2547 SET_FROM_CACHE(prefs, primary_pointer_type);
2548 SET_FROM_CACHE(prefs, primary_hover_type);
2549 SET_FROM_CACHE(prefs, pointer_events_max_touch_points);
2550 SET_FROM_CACHE(prefs, number_of_cpu_cores);
2551
2552#if defined(OS_ANDROID)
2553 SET_FROM_CACHE(prefs, video_fullscreen_orientation_lock_enabled);
2554 SET_FROM_CACHE(prefs, video_rotate_to_fullscreen_enabled);
2555#endif
2556
2557#undef SET_FROM_CACHE
2558 } else {
2559 // Every prefs->field modified below should have a SET_FROM_CACHE entry
2560 // above.
2561
2562 // On Android, Touch event feature detection is enabled by default,
2563 // Otherwise default is disabled.
2564 std::string touch_enabled_default_switch =
2565 switches::kTouchEventFeatureDetectionDisabled;
2566#if defined(OS_ANDROID)
2567 touch_enabled_default_switch = switches::kTouchEventFeatureDetectionEnabled;
2568#endif // defined(OS_ANDROID)
2569 const std::string touch_enabled_switch =
2570 command_line.HasSwitch(switches::kTouchEventFeatureDetection)
2571 ? command_line.GetSwitchValueASCII(
2572 switches::kTouchEventFeatureDetection)
2573 : touch_enabled_default_switch;
2574
2575 prefs->touch_event_feature_detection_enabled =
2576 (touch_enabled_switch == switches::kTouchEventFeatureDetectionAuto)
2577 ? (ui::GetTouchScreensAvailability() ==
2578 ui::TouchScreensAvailability::ENABLED)
2579 : (touch_enabled_switch.empty() ||
2580 touch_enabled_switch ==
2581 switches::kTouchEventFeatureDetectionEnabled);
2582
2583 std::tie(prefs->available_pointer_types, prefs->available_hover_types) =
2584 ui::GetAvailablePointerAndHoverTypes();
2585 prefs->primary_pointer_type =
2586 ui::GetPrimaryPointerType(prefs->available_pointer_types);
2587 prefs->primary_hover_type =
2588 ui::GetPrimaryHoverType(prefs->available_hover_types);
2589
2590 prefs->pointer_events_max_touch_points = ui::MaxTouchPoints();
2591
2592 prefs->number_of_cpu_cores = base::SysInfo::NumberOfProcessors();
2593
2594#if defined(OS_ANDROID)
2595 const bool device_is_phone =
2596 ui::GetDeviceFormFactor() == ui::DEVICE_FORM_FACTOR_PHONE;
2597 prefs->video_fullscreen_orientation_lock_enabled = device_is_phone;
2598 prefs->video_rotate_to_fullscreen_enabled = device_is_phone;
2599#endif
2600 }
2601}
2602
2603void WebContentsImpl::OnWebPreferencesChanged() {
Alexander Timin5fdeff22020-09-08 09:20:372604 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnWebPreferencesChanged");
2605
Rakina Zata Amni4029b6d2020-07-28 02:36:202606 // This is defensive code to avoid infinite loops due to code run inside
2607 // SetWebPreferences() accidentally updating more preferences and thus
2608 // calling back into this code. See crbug.com/398751 for one past example.
2609 if (updating_web_preferences_)
2610 return;
2611 updating_web_preferences_ = true;
2612 SetWebPreferences(ComputeWebPreferences());
2613#if defined(OS_ANDROID)
2614 for (FrameTreeNode* node : frame_tree_.Nodes()) {
2615 RenderFrameHostImpl* rfh = node->current_frame_host();
2616 if (rfh->is_local_root()) {
2617 if (auto* rwh = rfh->GetRenderWidgetHost())
2618 rwh->SetForceEnableZoom(web_preferences_->force_enable_zoom);
2619 }
2620 }
2621#endif
2622 updating_web_preferences_ = false;
2623}
2624
Ahmed Fakhryd70bf37b2018-04-04 17:07:242625void WebContentsImpl::NotifyPreferencesChanged() {
Alexander Timin5fdeff22020-09-08 09:20:372626 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::NotifyPreferencesChanged");
2627
Rakina Zata Amni347b70902020-07-22 10:49:042628 // Recompute the WebPreferences based on the current state of the WebContents,
Rakina Zata Amni4029b6d2020-07-28 02:36:202629 // etc. Note that OnWebPreferencesChanged will also call SetWebPreferences and
2630 // send the updated WebPreferences to all RenderViews for this WebContents.
2631 OnWebPreferencesChanged();
Ahmed Fakhryd70bf37b2018-04-04 17:07:242632}
2633
Bruce Long1e3e1f542019-10-16 17:56:282634void WebContentsImpl::SyncRendererPrefs() {
Alexander Timin5fdeff22020-09-08 09:20:372635 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SyncRendererPrefs");
2636
Peter Marshall2dc74e92020-07-29 20:02:302637 blink::mojom::RendererPreferences renderer_preferences = GetRendererPrefs();
Bruce Long1e3e1f542019-10-16 17:56:282638 RenderViewHostImpl::GetPlatformSpecificPrefs(&renderer_preferences);
2639 SendPageMessage(
2640 new PageMsg_SetRendererPrefs(MSG_ROUTING_NONE, renderer_preferences));
2641}
2642
Alexander Timin1cc31f42020-05-12 16:26:012643void WebContentsImpl::OnCookiesAccessed(NavigationHandle* navigation,
2644 const CookieAccessDetails& details) {
Alexander Timin5fdeff22020-09-08 09:20:372645 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnCookiesAccessed",
2646 "navigation_handle", navigation);
Alexander Timin90c20c32020-08-12 15:28:322647 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2648 observer->OnCookiesAccessed(navigation, details);
2649 });
Alexander Timin1cc31f42020-05-12 16:26:012650}
2651
2652void WebContentsImpl::OnCookiesAccessed(RenderFrameHostImpl* rfh,
2653 const CookieAccessDetails& details) {
Alexander Timin5fdeff22020-09-08 09:20:372654 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnCookiesAccessed",
2655 "render_frame_host",
2656 base::trace_event::ToTracedValue(rfh));
Alexander Timin90c20c32020-08-12 15:28:322657 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2658 observer->OnCookiesAccessed(rfh, details);
2659 });
Josh Karlindaba39322019-07-17 23:24:332660}
2661
[email protected]b172aee2012-04-10 17:05:262662void WebContentsImpl::Stop() {
Alexander Timin5fdeff22020-09-08 09:20:372663 TRACE_EVENT0("content", "WebContentsImpl::Stop");
dcheng57e39e22016-01-21 00:25:382664 for (FrameTreeNode* node : frame_tree_.Nodes())
2665 node->StopLoading();
Alexander Timin90c20c32020-08-12 15:28:322666 observers_.ForEachObserver(
2667 [&](WebContentsObserver* observer) { observer->NavigationStopped(); });
[email protected]0bfbf882011-12-22 18:19:272668}
2669
Francois Doray47f759d2018-06-11 18:13:512670void WebContentsImpl::SetPageFrozen(bool frozen) {
Alexander Timin5fdeff22020-09-08 09:20:372671 TRACE_EVENT1("content", "WebContentsImpl::SetPageFrozen", "frozen", frozen);
2672
Francois Doray47f759d2018-06-11 18:13:512673 // A visible page is never frozen.
2674 DCHECK_NE(Visibility::VISIBLE, GetVisibility());
2675
Yuzu Saijo4fa1e9a2020-05-20 02:53:262676 for (auto& entry : frame_tree_.render_view_hosts()) {
2677 entry.second->SetIsFrozen(frozen);
2678 }
Fadi Meawada6573e02018-03-10 00:52:112679}
2680
erikchen6c7df7f7a2018-05-03 18:13:592681std::unique_ptr<WebContents> WebContentsImpl::Clone() {
Alexander Timin5fdeff22020-09-08 09:20:372682 TRACE_EVENT0("content", "WebContentsImpl::Clone");
2683
[email protected]14392a52012-05-02 20:28:442684 // We use our current SiteInstance since the cloned entry will use it anyway.
alexmose201c7cd2015-06-10 17:14:212685 // We pass our own opener so that the cloned page can access it if it was set
[email protected]ed245db2012-12-18 08:00:452686 // before.
[email protected]54944cde2012-12-09 09:24:592687 CreateParams create_params(GetBrowserContext(), GetSiteInstance());
Ian Clelland5cbaaf82017-11-27 22:00:032688 FrameTreeNode* opener = frame_tree_.root()->opener();
2689 RenderFrameHostImpl* opener_rfh = nullptr;
2690 if (opener)
2691 opener_rfh = opener->current_frame_host();
erikchen6c7df7f7a2018-05-03 18:13:592692 std::unique_ptr<WebContentsImpl> tc =
erikchen50735fd2018-05-05 15:08:332693 CreateWithOpener(create_params, opener_rfh);
Lucas Furukawa Gadani5553a152019-01-08 18:55:572694 tc->GetController().CopyStateFrom(&controller_, true);
Alexander Timin90c20c32020-08-12 15:28:322695 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2696 observer->DidCloneToNewWebContents(this, tc.get());
2697 });
[email protected]0bfbf882011-12-22 18:19:272698 return tc;
2699}
2700
[email protected]14392a52012-05-02 20:28:442701void WebContentsImpl::Observe(int type,
[email protected]8ff00d72012-10-23 19:12:212702 const NotificationSource& source,
2703 const NotificationDetails& details) {
Alexander Timin5fdeff22020-09-08 09:20:372704 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::Observe", "type", type);
[email protected]14392a52012-05-02 20:28:442705 switch (type) {
[email protected]8ff00d72012-10-23 19:12:212706 case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: {
2707 RenderWidgetHost* host = Source<RenderWidgetHost>(source).ptr();
[email protected]0b431992014-06-24 00:08:032708 RenderWidgetHostView* view = host->GetView();
2709 if (view == GetFullscreenRenderWidgetHostView()) {
2710 // We cannot just call view_->RestoreFocus() here. On some platforms,
2711 // attempting to focus the currently-invisible WebContentsView will be
2712 // flat-out ignored. Therefore, this boolean is used to track whether
2713 // we will request focus after the fullscreen widget has been
2714 // destroyed.
2715 fullscreen_widget_had_focus_at_shutdown_ = (view && view->HasFocus());
2716 } else {
alexmosc2a8cec2016-05-23 22:19:532717 for (auto i = pending_widget_views_.begin();
[email protected]0b431992014-06-24 00:08:032718 i != pending_widget_views_.end(); ++i) {
2719 if (host->GetView() == i->second) {
2720 pending_widget_views_.erase(i);
2721 break;
2722 }
[email protected]bafe6cd2012-05-23 23:09:502723 }
2724 }
2725 break;
2726 }
[email protected]14392a52012-05-02 20:28:442727 default:
2728 NOTREACHED();
2729 }
2730}
2731
[email protected]ec6c05f2013-10-23 18:41:572732WebContents* WebContentsImpl::GetWebContents() {
2733 return this;
2734}
2735
[email protected]54944cde2012-12-09 09:24:592736void WebContentsImpl::Init(const WebContents::CreateParams& params) {
Alexander Timin5fdeff22020-09-08 09:20:372737 TRACE_EVENT0("content", "WebContentsImpl::Init");
2738
[email protected]fa944cb82013-11-15 17:51:212739 // This is set before initializing the render manager since
[email protected]b0936d22013-11-28 06:47:362740 // RenderFrameHostManager::Init calls back into us via its delegate to ask if
[email protected]fa944cb82013-11-15 17:51:212741 // it should be hidden.
Francois Doraye6161152018-03-27 22:05:372742 visibility_ =
2743 params.initially_hidden ? Visibility::HIDDEN : Visibility::VISIBLE;
[email protected]d6fa88f2013-10-18 16:00:432744
Sebastien Marchand28cf23182018-06-20 02:39:352745 if (!params.last_active_time.is_null())
2746 last_active_time_ = params.last_active_time;
2747
dcheng3ce04b62015-10-26 23:30:552748 scoped_refptr<SiteInstance> site_instance = params.site_instance;
2749 if (!site_instance)
2750 site_instance = SiteInstance::Create(params.browser_context);
Lukasz Anforowicz3caa8372018-06-05 17:22:072751 if (params.desired_renderer_state == CreateParams::kNoRendererProcess) {
2752 static_cast<SiteInstanceImpl*>(site_instance.get())
2753 ->PreventAssociationWithSpareProcess();
2754 }
dcheng3ce04b62015-10-26 23:30:552755
Fergal Dalycb0c1fdf2020-03-16 07:13:492756 GetRenderManager()->InitRoot(site_instance.get(),
2757 params.renderer_initiated_creation);
lukasza464d8692016-02-22 19:26:322758
lukasza5140a412016-09-15 21:12:302759 // blink::FrameTree::setName always keeps |unique_name| empty in case of a
2760 // main frame - let's do the same thing here.
2761 std::string unique_name;
lukasza464d8692016-02-22 19:26:322762 frame_tree_.root()->SetFrameName(params.main_frame_name, unique_name);
[email protected]d1198fd2012-08-13 22:50:192763
[email protected]fc2b46b2014-05-03 16:33:452764 WebContentsViewDelegate* delegate =
2765 GetContentClient()->browser()->GetWebContentsViewDelegate(this);
2766
W. James MacLean2539adb32019-12-13 00:40:442767 if (browser_plugin_guest_) {
Fergal Daly55b6d722020-09-11 07:56:332768 view_ = std::make_unique<WebContentsViewChildFrame>(
2769 this, delegate, &render_view_host_delegate_view_);
sky52a39e342016-12-17 17:23:222770 } else {
2771 view_.reset(CreateWebContentsView(this, delegate,
2772 &render_view_host_delegate_view_));
[email protected]d1198fd2012-08-13 22:50:192773 }
[email protected]fc2b46b2014-05-03 16:33:452774 CHECK(render_view_host_delegate_view_);
[email protected]d1198fd2012-08-13 22:50:192775 CHECK(view_.get());
2776
danakjfc5184932019-09-12 18:08:322777 view_->CreateView(params.context);
[email protected]d1198fd2012-08-13 22:50:192778
brettw4b461082016-11-19 18:55:162779#if BUILDFLAG(ENABLE_PLUGINS)
Fergal Daly55b6d722020-09-11 07:56:332780 plugin_content_origin_allowlist_ =
2781 std::make_unique<PluginContentOriginAllowlist>(this);
tommyclieb25b2a2014-11-03 19:45:092782#endif
2783
[email protected]d1198fd2012-08-13 22:50:192784 registrar_.Add(this,
[email protected]8ff00d72012-10-23 19:12:212785 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
2786 NotificationService::AllBrowserContextsAndSources());
[email protected]f28ef9a32014-05-12 16:36:102787
Fergal Daly55b6d722020-09-11 07:56:332788 screen_orientation_provider_ =
2789 std::make_unique<ScreenOrientationProvider>(this);
[email protected]01f83f92014-06-17 14:41:542790
mfomitchev2b8b066a2016-01-28 19:23:152791#if defined(OS_ANDROID)
Oksana Zhuravlova0b634332019-10-28 23:04:222792 DateTimeChooserAndroid::CreateForWebContents(this);
[email protected]583418cc2013-01-17 14:01:102793#endif
fsamuel7310a4262014-12-05 05:06:442794
2795 // BrowserPluginGuest::Init needs to be called after this WebContents has
W. James MacLean6e78da342019-12-13 15:13:232796 // a RenderWidgetHostViewChildFrame. That is, |view_->CreateView| above.
fsamuel7310a4262014-12-05 05:06:442797 if (browser_plugin_guest_)
2798 browser_plugin_guest_->Init();
nickf9acfbe2014-12-23 19:12:372799
Fergal Daly55b6d722020-09-11 07:56:332800 for (auto& i : g_created_callbacks.Get())
2801 i.Run(this);
naskob21fe4872015-02-24 14:15:562802
2803 // If the WebContents creation was renderer-initiated, it means that the
2804 // corresponding RenderView and main RenderFrame have already been created.
2805 // Ensure observers are notified about this.
2806 if (params.renderer_initiated_creation) {
Fergal Dalybb2d6592020-06-02 05:02:332807 GetRenderViewHost()->GetWidget()->set_renderer_initialized(true);
Alex Moshchuk27caae82017-09-11 23:11:182808 GetRenderViewHost()->DispatchRenderViewCreated();
naskob21fe4872015-02-24 14:15:562809 GetRenderManager()->current_frame_host()->SetRenderFrameCreated(true);
2810 }
naskof5940b9f2015-03-02 23:04:052811
lof84501da082016-05-23 21:22:542812 // Create the renderer process in advance if requested.
Lukasz Anforowicz3caa8372018-06-05 17:22:072813 if (params.desired_renderer_state ==
2814 CreateParams::kInitializeAndWarmupRendererProcess) {
lof84501da082016-05-23 21:22:542815 if (!GetRenderManager()->current_frame_host()->IsRenderFrameLive()) {
2816 GetRenderManager()->InitRenderView(GetRenderViewHost(), nullptr);
2817 }
2818 }
2819
naskof5940b9f2015-03-02 23:04:052820 // Ensure that observers are notified of the creation of this WebContents's
2821 // main RenderFrameHost. It must be done here for main frames, since the
2822 // NotifySwappedFromRenderManager expects view_ to already be created and that
2823 // happens after RenderFrameHostManager::Init.
2824 NotifySwappedFromRenderManager(
2825 nullptr, GetRenderManager()->current_frame_host(), true);
Albert J. Wonge76bf0b82019-09-27 07:47:062826
2827 // For WebContents that are never shown, do critical initialization here which
2828 // would normally only happen when the WebContents is shown.
2829 if (params.is_never_visible) {
2830 // This has just been created so there can only be one frame. Thus it is
2831 // safe to initialize the root.
2832 GetMainFrame()->Init();
2833 }
[email protected]d1198fd2012-08-13 22:50:192834}
2835
[email protected]7fff43e2013-05-21 20:21:102836void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl* web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:372837 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnWebContentsDestroyed");
2838
[email protected]7fff43e2013-05-21 20:21:102839 RemoveDestructionObserver(web_contents);
2840
[email protected]ceee8cd2013-03-08 04:59:512841 // Clear a pending contents that has been closed before being shown.
alexmosc2a8cec2016-05-23 22:19:532842 for (auto iter = pending_contents_.begin(); iter != pending_contents_.end();
[email protected]ceee8cd2013-03-08 04:59:512843 ++iter) {
Joel Hockey8c2011b22020-04-30 05:07:192844 if (iter->second.contents.get() != web_contents)
[email protected]ceee8cd2013-03-08 04:59:512845 continue;
erikchenbee5c9622018-04-27 19:30:252846
2847 // Someone else has deleted the WebContents. That should never happen!
2848 // TODO(erikchen): Fix semantics here. https://crbug.com/832879.
Joel Hockey8c2011b22020-04-30 05:07:192849 iter->second.contents.release();
[email protected]ceee8cd2013-03-08 04:59:512850 pending_contents_.erase(iter);
[email protected]ceee8cd2013-03-08 04:59:512851 return;
2852 }
2853 NOTREACHED();
[email protected]14392a52012-05-02 20:28:442854}
2855
[email protected]7fff43e2013-05-21 20:21:102856void WebContentsImpl::AddDestructionObserver(WebContentsImpl* web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:372857 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
2858 "WebContentsImpl::AddDestructionObserver");
2859
Jan Wilken Dörrie73c901e2019-06-12 09:02:322860 if (!base::Contains(destruction_observers_, web_contents)) {
[email protected]7fff43e2013-05-21 20:21:102861 destruction_observers_[web_contents] =
Jeremy Roman04f27c372017-10-27 15:20:552862 std::make_unique<DestructionObserver>(this, web_contents);
[email protected]7fff43e2013-05-21 20:21:102863 }
2864}
2865
2866void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl* web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:372867 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
2868 "WebContentsImpl::RemoveDestructionObserver");
avia8cf81982016-08-12 20:28:462869 destruction_observers_.erase(web_contents);
[email protected]7fff43e2013-05-21 20:21:102870}
2871
[email protected]b172aee2012-04-10 17:05:262872void WebContentsImpl::AddObserver(WebContentsObserver* observer) {
Alexander Timin5fdeff22020-09-08 09:20:372873 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
2874 "WebContentsImpl::AddObserver");
[email protected]be1f56ab2011-12-22 06:55:312875 observers_.AddObserver(observer);
2876}
2877
[email protected]b172aee2012-04-10 17:05:262878void WebContentsImpl::RemoveObserver(WebContentsObserver* observer) {
Alexander Timin5fdeff22020-09-08 09:20:372879 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
2880 "WebContentsImpl::RemoveObserver");
[email protected]be1f56ab2011-12-22 06:55:312881 observers_.RemoveObserver(observer);
2882}
2883
[email protected]948481d2014-06-11 18:32:222884std::set<RenderWidgetHostView*>
2885WebContentsImpl::GetRenderWidgetHostViewsInTree() {
2886 std::set<RenderWidgetHostView*> set;
Carlos IL07f282f2020-05-15 22:58:292887 for (RenderFrameHost* rfh : GetAllFrames()) {
2888 if (RenderWidgetHostView* rwhv = static_cast<RenderFrameHostImpl*>(rfh)
2889 ->frame_tree_node()
2890 ->render_manager()
2891 ->GetRenderWidgetHostView()) {
lfgf949e0e2017-05-10 22:18:112892 set.insert(rwhv);
dchengafb53e22016-02-04 08:11:082893 }
[email protected]948481d2014-06-11 18:32:222894 }
[email protected]de3c5d82014-05-28 22:12:592895 return set;
2896}
2897
Adithya Srinivasane6e7f842019-12-16 18:41:362898std::set<RenderWidgetHostView*>
2899WebContentsImpl::GetRenderWidgetHostViewsInWebContentsTree() {
2900 std::set<RenderWidgetHostView*> result;
2901 GetRenderWidgetHostViewsInWebContentsTree(result);
2902 return result;
2903}
2904
2905void WebContentsImpl::GetRenderWidgetHostViewsInWebContentsTree(
2906 std::set<RenderWidgetHostView*>& result) {
2907 std::set<RenderWidgetHostView*> views = GetRenderWidgetHostViewsInTree();
2908 result.insert(views.begin(), views.end());
2909 for (auto* inner_web_contents : GetInnerWebContents()) {
2910 static_cast<WebContentsImpl*>(inner_web_contents)
2911 ->GetRenderWidgetHostViewsInWebContentsTree(result);
2912 }
2913}
2914
[email protected]b172aee2012-04-10 17:05:262915void WebContentsImpl::Activate() {
Alexander Timin5fdeff22020-09-08 09:20:372916 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Activate");
[email protected]d5f942ba2008-09-26 19:30:342917 if (delegate_)
2918 delegate_->ActivateContents(this);
2919}
2920
avi3e4b8512015-11-11 01:55:492921void WebContentsImpl::LostCapture(RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:372922 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::LostCapture",
2923 "render_widget_host", render_widget_host);
avi3e4b8512015-11-11 01:55:492924 if (!RenderViewHostImpl::From(render_widget_host))
2925 return;
2926
[email protected]63954792011-07-11 04:17:482927 if (delegate_)
2928 delegate_->LostCapture();
2929}
2930
Yue Ru Sun979c4b162019-11-06 16:11:042931ukm::SourceId
2932WebContentsImpl::GetUkmSourceIdForLastCommittedSourceIncludingSameDocument()
2933 const {
2934 return last_committed_source_id_including_same_document_;
2935}
2936
Ahmed Fakhryfaa32d22018-10-05 15:56:162937void WebContentsImpl::SetTopControlsShownRatio(
2938 RenderWidgetHostImpl* render_widget_host,
2939 float ratio) {
Alexander Timin5fdeff22020-09-08 09:20:372940 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetTopControlsShownRatio",
2941 "render_widget_host", render_widget_host, "ratio",
2942 ratio);
Ahmed Fakhryfaa32d22018-10-05 15:56:162943 if (!delegate_)
2944 return;
2945
2946 RenderFrameHostImpl* rfh = GetMainFrame();
2947 if (!rfh || render_widget_host != rfh->GetRenderWidgetHost())
2948 return;
2949
2950 delegate_->SetTopControlsShownRatio(this, ratio);
Ahmed Fakhry58e6ef542018-09-04 18:05:382951}
2952
Ahmed Fakhry58e6ef542018-09-04 18:05:382953void WebContentsImpl::SetTopControlsGestureScrollInProgress(bool in_progress) {
Alexander Timin5fdeff22020-09-08 09:20:372954 OPTIONAL_TRACE_EVENT1(
2955 "content", "WebContentsImpl::SetTopControlsGestureScrollInProgress",
2956 "in_progress", in_progress);
Ahmed Fakhry58e6ef542018-09-04 18:05:382957 if (delegate_)
2958 delegate_->SetTopControlsGestureScrollInProgress(in_progress);
2959}
2960
lazyboy63f5b312015-11-23 20:19:522961void WebContentsImpl::RenderWidgetCreated(
2962 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:372963 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderWidgetCreated",
2964 "render_widget_host", render_widget_host);
lazyboy63f5b312015-11-23 20:19:522965 created_widgets_.insert(render_widget_host);
2966}
2967
[email protected]b24b68a2012-09-24 21:57:262968void WebContentsImpl::RenderWidgetDeleted(
2969 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:372970 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderWidgetDeleted",
2971 "render_widget_host", render_widget_host);
lazyboy63f5b312015-11-23 20:19:522972 // Note that |is_being_destroyed_| can be true at this point as
2973 // ~WebContentsImpl() calls RFHM::ClearRFHsPendingShutdown(), which might lead
2974 // us here.
2975 created_widgets_.erase(render_widget_host);
[email protected]b24b68a2012-09-24 21:57:262976
lazyboy63f5b312015-11-23 20:19:522977 if (is_being_destroyed_)
2978 return;
[email protected]44470a22013-01-24 01:21:542979
2980 if (render_widget_host &&
alexmosc9e76ec2016-05-16 22:59:372981 render_widget_host->GetRoutingID() == fullscreen_widget_routing_id_ &&
2982 render_widget_host->GetProcess()->GetID() ==
2983 fullscreen_widget_process_id_) {
[email protected]4aebbca2013-09-17 22:26:492984 if (delegate_ && delegate_->EmbedsFullscreenWidget())
mlamouri7a78d6fd2015-01-17 13:23:532985 delegate_->ExitFullscreenModeForTab(this);
Alexander Timin90c20c32020-08-12 15:28:322986 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2987 observer->DidDestroyFullscreenWidget();
2988 });
alexmosc9e76ec2016-05-16 22:59:372989 fullscreen_widget_process_id_ = ChildProcessHost::kInvalidUniqueID;
[email protected]44470a22013-01-24 01:21:542990 fullscreen_widget_routing_id_ = MSG_ROUTING_NONE;
[email protected]0b431992014-06-24 00:08:032991 if (fullscreen_widget_had_focus_at_shutdown_)
2992 view_->RestoreFocus();
[email protected]44470a22013-01-24 01:21:542993 }
lfgbee1e0a2016-06-08 21:24:212994
lfg7d4caad2017-03-22 09:01:452995 if (render_widget_host == mouse_lock_widget_)
lfgff8dfc8d2016-10-21 17:42:322996 LostMouseLock(mouse_lock_widget_);
Joe Downing192998b22018-03-22 15:51:362997
Joe Downingc1a57efe2018-05-09 18:23:542998 CancelKeyboardLock(render_widget_host);
[email protected]b24b68a2012-09-24 21:57:262999}
3000
miu9e14e492014-10-25 02:39:043001void WebContentsImpl::RenderWidgetGotFocus(
3002 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:373003 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderWidgetGotFocus",
3004 "render_widget_host", render_widget_host);
calamity7fe55ce2015-04-10 03:59:373005 // Notify the observers if an embedded fullscreen widget was focused.
3006 if (delegate_ && render_widget_host && delegate_->EmbedsFullscreenWidget() &&
3007 render_widget_host->GetView() == GetFullscreenRenderWidgetHostView()) {
Michael Thiessen896405db2017-07-20 17:52:323008 NotifyWebContentsFocused(render_widget_host);
calamity7fe55ce2015-04-10 03:59:373009 }
miu9e14e492014-10-25 02:39:043010}
3011
zijiehe3bee08e22017-05-17 04:14:463012void WebContentsImpl::RenderWidgetLostFocus(
3013 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:373014 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderWidgetLostFocus",
3015 "render_widget_host", render_widget_host);
Michael Thiessen896405db2017-07-20 17:52:323016 // Notify the observers if an embedded fullscreen widget lost focus.
3017 if (delegate_ && render_widget_host && delegate_->EmbedsFullscreenWidget() &&
3018 render_widget_host->GetView() == GetFullscreenRenderWidgetHostView()) {
3019 NotifyWebContentsLostFocus(render_widget_host);
3020 }
zijiehe3bee08e22017-05-17 04:14:463021}
3022
estaded0a0c992015-01-21 14:12:063023void WebContentsImpl::RenderWidgetWasResized(
rouslan2f5993f2015-01-29 00:18:313024 RenderWidgetHostImpl* render_widget_host,
3025 bool width_changed) {
Alexander Timin5fdeff22020-09-08 09:20:373026 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RenderWidgetWasResized",
3027 "render_widget_host", render_widget_host,
3028 "width_changed", width_changed);
creisc014b402015-04-23 16:41:453029 RenderFrameHostImpl* rfh = GetMainFrame();
estadece344ec2015-01-23 00:12:293030 if (!rfh || render_widget_host != rfh->GetRenderWidgetHost())
estaded0a0c992015-01-21 14:12:063031 return;
estaded0a0c992015-01-21 14:12:063032
Alexander Timin90c20c32020-08-12 15:28:323033 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3034 observer->MainFrameWasResized(width_changed);
3035 });
estaded0a0c992015-01-21 14:12:063036}
3037
skyf65d9bb2017-03-24 02:26:393038KeyboardEventProcessingResult WebContentsImpl::PreHandleKeyboardEvent(
3039 const NativeWebKeyboardEvent& event) {
Alexander Timin5fdeff22020-09-08 09:20:373040 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
3041 "WebContentsImpl::PreHandleKeyboardEvent");
W. James MacLeane1187272019-11-12 03:42:483042 auto* outermost_contents = GetOutermostWebContents();
3043 // TODO(wjmaclean): Generalize this to forward all key events to the outermost
3044 // delegate's handler.
Avi Drissman97aef042020-06-30 21:04:483045 if (outermost_contents != this && IsFullscreen() &&
W. James MacLeane1187272019-11-12 03:42:483046 event.windows_key_code == ui::VKEY_ESCAPE) {
3047 // When an inner WebContents has focus and is fullscreen, redirect <esc>
3048 // key events to the outermost WebContents so it can be handled by that
3049 // WebContents' delegate.
3050 if (outermost_contents->PreHandleKeyboardEvent(event) ==
3051 KeyboardEventProcessingResult::HANDLED) {
3052 return KeyboardEventProcessingResult::HANDLED;
3053 }
3054 }
skyf65d9bb2017-03-24 02:26:393055 return delegate_ ? delegate_->PreHandleKeyboardEvent(this, event)
3056 : KeyboardEventProcessingResult::NOT_HANDLED;
[email protected]63954792011-07-11 04:17:483057}
3058
Dave Tapuska344399e2019-09-09 15:18:263059bool WebContentsImpl::HandleMouseEvent(const blink::WebMouseEvent& event) {
Alexander Timin5fdeff22020-09-08 09:20:373060 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
3061 "WebContentsImpl::HandleMouseEvent");
Dave Tapuska344399e2019-09-09 15:18:263062 // Handle mouse button back/forward in the browser process after the render
3063 // process is done with the event. This ensures all renderer-initiated history
3064 // navigations can be treated consistently.
3065 if (event.GetType() == blink::WebInputEvent::Type::kMouseUp) {
3066 WebContentsImpl* outermost = GetOutermostWebContents();
3067 if (event.button == blink::WebPointerProperties::Button::kBack &&
3068 outermost->controller_.CanGoBack()) {
3069 outermost->controller_.GoBack();
3070 return true;
3071 } else if (event.button == blink::WebPointerProperties::Button::kForward &&
3072 outermost->controller_.CanGoForward()) {
3073 outermost->controller_.GoForward();
3074 return true;
3075 }
3076 }
3077 return false;
3078}
3079
Scott Violetd5caa872018-10-16 22:00:513080bool WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
Alexander Timin5fdeff22020-09-08 09:20:373081 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
3082 "WebContentsImpl::HandleKeyboardEvent");
[email protected]0b094002014-08-20 18:28:103083 if (browser_plugin_embedder_ &&
3084 browser_plugin_embedder_->HandleKeyboardEvent(event)) {
Scott Violetd5caa872018-10-16 22:00:513085 return true;
[email protected]0b094002014-08-20 18:28:103086 }
Scott Violetd5caa872018-10-16 22:00:513087 return delegate_ && delegate_->HandleKeyboardEvent(this, event);
[email protected]63954792011-07-11 04:17:483088}
3089
Alexander Timin5fdeff22020-09-08 09:20:373090bool WebContentsImpl::HandleWheelEvent(const blink::WebMouseWheelEvent& event) {
3091 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
3092 "WebContentsImpl::HandleWheelEvent");
Avi Drissman7c57be72020-07-29 20:09:463093#if !defined(OS_MAC)
lanweia93644f2015-01-21 22:00:333094 // On platforms other than Mac, control+mousewheel may change zoom. On Mac,
3095 // this isn't done for two reasons:
[email protected]bccc4472013-04-18 16:37:193096 // -the OS already has a gesture to do this through pinch-zoom
3097 // -if a user starts an inertial scroll, let's go, and presses control
3098 // (i.e. control+tab) then the OS's buffered scroll events will come in
3099 // with control key set which isn't what the user wants
Blink Reformat1c4d759e2017-04-09 16:34:543100 if (delegate_ && event.wheel_ticks_y &&
Ehsan Karamad0f83cb112018-09-06 22:07:363101 event.event_action == blink::WebMouseWheelEvent::EventAction::kPageZoom) {
w.shackleton49bcd392016-01-06 17:38:223102 // Count only integer cumulative scrolls as zoom events; this handles
3103 // smooth scroll and regular scroll device behavior.
Blink Reformat1c4d759e2017-04-09 16:34:543104 zoom_scroll_remainder_ += event.wheel_ticks_y;
w.shackleton49bcd392016-01-06 17:38:223105 int whole_zoom_scroll_remainder_ = std::lround(zoom_scroll_remainder_);
3106 zoom_scroll_remainder_ -= whole_zoom_scroll_remainder_;
3107 if (whole_zoom_scroll_remainder_ != 0) {
3108 delegate_->ContentsZoomChange(whole_zoom_scroll_remainder_ > 0);
3109 }
[email protected]fb3f066e2013-02-12 19:12:523110 return true;
3111 }
[email protected]bccc4472013-04-18 16:37:193112#endif
[email protected]fb3f066e2013-02-12 19:12:523113 return false;
3114}
3115
[email protected]04bce562014-01-30 05:34:543116bool WebContentsImpl::PreHandleGestureEvent(
3117 const blink::WebGestureEvent& event) {
Alexander Timin5fdeff22020-09-08 09:20:373118 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
3119 "WebContentsImpl::PreHandleGestureEvent");
[email protected]28042d32014-02-03 14:10:033120 return delegate_ && delegate_->PreHandleGestureEvent(this, event);
[email protected]04bce562014-01-30 05:34:543121}
3122
kenrb2a565f82015-09-02 20:24:593123RenderWidgetHostInputEventRouter* WebContentsImpl::GetInputEventRouter() {
wjmacleane31234f2015-12-14 17:20:453124 if (!is_being_destroyed_ && GetOuterWebContents())
3125 return GetOuterWebContents()->GetInputEventRouter();
3126
3127 if (!rwh_input_event_router_.get() && !is_being_destroyed_)
Fergal Daly55b6d722020-09-11 07:56:333128 rwh_input_event_router_ =
3129 std::make_unique<RenderWidgetHostInputEventRouter>();
kenrb2a565f82015-09-02 20:24:593130 return rwh_input_event_router_.get();
3131}
3132
alexmos3fcd0ca2015-10-23 18:18:333133void WebContentsImpl::ReplicatePageFocus(bool is_focused) {
Alexander Timin5fdeff22020-09-08 09:20:373134 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ReplicatePageFocus",
3135 "is_focused", is_focused);
alexmos3fcd0ca2015-10-23 18:18:333136 // Focus loss may occur while this WebContents is being destroyed. Don't
3137 // send the message in this case, as the main frame's RenderFrameHost and
3138 // other state has already been cleared.
3139 if (is_being_destroyed_)
3140 return;
3141
3142 frame_tree_.ReplicatePageFocus(is_focused);
3143}
3144
alexmosc4cbacb2015-11-21 01:29:223145RenderWidgetHostImpl* WebContentsImpl::GetFocusedRenderWidgetHost(
3146 RenderWidgetHostImpl* receiving_widget) {
alexmosc4cbacb2015-11-21 01:29:223147 // Events for widgets other than the main frame (e.g., popup menus) should be
3148 // forwarded directly to the widget they arrived on.
3149 if (receiving_widget != GetMainFrame()->GetRenderWidgetHost())
3150 return receiving_widget;
alexmosc4d183e2015-11-06 00:46:523151
paulmeyerfeafc2d2017-04-25 21:46:403152 // If the focused WebContents is a guest WebContents, then get the focused
3153 // frame in the embedder WebContents instead.
W. James MacLean13d834d2019-12-04 16:06:453154 FrameTreeNode* focused_frame =
3155 GetFocusedWebContents()->frame_tree_.GetFocusedFrame();
lfg1453e412017-04-11 00:48:503156
alexmosc4d183e2015-11-06 00:46:523157 if (!focused_frame)
alexmosc4cbacb2015-11-21 01:29:223158 return receiving_widget;
alexmosc4d183e2015-11-06 00:46:523159
alexmos732ca3a2015-12-08 02:01:023160 // The view may be null if a subframe's renderer process has crashed while
3161 // the subframe has focus. Drop the event in that case. Do not give
3162 // it to the main frame, so that the user doesn't unexpectedly type into the
3163 // wrong frame if a focused subframe renderer crashes while they type.
3164 RenderWidgetHostView* view = focused_frame->current_frame_host()->GetView();
3165 if (!view)
3166 return nullptr;
3167
3168 return RenderWidgetHostImpl::From(view->GetRenderWidgetHost());
alexmosc4d183e2015-11-06 00:46:523169}
3170
avallee9993fca2016-11-17 06:16:503171RenderWidgetHostImpl* WebContentsImpl::GetRenderWidgetHostWithPageFocus() {
lfg1453e412017-04-11 00:48:503172 WebContentsImpl* focused_web_contents = GetFocusedWebContents();
3173
lfg1453e412017-04-11 00:48:503174 return focused_web_contents->GetMainFrame()->GetRenderWidgetHost();
avallee9993fca2016-11-17 06:16:503175}
3176
Avi Drissmand1d25652020-03-06 21:28:583177bool WebContentsImpl::CanEnterFullscreenMode() {
Avi Drissman33972942020-06-19 14:16:013178 // It's possible that this WebContents was spawned while blocking UI was on
3179 // the screen, or that it was downstream from a WebContents when UI was
3180 // blocked. Therefore, disqualify it from fullscreen if it or any upstream
3181 // WebContents has an active blocker.
3182 auto openers = GetAllOpeningWebContents(this);
3183 return std::all_of(openers.begin(), openers.end(), [](auto* opener) {
3184 return opener->fullscreen_blocker_count_ == 0;
3185 });
Avi Drissmand1d25652020-03-06 21:28:583186}
3187
Dave Tapuska3ed44192018-05-01 18:53:303188void WebContentsImpl::EnterFullscreenMode(
Mike Wasserman4ca09792020-05-29 17:44:433189 RenderFrameHost* requesting_frame,
Dave Tapuskaa4189512019-10-15 20:27:343190 const blink::mojom::FullscreenOptions& options) {
Alexander Timin5fdeff22020-09-08 09:20:373191 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::EnterFullscreenMode");
Avi Drissmand1d25652020-03-06 21:28:583192 DCHECK(CanEnterFullscreenMode());
3193
mlamouri7a78d6fd2015-01-17 13:23:533194 // This method is being called to enter renderer-initiated fullscreen mode.
3195 // Make sure any existing fullscreen widget is shut down first.
[email protected]4aebbca2013-09-17 22:26:493196 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
avi85a4cef2015-12-18 20:13:373197 if (widget_view) {
3198 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())
3199 ->ShutdownAndDestroyWidget(true);
3200 }
[email protected]4aebbca2013-09-17 22:26:493201
Joe Downing13dd76b2018-04-09 18:32:153202 if (delegate_) {
Mike Wasserman4ca09792020-05-29 17:44:433203 delegate_->EnterFullscreenModeForTab(requesting_frame, options);
mlamouri7a78d6fd2015-01-17 13:23:533204
Joe Downing13dd76b2018-04-09 18:32:153205 if (keyboard_lock_widget_)
3206 delegate_->RequestKeyboardLock(this, esc_key_locked_);
3207 }
3208
Alexander Timin90c20c32020-08-12 15:28:323209 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3210 observer->DidToggleFullscreenModeForTab(IsFullscreen(), false);
3211 });
Avi Drissman33972942020-06-19 14:16:013212 FullscreenContentsSet(GetBrowserContext())->insert(this);
mlamouri7a78d6fd2015-01-17 13:23:533213}
3214
bokanece34a82016-01-28 19:49:463215void WebContentsImpl::ExitFullscreenMode(bool will_cause_resize) {
Alexander Timin5fdeff22020-09-08 09:20:373216 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ExitFullscreenMode",
3217 "will_cause_resize", will_cause_resize);
mlamouri7a78d6fd2015-01-17 13:23:533218 // This method is being called to leave renderer-initiated fullscreen mode.
3219 // Make sure any existing fullscreen widget is shut down first.
3220 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
avi85a4cef2015-12-18 20:13:373221 if (widget_view) {
3222 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())
3223 ->ShutdownAndDestroyWidget(true);
3224 }
mlamouri7a78d6fd2015-01-17 13:23:533225
Joe Downing13dd76b2018-04-09 18:32:153226 if (delegate_) {
mlamouri7a78d6fd2015-01-17 13:23:533227 delegate_->ExitFullscreenModeForTab(this);
[email protected]657c8e02014-03-19 19:18:373228
Joe Downing13dd76b2018-04-09 18:32:153229 if (keyboard_lock_widget_)
3230 delegate_->CancelKeyboardLockRequest(this);
3231 }
3232
bokanece34a82016-01-28 19:49:463233 // The fullscreen state is communicated to the renderer through a resize
3234 // message. If the change in fullscreen state doesn't cause a view resize
3235 // then we must ensure web contents exit the fullscreen state by explicitly
3236 // sending a resize message. This is required for the situation of the browser
3237 // moving the view into a "browser fullscreen" state and then the contents
3238 // entering "tab fullscreen". Exiting the contents "tab fullscreen" then won't
3239 // have the side effect of the view resizing, hence the explicit call here is
3240 // required.
3241 if (!will_cause_resize) {
3242 if (RenderWidgetHostView* rwhv = GetRenderWidgetHostView()) {
3243 if (RenderWidgetHost* render_widget_host = rwhv->GetRenderWidgetHost())
Fady Samuel0b911822018-04-25 13:22:163244 render_widget_host->SynchronizeVisualProperties();
bokanece34a82016-01-28 19:49:463245 }
scheib3dcb6c932015-02-23 10:55:583246 }
3247
Arthur Sonzogni929d29f2018-09-17 14:19:443248 current_fullscreen_frame_ = nullptr;
Becca Hughese9e27952018-06-25 17:08:273249
Alexander Timin90c20c32020-08-12 15:28:323250 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3251 observer->DidToggleFullscreenModeForTab(IsFullscreen(), will_cause_resize);
3252 });
Becca Hughesd11d6502018-07-31 17:01:283253
3254 if (display_cutout_host_impl_)
3255 display_cutout_host_impl_->DidExitFullscreen();
Avi Drissman33972942020-06-19 14:16:013256
3257 FullscreenContentsSet(GetBrowserContext())->erase(this);
[email protected]8a5e0ca2011-08-25 06:30:473258}
3259
Becca Hughesfd5d8f892018-06-14 18:23:363260void WebContentsImpl::FullscreenStateChanged(RenderFrameHost* rfh,
3261 bool is_fullscreen) {
Alexander Timin5fdeff22020-09-08 09:20:373262 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::FullscreenStateChanged",
3263 "render_frame_host", rfh, "is_fullscreen",
3264 is_fullscreen);
Arthur Sonzogni929d29f2018-09-17 14:19:443265 RenderFrameHostImpl* frame = static_cast<RenderFrameHostImpl*>(rfh);
Becca Hughesfd5d8f892018-06-14 18:23:363266
3267 if (is_fullscreen) {
Jan Wilken Dörrie531be7ca2019-06-07 10:05:573268 if (!base::Contains(fullscreen_frames_, frame)) {
Arthur Sonzogni929d29f2018-09-17 14:19:443269 fullscreen_frames_.insert(frame);
3270 FullscreenFrameSetUpdated();
Becca Hughesfd5d8f892018-06-14 18:23:363271 }
Arthur Sonzogni929d29f2018-09-17 14:19:443272 return;
3273 }
Becca Hughesfd5d8f892018-06-14 18:23:363274
Arthur Sonzogni929d29f2018-09-17 14:19:443275 // If |frame| is no longer in fullscreen, remove it and any descendants.
3276 // See https://fullscreen.spec.whatwg.org.
Arthur Sonzogni969a794e2018-10-11 08:56:093277 size_t size_before_deletion = fullscreen_frames_.size();
3278 base::EraseIf(fullscreen_frames_, [&](RenderFrameHostImpl* current) {
3279 return (current == frame || current->IsDescendantOf(frame));
Arthur Sonzogni929d29f2018-09-17 14:19:443280 });
3281
Arthur Sonzogni969a794e2018-10-11 08:56:093282 if (size_before_deletion != fullscreen_frames_.size())
Arthur Sonzogni929d29f2018-09-17 14:19:443283 FullscreenFrameSetUpdated();
3284}
3285
3286void WebContentsImpl::FullscreenFrameSetUpdated() {
Alexander Timin5fdeff22020-09-08 09:20:373287 OPTIONAL_TRACE_EVENT0("content",
3288 "WebContentsImpl::FullscreenFrameSetUpdated");
Arthur Sonzogni929d29f2018-09-17 14:19:443289 if (fullscreen_frames_.empty()) {
3290 current_fullscreen_frame_ = nullptr;
3291 return;
Becca Hughesfd5d8f892018-06-14 18:23:363292 }
3293
Arthur Sonzogni929d29f2018-09-17 14:19:443294 // Find the current fullscreen frame and call the observers.
3295 // If frame A is fullscreen, then frame B goes into inner fullscreen, then B
3296 // exits fullscreen - that will result in A being fullscreen.
3297 RenderFrameHostImpl* new_fullscreen_frame = *std::max_element(
3298 fullscreen_frames_.begin(), fullscreen_frames_.end(), FrameCompareDepth);
Becca Hughesfd5d8f892018-06-14 18:23:363299
Arthur Sonzogni929d29f2018-09-17 14:19:443300 // If we have already notified observers about this frame then we should not
3301 // fire the observers again.
3302 if (new_fullscreen_frame == current_fullscreen_frame_)
3303 return;
3304 current_fullscreen_frame_ = new_fullscreen_frame;
Becca Hughesfd5d8f892018-06-14 18:23:363305
Alexander Timin90c20c32020-08-12 15:28:323306 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3307 observer->DidAcquireFullscreen(new_fullscreen_frame);
3308 });
Arthur Sonzogni929d29f2018-09-17 14:19:443309 if (display_cutout_host_impl_)
3310 display_cutout_host_impl_->DidAcquireFullscreen(new_fullscreen_frame);
Becca Hughesfd5d8f892018-06-14 18:23:363311}
3312
Collin Baker989e0882019-11-01 01:27:173313void WebContentsImpl::UpdateVisibilityAndNotifyPageAndView(
3314 Visibility new_visibility) {
Alexander Timin5fdeff22020-09-08 09:20:373315 OPTIONAL_TRACE_EVENT1("content",
3316 "WebContentsImpl::UpdateVisibilityAndNotifyPageAndView",
3317 "new_visibility", static_cast<int>(new_visibility));
Collin Baker989e0882019-11-01 01:27:173318 // Only hide the page if there are no entities capturing screenshots
Collin Bakerc5259962019-11-14 17:51:583319 // or video (e.g. mirroring). If there are, apply the correct state of
3320 // kHidden or kHiddenButPainting.
3321 PageVisibilityState page_visibility;
3322 if (new_visibility == Visibility::VISIBLE || visible_capturer_count_ > 0)
3323 page_visibility = PageVisibilityState::kVisible;
3324 else if (hidden_capturer_count_ > 0)
3325 page_visibility = PageVisibilityState::kHiddenButPainting;
3326 else
3327 page_visibility = PageVisibilityState::kHidden;
Collin Baker989e0882019-11-01 01:27:173328 // If there are entities in Picture-in-Picture mode, don't activate
3329 // the "disable rendering" optimization.
Collin Bakerc5259962019-11-14 17:51:583330 const bool view_is_visible =
3331 page_visibility != PageVisibilityState::kHidden ||
3332 HasPictureInPictureVideo();
Collin Baker989e0882019-11-01 01:27:173333
Collin Bakerc5259962019-11-14 17:51:583334 if (page_visibility != PageVisibilityState::kHidden) {
Dana Friedcf3bc8e2019-11-13 20:00:243335 // We cannot show a page or capture video unless there is a valid renderer
3336 // associated with this web contents. The navigation controller for this
3337 // page must be set to active (allowing navigation to complete, a renderer
3338 // and its associated views to be created, etc.) if any of these conditions
3339 // holds.
3340 //
3341 // Previously, it was possible for browser-side code to try to capture video
3342 // from a restored tab (for a variety of reasons, including the browser
3343 // creating preview thumbnails) and the tab would never actually load. By
Collin Bakerc5259962019-11-14 17:51:583344 // keying this behavior off of |page_visibility| instead of just
Dana Friedcf3bc8e2019-11-13 20:00:243345 // |new_visibility| we avoid this case. See crbug.com/1020782 for more
3346 // context.
3347 controller_.SetActive(true);
3348
3349 // This shows the Page before showing the individual RenderWidgets, as
3350 // RenderWidgets will work to produce compositor frames and handle input
3351 // as soon as they are shown. But the Page and other classes do not expect
3352 // to be producing frames when the Page is hidden. So we make sure the Page
3353 // is shown first.
Yuzu Saijo232076f2020-05-29 07:14:023354 for (auto* rvh : GetRenderViewHostsIncludingBackForwardCached()) {
3355 rvh->SetVisibility(page_visibility);
Yuzu Saijobe024af02020-05-11 07:35:563356 }
Collin Baker98457b52019-11-06 21:34:293357 }
Collin Baker989e0882019-11-01 01:27:173358
3359 // |GetRenderWidgetHostView()| can be null if the user middle clicks a link to
3360 // open a tab in the background, then closes the tab before selecting it.
3361 // This is because closing the tab calls WebContentsImpl::Destroy(), which
3362 // removes the |GetRenderViewHost()|; then when we actually destroy the
3363 // window, OnWindowPosChanged() notices and calls WasHidden() (which
3364 // calls us).
3365 if (auto* view = GetRenderWidgetHostView()) {
3366 if (view_is_visible) {
3367 view->Show();
Collin Baker989e0882019-11-01 01:27:173368 } else if (new_visibility == Visibility::HIDDEN) {
3369 view->Hide();
3370 } else {
3371 view->WasOccluded();
3372 }
3373 }
3374
Carlos IL07f282f2020-05-15 22:58:293375 SetVisibilityForChildViews(view_is_visible);
Collin Baker989e0882019-11-01 01:27:173376
3377 // Make sure to call SetVisibilityAndNotifyObservers(VISIBLE) before notifying
3378 // the CrossProcessFrameConnector.
3379 if (new_visibility == Visibility::VISIBLE) {
3380 last_active_time_ = base::TimeTicks::Now();
3381 SetVisibilityAndNotifyObservers(new_visibility);
3382 }
3383
Collin Bakerc5259962019-11-14 17:51:583384 if (page_visibility == PageVisibilityState::kHidden) {
Collin Baker989e0882019-11-01 01:27:173385 // Similar to when showing the page, we only hide the page after
3386 // hiding the individual RenderWidgets.
Yuzu Saijo232076f2020-05-29 07:14:023387 for (auto* rvh : GetRenderViewHostsIncludingBackForwardCached()) {
3388 rvh->SetVisibility(page_visibility);
Yuzu Saijobe024af02020-05-11 07:35:563389 }
3390
Collin Baker989e0882019-11-01 01:27:173391 } else {
3392 for (FrameTreeNode* node : frame_tree_.Nodes()) {
3393 RenderFrameProxyHost* parent = node->render_manager()->GetProxyToParent();
3394 if (!parent)
3395 continue;
3396
3397 parent->cross_process_frame_connector()->DelegateWasShown();
3398 }
3399 }
3400
3401 if (new_visibility != Visibility::VISIBLE)
3402 SetVisibilityAndNotifyObservers(new_visibility);
3403}
3404
Clark DuValla0e42992018-09-17 17:00:113405#if defined(OS_ANDROID)
3406void WebContentsImpl::UpdateUserGestureCarryoverInfo() {
Alexander Timin5fdeff22020-09-08 09:20:373407 OPTIONAL_TRACE_EVENT0("content",
3408 "WebContentsImpl::UpdateUserGestureCarryoverInfo");
Clark DuValla0e42992018-09-17 17:00:113409 if (delegate_)
3410 delegate_->UpdateUserGestureCarryoverInfo(this);
3411}
3412#endif
3413
Avi Drissman97aef042020-06-30 21:04:483414bool WebContentsImpl::IsFullscreen() {
[email protected]199bba6e2012-04-04 16:19:383415 return delegate_ ? delegate_->IsFullscreenForTabOrPending(this) : false;
[email protected]5d5f7af2011-10-01 01:38:123416}
3417
Malay Keshav87c42c02019-01-15 08:37:473418bool WebContentsImpl::ShouldShowStaleContentOnEviction() {
3419 return GetDelegate() && GetDelegate()->ShouldShowStaleContentOnEviction(this);
3420}
3421
danakj45d42452020-04-08 17:24:183422blink::mojom::DisplayMode WebContentsImpl::GetDisplayMode() const {
mikhail.pozdnyakovc0e251b2015-04-15 06:51:123423 return delegate_ ? delegate_->GetDisplayMode(this)
Eric Willigers052f0432019-10-04 04:06:573424 : blink::mojom::DisplayMode::kBrowser;
mikhail.pozdnyakovc0e251b2015-04-15 06:51:123425}
3426
avic3aa8422015-11-09 20:57:223427void WebContentsImpl::RequestToLockMouse(
3428 RenderWidgetHostImpl* render_widget_host,
3429 bool user_gesture,
lfgad8244352016-07-13 16:55:513430 bool last_unlocked_by_target,
3431 bool privileged) {
Alexander Timin5fdeff22020-09-08 09:20:373432 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RequestToLockMouse",
3433 "render_widget_host", render_widget_host, "privileged",
3434 privileged);
lfgf0cd46e2017-01-04 00:05:233435 for (WebContentsImpl* current = this; current;
3436 current = current->GetOuterWebContents()) {
3437 if (current->mouse_lock_widget_) {
James Hollyerd5c9de462020-03-10 19:02:453438 render_widget_host->GotResponseToLockMouseRequest(
3439 blink::mojom::PointerLockResult::kAlreadyLocked);
lfgf0cd46e2017-01-04 00:05:233440 return;
3441 }
[email protected]e9621112011-10-17 05:38:373442 }
avic3aa8422015-11-09 20:57:223443
lfgad8244352016-07-13 16:55:513444 if (privileged) {
lfgf0cd46e2017-01-04 00:05:233445 DCHECK(!GetOuterWebContents());
lfgad8244352016-07-13 16:55:513446 mouse_lock_widget_ = render_widget_host;
James Hollyerd5c9de462020-03-10 19:02:453447 render_widget_host->GotResponseToLockMouseRequest(
3448 blink::mojom::PointerLockResult::kSuccess);
lfgad8244352016-07-13 16:55:513449 return;
3450 }
3451
lfgbee1e0a2016-06-08 21:24:213452 bool widget_in_frame_tree = false;
3453 for (FrameTreeNode* node : frame_tree_.Nodes()) {
3454 if (node->current_frame_host()->GetRenderWidgetHost() ==
3455 render_widget_host) {
3456 widget_in_frame_tree = true;
3457 break;
3458 }
3459 }
3460
3461 if (widget_in_frame_tree && delegate_) {
lfgf0cd46e2017-01-04 00:05:233462 for (WebContentsImpl* current = this; current;
3463 current = current->GetOuterWebContents()) {
3464 current->mouse_lock_widget_ = render_widget_host;
3465 }
3466
avic3aa8422015-11-09 20:57:223467 delegate_->RequestToLockMouse(this, user_gesture, last_unlocked_by_target);
lfgbee1e0a2016-06-08 21:24:213468 } else {
James Hollyerd5c9de462020-03-10 19:02:453469 render_widget_host->GotResponseToLockMouseRequest(
3470 blink::mojom::PointerLockResult::kWrongDocument);
lfgbee1e0a2016-06-08 21:24:213471 }
[email protected]e9621112011-10-17 05:38:373472}
3473
avi3e4b8512015-11-11 01:55:493474void WebContentsImpl::LostMouseLock(RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:373475 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::LostMouseLock",
3476 "render_widget_host", render_widget_host);
lfgbee1e0a2016-06-08 21:24:213477 CHECK(mouse_lock_widget_);
lfgf0cd46e2017-01-04 00:05:233478
3479 if (mouse_lock_widget_->delegate()->GetAsWebContents() != this)
3480 return mouse_lock_widget_->delegate()->LostMouseLock(render_widget_host);
3481
lfgbee1e0a2016-06-08 21:24:213482 mouse_lock_widget_->SendMouseLockLost();
lfgf0cd46e2017-01-04 00:05:233483 for (WebContentsImpl* current = this; current;
3484 current = current->GetOuterWebContents()) {
3485 current->mouse_lock_widget_ = nullptr;
3486 }
avi3e4b8512015-11-11 01:55:493487
[email protected]e9621112011-10-17 05:38:373488 if (delegate_)
3489 delegate_->LostMouseLock();
3490}
3491
lfgad8244352016-07-13 16:55:513492bool WebContentsImpl::HasMouseLock(RenderWidgetHostImpl* render_widget_host) {
3493 // To verify if the mouse is locked, the mouse_lock_widget_ needs to be
3494 // assigned to the widget that requested the mouse lock, and the top-level
3495 // platform RenderWidgetHostView needs to hold the mouse lock from the OS.
Lucas Gadania0ea0172018-09-20 18:31:373496 auto* widget_host = GetTopLevelRenderWidgetHostView();
3497 return mouse_lock_widget_ == render_widget_host && widget_host &&
3498 widget_host->IsMouseLocked();
lfgad8244352016-07-13 16:55:513499}
3500
lfg84763c92017-02-16 18:55:153501RenderWidgetHostImpl* WebContentsImpl::GetMouseLockWidget() {
Lucas Gadania0ea0172018-09-20 18:31:373502 auto* widget_host = GetTopLevelRenderWidgetHostView();
3503 if ((widget_host && widget_host->IsMouseLocked()) ||
lfge2176fb2017-03-26 00:45:473504 (GetFullscreenRenderWidgetHostView() &&
Lucas Gadania0ea0172018-09-20 18:31:373505 GetFullscreenRenderWidgetHostView()->IsMouseLocked())) {
lfg84763c92017-02-16 18:55:153506 return mouse_lock_widget_;
Lucas Gadania0ea0172018-09-20 18:31:373507 }
lfg84763c92017-02-16 18:55:153508
3509 return nullptr;
3510}
3511
Joe Downing192998b22018-03-22 15:51:363512bool WebContentsImpl::RequestKeyboardLock(
Joe Downing13dd76b2018-04-09 18:32:153513 RenderWidgetHostImpl* render_widget_host,
3514 bool esc_key_locked) {
Alexander Timin5fdeff22020-09-08 09:20:373515 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RequestKeyboardLock",
3516 "render_widget_host", render_widget_host,
3517 "esc_key_locked", esc_key_locked);
Joe Downing192998b22018-03-22 15:51:363518 DCHECK(render_widget_host);
Joe Downing192998b22018-03-22 15:51:363519 if (render_widget_host->delegate()->GetAsWebContents() != this) {
3520 NOTREACHED();
3521 return false;
3522 }
3523
3524 // KeyboardLock is only supported when called by the top-level browsing
3525 // context and is not supported in embedded content scenarios.
3526 if (GetOuterWebContents())
3527 return false;
3528
Joe Downing13dd76b2018-04-09 18:32:153529 esc_key_locked_ = esc_key_locked;
Joe Downing192998b22018-03-22 15:51:363530 keyboard_lock_widget_ = render_widget_host;
3531
Joe Downing13dd76b2018-04-09 18:32:153532 if (delegate_)
3533 delegate_->RequestKeyboardLock(this, esc_key_locked_);
Joe Downing192998b22018-03-22 15:51:363534 return true;
3535}
3536
3537void WebContentsImpl::CancelKeyboardLock(
3538 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:373539 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::CancelKeyboardLockRequest",
3540 "render_widget_host", render_widget_host);
Joe Downing192998b22018-03-22 15:51:363541 if (!keyboard_lock_widget_ || render_widget_host != keyboard_lock_widget_)
3542 return;
3543
3544 RenderWidgetHostImpl* old_keyboard_lock_widget = keyboard_lock_widget_;
3545 keyboard_lock_widget_ = nullptr;
3546
Joe Downing13dd76b2018-04-09 18:32:153547 if (delegate_)
3548 delegate_->CancelKeyboardLockRequest(this);
3549
Joe Downing192998b22018-03-22 15:51:363550 old_keyboard_lock_widget->CancelKeyboardLock();
3551}
3552
3553RenderWidgetHostImpl* WebContentsImpl::GetKeyboardLockWidget() {
3554 return keyboard_lock_widget_;
3555}
3556
Dave Tapuskac3344362019-02-20 17:54:283557void WebContentsImpl::OnRenderFrameProxyVisibilityChanged(
3558 blink::mojom::FrameVisibility visibility) {
Alexander Timin5fdeff22020-09-08 09:20:373559 OPTIONAL_TRACE_EVENT1("content",
3560 "WebContentsImpl::OnRenderFrameProxyVisibilityChanged",
3561 "visibility", static_cast<int>(visibility));
Dave Tapuskac3344362019-02-20 17:54:283562 switch (visibility) {
3563 case blink::mojom::FrameVisibility::kRenderedInViewport:
3564 WasShown();
3565 break;
3566 case blink::mojom::FrameVisibility::kNotRendered:
3567 WasHidden();
3568 break;
3569 case blink::mojom::FrameVisibility::kRenderedOutOfViewport:
3570 WasOccluded();
3571 break;
3572 }
ekaramada4f42692016-02-11 19:48:373573}
3574
Albert J. Wong65fe64d2019-09-20 02:48:143575RenderFrameHostDelegate* WebContentsImpl::CreateNewWindow(
csharrison95f01e922017-04-24 18:52:353576 RenderFrameHost* opener,
rockot5c478a72016-09-28 23:14:183577 const mojom::CreateNewWindowParams& params,
Albert J. Wong65fe64d2019-09-20 02:48:143578 bool is_new_browsing_instance,
Sergey Kuznetsov32257a22019-02-11 20:26:503579 bool has_user_gesture,
[email protected]97714c82012-06-06 10:15:133580 SessionStorageNamespace* session_storage_namespace) {
Alexander Timin5fdeff22020-09-08 09:20:373581 TRACE_EVENT2("browser,content,navigation", "WebContentsImpl::CreateNewWindow",
3582 "opener", base::trace_event::ToTracedValue(opener), "params",
3583 base::trace_event::ToTracedValue(params));
csharrison95f01e922017-04-24 18:52:353584 DCHECK(opener);
nick5ae4d2d2017-01-06 01:18:353585
csharrison95f01e922017-04-24 18:52:353586 int render_process_id = opener->GetProcess()->GetID();
csharrison95f01e922017-04-24 18:52:353587
Albert J. Wong65fe64d2019-09-20 02:48:143588 SiteInstance* source_site_instance = opener->GetSiteInstance();
nick5ae4d2d2017-01-06 01:18:353589
Aaron Colwelleb219982020-01-16 02:17:273590 const GURL source_site_url = source_site_instance->GetSiteURL();
[email protected]fdac6ade2013-07-20 01:06:303591 const std::string& partition_id =
Aaron Colwelleb219982020-01-16 02:17:273592 GetContentClient()->browser()->GetStoragePartitionIdForSite(
3593 GetBrowserContext(), source_site_url);
3594 {
3595 StoragePartition* partition = BrowserContext::GetStoragePartitionForSite(
3596 GetBrowserContext(), source_site_url);
3597 DOMStorageContextWrapper* dom_storage_context =
3598 static_cast<DOMStorageContextWrapper*>(
3599 partition->GetDOMStorageContext());
3600 SessionStorageNamespaceImpl* session_storage_namespace_impl =
3601 static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace);
3602 CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context));
3603 }
[email protected]dd6730412013-08-14 15:03:373604
Albert J. Wong1ceccef92019-10-08 08:25:203605 if (delegate_ && delegate_->IsWebContentsCreationOverridden(
3606 source_site_instance, params.window_container_type,
3607 opener->GetLastCommittedURL(), params.frame_name,
3608 params.target_url)) {
3609 return static_cast<WebContentsImpl*>(delegate_->CreateCustomWebContents(
3610 opener, source_site_instance, is_new_browsing_instance,
3611 opener->GetLastCommittedURL(), params.frame_name, params.target_url,
3612 partition_id, session_storage_namespace));
[email protected]dd6730412013-08-14 15:03:373613 }
3614
danakj22b4e8b2019-08-01 23:14:393615 bool renderer_started_hidden =
3616 params.disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB;
3617
Aaron Colwelleb219982020-01-16 02:17:273618 // We usually create the new window in the same BrowsingInstance (group of
3619 // script-related windows), by passing in the current SiteInstance. However,
3620 // if the opener is being suppressed (in a non-guest), we do not provide
3621 // a SiteInstance which causes a new one to get created in its own
3622 // BrowsingInstance.
3623 bool is_guest = BrowserPluginGuest::IsGuest(this);
3624 scoped_refptr<SiteInstance> site_instance =
3625 params.opener_suppressed && !is_guest ? nullptr : source_site_instance;
3626
[email protected]dd6730412013-08-14 15:03:373627 // Create the new web contents. This will automatically create the new
3628 // WebContentsView. In the future, we may want to create the view separately.
[email protected]fc72bb12013-06-02 21:13:463629 CreateParams create_params(GetBrowserContext(), site_instance.get());
nasko48321ca32015-07-02 20:44:123630 create_params.main_frame_name = params.frame_name;
alexmos4cf2aa32015-07-15 23:40:433631 create_params.opener_render_process_id = render_process_id;
csharrison95f01e922017-04-24 18:52:353632 create_params.opener_render_frame_id = opener->GetRoutingID();
[email protected]50d326e2014-05-20 17:59:063633 create_params.opener_suppressed = params.opener_suppressed;
danakj22b4e8b2019-08-01 23:14:393634 create_params.initially_hidden = renderer_started_hidden;
[email protected]50d326e2014-05-20 17:59:063635
Albert J. Wong65fe64d2019-09-20 02:48:143636 // Even though all codepaths leading here are in response to a renderer
3637 // tryng to open a new window, if the new window ends up in a different
3638 // browsing instance, then the RenderViewHost, RenderWidgetHost,
3639 // RenderFrameHost constellation is effectively browser initiated
3640 // the opener's process will not given the routing IDs for the new
3641 // objects.
3642 create_params.renderer_initiated_creation = !is_new_browsing_instance;
Albert J. Wong1ceccef92019-10-08 08:25:203643
Albert J. Wong65fe64d2019-09-20 02:48:143644 std::unique_ptr<WebContentsImpl> new_contents;
[email protected]c4538072013-03-18 02:17:553645 if (!is_guest) {
3646 create_params.context = view_->GetNativeView();
Albert J. Wong65fe64d2019-09-20 02:48:143647 new_contents = WebContentsImpl::Create(create_params);
3648 } else {
3649 new_contents = base::WrapUnique(static_cast<WebContentsImpl*>(
3650 GetBrowserPluginGuest()->CreateNewGuestWindow(create_params)));
[email protected]c4538072013-03-18 02:17:553651 }
Albert J. Wong65fe64d2019-09-20 02:48:143652 auto* new_contents_impl = new_contents.get();
danakje6c01622018-10-05 19:39:263653
3654 new_contents_impl->GetController().SetSessionStorageNamespace(
erikchenbee5c9622018-04-27 19:30:253655 partition_id, session_storage_namespace);
[email protected]d1198fd2012-08-13 22:50:193656
alexmos646fec02015-07-25 00:11:493657 // If the new frame has a name, make sure any SiteInstances that can find
3658 // this named frame have proxies for it. Must be called after
3659 // SetSessionStorageNamespace, since this calls CreateRenderView, which uses
3660 // GetSessionStorageNamespace.
3661 if (!params.frame_name.empty())
danakje6c01622018-10-05 19:39:263662 new_contents_impl->GetRenderManager()->CreateProxiesForNewNamedFrame();
alexmos646fec02015-07-25 00:11:493663
[email protected]c4538072013-03-18 02:17:553664 // Save the window for later if we're not suppressing the opener (since it
[email protected]d70bea92013-04-05 04:23:343665 // will be shown immediately).
3666 if (!params.opener_suppressed) {
3667 if (!is_guest) {
danakje6c01622018-10-05 19:39:263668 WebContentsView* new_view = new_contents_impl->view_.get();
[email protected]bafe6cd2012-05-23 23:09:503669
[email protected]d70bea92013-04-05 04:23:343670 // TODO(brettw): It seems bogus that we have to call this function on the
3671 // newly created object and give it one of its own member variables.
danakj22b4e8b2019-08-01 23:14:393672 RenderWidgetHostView* widget_view = new_view->CreateViewForWidget(
W. James MacLean13d834d2019-12-04 16:06:453673 new_contents_impl->GetRenderViewHost()->GetWidget());
danakj22b4e8b2019-08-01 23:14:393674 if (!renderer_started_hidden) {
3675 // RenderWidgets for frames always initialize as hidden. If the renderer
3676 // created this window as visible, then we show it here.
3677 widget_view->Show();
3678 }
[email protected]d70bea92013-04-05 04:23:343679 }
[email protected]bafe6cd2012-05-23 23:09:503680 // Save the created window associated with the route so we can show it
3681 // later.
Albert J. Wongcb004632018-07-10 22:58:253682 //
3683 // TODO(ajwong): This should be keyed off the RenderFrame routing id or the
3684 // FrameTreeNode id instead of the routing id of the Widget for the main
3685 // frame. https://crbug.com/545684
Fergal Daly052873a82020-03-11 14:45:493686 int32_t main_frame_routing_id = new_contents_impl->GetMainFrame()
3687 ->GetRenderWidgetHost()
3688 ->GetRoutingID();
3689 GlobalRoutingID id(render_process_id, main_frame_routing_id);
Joel Hockey8c2011b22020-04-30 05:07:193690 pending_contents_[id] =
3691 CreatedWindow(std::move(new_contents), params.target_url);
danakje6c01622018-10-05 19:39:263692 AddDestructionObserver(new_contents_impl);
[email protected]bafe6cd2012-05-23 23:09:503693 }
3694
3695 if (delegate_) {
Bryan McQuaded2b93c02017-07-14 22:26:313696 delegate_->WebContentsCreated(this, render_process_id,
3697 opener->GetRoutingID(), params.frame_name,
danakje6c01622018-10-05 19:39:263698 params.target_url, new_contents_impl);
[email protected]bafe6cd2012-05-23 23:09:503699 }
3700
Alexander Timin90c20c32020-08-12 15:28:323701 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3702 observer->DidOpenRequestedURL(new_contents_impl, opener, params.target_url,
3703 params.referrer.To<Referrer>(),
3704 params.disposition, ui::PAGE_TRANSITION_LINK,
3705 false, // started_from_context_menu
3706 true); // renderer_initiated
3707 });
pnolandaae574e2017-03-06 21:04:213708
[email protected]bafe6cd2012-05-23 23:09:503709 if (params.opener_suppressed) {
3710 // When the opener is suppressed, the original renderer cannot access the
3711 // new window. As a result, we need to show and navigate the window here.
[email protected]eda238a12012-09-07 23:44:003712 bool was_blocked = false;
erikchenbee5c9622018-04-27 19:30:253713
[email protected]eda238a12012-09-07 23:44:003714 if (delegate_) {
danakje6c01622018-10-05 19:39:263715 base::WeakPtr<WebContentsImpl> weak_new_contents =
3716 new_contents_impl->weak_factory_.GetWeakPtr();
nick0d558482017-02-13 22:27:223717
danakje6c01622018-10-05 19:39:263718 gfx::Rect initial_rect; // Report an empty initial rect.
Albert J. Wong65fe64d2019-09-20 02:48:143719 delegate_->AddNewContents(this, std::move(new_contents),
Joel Hockey891e88062020-04-30 05:38:443720 params.target_url, params.disposition,
3721 initial_rect, has_user_gesture, &was_blocked);
danakje6c01622018-10-05 19:39:263722 // The delegate may delete |new_contents_impl| during AddNewContents().
nick0d558482017-02-13 22:27:223723 if (!weak_new_contents)
Albert J. Wong65fe64d2019-09-20 02:48:143724 return nullptr;
[email protected]eda238a12012-09-07 23:44:003725 }
erikchenbee5c9622018-04-27 19:30:253726
[email protected]eda238a12012-09-07 23:44:003727 if (!was_blocked) {
Nasko Oskov83a8cf92018-10-19 14:58:563728 std::unique_ptr<NavigationController::LoadURLParams> load_params =
3729 std::make_unique<NavigationController::LoadURLParams>(
3730 params.target_url);
Nasko Oskov93e7c55c2018-12-19 01:59:293731 load_params->initiator_origin = opener->GetLastCommittedOrigin();
Lukasz Anforowiczd2629b42020-08-11 16:07:313732 // Avoiding setting |load_params->source_site_instance| when
3733 // |opener_suppressed| is true, because in that case we do not want to use
3734 // the old SiteInstance and/or BrowsingInstance. See also the test here:
3735 // NewPopupCOOP_SameOriginPolicyAndCrossOriginIframeSetsNoopener.
Leon Han963dc182018-11-06 05:41:483736 load_params->referrer = params.referrer.To<Referrer>();
Nasko Oskov83a8cf92018-10-19 14:58:563737 load_params->transition_type = ui::PAGE_TRANSITION_LINK;
3738 load_params->is_renderer_initiated = true;
Sergey Kuznetsov32257a22019-02-11 20:26:503739 load_params->has_user_gesture = has_user_gesture;
mariakhomenkoa4971c12015-07-21 19:04:373740
3741 if (delegate_ && !is_guest &&
3742 !delegate_->ShouldResumeRequestsForCreatedWindow()) {
Nasko Oskov83a8cf92018-10-19 14:58:563743 // We are in asynchronous add new contents path, delay navigation.
3744 DCHECK(!new_contents_impl->delayed_open_url_params_);
3745 new_contents_impl->delayed_load_url_params_ = std::move(load_params);
mariakhomenkoa4971c12015-07-21 19:04:373746 } else {
Nasko Oskov83a8cf92018-10-19 14:58:563747 new_contents_impl->controller_.LoadURLWithParams(*load_params.get());
Nasko Oskov28ebd5b2018-12-07 22:29:333748 if (!is_guest)
3749 new_contents_impl->Focus();
mariakhomenkoa4971c12015-07-21 19:04:373750 }
[email protected]eda238a12012-09-07 23:44:003751 }
[email protected]bafe6cd2012-05-23 23:09:503752 }
Albert J. Wong65fe64d2019-09-20 02:48:143753 return new_contents_impl;
[email protected]bafe6cd2012-05-23 23:09:503754}
3755
Dave Tapuskad9835622020-03-10 17:32:313756void WebContentsImpl::CreateNewWidget(
Tal Pressman5dcd2382020-08-26 07:13:053757 AgentSchedulingGroupHost& agent_scheduling_group,
3758 int32_t route_id,
Dave Tapuska8499eec2020-03-16 17:54:303759 mojo::PendingAssociatedReceiver<blink::mojom::WidgetHost> blink_widget_host,
3760 mojo::PendingAssociatedRemote<blink::mojom::Widget> blink_widget) {
Tal Pressman5dcd2382020-08-26 07:13:053761 CreateNewWidget(agent_scheduling_group, route_id,
3762 /*is_fullscreen=*/false, std::move(blink_widget_host),
3763 std::move(blink_widget));
[email protected]bafe6cd2012-05-23 23:09:503764}
3765
Julie Jeongeun Kimcaacf9102019-09-12 02:13:053766void WebContentsImpl::CreateNewFullscreenWidget(
Tal Pressman5dcd2382020-08-26 07:13:053767 AgentSchedulingGroupHost& agent_scheduling_group,
3768 int32_t route_id,
Dave Tapuska8499eec2020-03-16 17:54:303769 mojo::PendingAssociatedReceiver<blink::mojom::WidgetHost> blink_widget_host,
3770 mojo::PendingAssociatedRemote<blink::mojom::Widget> blink_widget) {
Tal Pressman5dcd2382020-08-26 07:13:053771 CreateNewWidget(agent_scheduling_group, route_id,
3772 /*is_fullscreen=*/true, std::move(blink_widget_host),
3773 std::move(blink_widget));
[email protected]bafe6cd2012-05-23 23:09:503774}
3775
Dave Tapuskad9835622020-03-10 17:32:313776void WebContentsImpl::CreateNewWidget(
Tal Pressman5dcd2382020-08-26 07:13:053777 AgentSchedulingGroupHost& agent_scheduling_group,
Dave Tapuskad9835622020-03-10 17:32:313778 int32_t route_id,
3779 bool is_fullscreen,
Dave Tapuska8499eec2020-03-16 17:54:303780 mojo::PendingAssociatedReceiver<blink::mojom::WidgetHost> blink_widget_host,
3781 mojo::PendingAssociatedRemote<blink::mojom::Widget> blink_widget) {
Alexander Timin5fdeff22020-09-08 09:20:373782 OPTIONAL_TRACE_EVENT1(
3783 "content", "WebContentsImpl::CreateNewWidget", "params",
3784 base::trace_event::TracedValue::Build(
3785 {{"route_id", route_id}, {"is_fullscreen", is_fullscreen}}));
Tal Pressman5dcd2382020-08-26 07:13:053786 RenderProcessHost* process = agent_scheduling_group.GetProcess();
kenrbb46f86a2015-12-07 07:53:233787 // A message to create a new widget can only come from an active process for
[email protected]a8504022013-12-04 20:23:513788 // this WebContentsImpl instance. If any other process sends the request,
3789 // it is invalid and the process must be terminated.
Tal Pressman5dcd2382020-08-26 07:13:053790 if (!HasMatchingProcess(&frame_tree_, process->GetID())) {
Lukasz Anforowicz6f746282018-01-04 23:24:513791 ReceivedBadMessage(process, bad_message::WCI_NEW_WIDGET_PROCESS_MISMATCH);
[email protected]a8504022013-12-04 20:23:513792 return;
3793 }
3794
Tal Pressman5dcd2382020-08-26 07:13:053795 RenderWidgetHostImpl* widget_host = new RenderWidgetHostImpl(
3796 this, agent_scheduling_group, route_id, IsHidden(),
3797 std::make_unique<FrameTokenMessageQueue>());
Dave Tapuska8499eec2020-03-16 17:54:303798
3799 widget_host->BindWidgetInterfaces(std::move(blink_widget_host),
3800 std::move(blink_widget));
[email protected]cfd80b02014-05-01 17:46:483801 RenderWidgetHostViewBase* widget_view =
3802 static_cast<RenderWidgetHostViewBase*>(
danakj0b246942018-09-17 21:30:273803 view_->CreateViewForChildWidget(widget_host));
[email protected]83918ec2013-01-10 15:37:193804 if (!widget_view)
3805 return;
danakj0b246942018-09-17 21:30:273806 // Fullscreen child widgets are frames, other child widgets are popups, and
3807 // popups should not get activated.
3808 if (!is_fullscreen)
3809 widget_view->SetWidgetType(WidgetType::kPopup);
[email protected]bafe6cd2012-05-23 23:09:503810 // Save the created widget associated with the route so we can show it later.
Tal Pressman5dcd2382020-08-26 07:13:053811 pending_widget_views_[GlobalRoutingID(process->GetID(), route_id)] =
alexmosc2a8cec2016-05-23 22:19:533812 widget_view;
[email protected]bafe6cd2012-05-23 23:09:503813}
3814
Mike Wassermandabad612020-08-13 04:26:273815void WebContentsImpl::ShowCreatedWindow(RenderFrameHost* opener,
nick5ae4d2d2017-01-06 01:18:353816 int main_frame_widget_route_id,
[email protected]bafe6cd2012-05-23 23:09:503817 WindowOpenDisposition disposition,
bokan107a47f2015-02-03 23:23:393818 const gfx::Rect& initial_rect,
[email protected]bafe6cd2012-05-23 23:09:503819 bool user_gesture) {
Alexander Timin5fdeff22020-09-08 09:20:373820 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::ShowCreatedWindow",
3821 "opener", base::trace_event::ToTracedValue(opener),
3822 "main_frame_widget_route_id",
3823 main_frame_widget_route_id);
danakje6c01622018-10-05 19:39:263824 // This method is the renderer requesting an existing top level window to
3825 // show a new top level window that the renderer created. Each top level
3826 // window is associated with a WebContents. In this case it was created
3827 // earlier but showing it was deferred until the renderer requested for it
3828 // to be shown. We find that previously created WebContents here.
3829 // TODO(danakj): Why do we defer this show step until the renderer asks for it
3830 // when it will always do so. What needs to happen in the renderer before we
3831 // reach here?
Mike Wassermandabad612020-08-13 04:26:273832 base::Optional<CreatedWindow> owned_created = GetCreatedWindow(
3833 opener->GetProcess()->GetID(), main_frame_widget_route_id);
Joel Hockey8c2011b22020-04-30 05:07:193834
danakje6c01622018-10-05 19:39:263835 // The browser may have rejected the request to make a new window, or the
3836 // renderer could be sending an invalid route id. Ignore the request then.
Joel Hockey8c2011b22020-04-30 05:07:193837 if (!owned_created || !owned_created->contents)
danakje6c01622018-10-05 19:39:263838 return;
mariakhomenko44bdc4732015-04-29 01:55:383839
Joel Hockey8c2011b22020-04-30 05:07:193840 WebContentsImpl* created = owned_created->contents.get();
3841
danakje6c01622018-10-05 19:39:263842 // This uses the delegate for the WebContents where the window was created
3843 // from, to control how to show the newly created window.
3844 WebContentsDelegate* delegate = GetDelegate();
nick5ae4d2d2017-01-06 01:18:353845
Mike Wassermanb6bc0152020-08-25 22:46:203846 // Individual members of |initial_rect| may be 0 to indicate that the
3847 // window.open() feature string did not specify a value. This code does not
3848 // have the ability to distinguish between an unspecified value and 0.
3849 // Assume that if any single value is non-zero, all values should be used.
3850 // TODO(crbug.com/897300): Plumb values as specified; set defaults here?
3851 gfx::Rect adjusted_rect = initial_rect;
3852 int64_t display_id = display::kInvalidDisplayId;
3853 if (adjusted_rect != gfx::Rect())
3854 display_id = AdjustRequestedWindowBounds(&adjusted_rect, opener);
3855
3856 // Drop fullscreen when opening a WebContents to prohibit deceptive behavior.
3857 // Only drop fullscreen on the specific destination display, if it is known.
3858 // This supports sites using cross-screen window placement capabilities to
3859 // retain fullscreen and open a window on another screen.
3860 ForSecurityDropFullscreen(display_id).RunAndReset();
3861
danakje6c01622018-10-05 19:39:263862 // The delegate can be null in tests, so we must check for it :(.
3863 if (delegate) {
3864 // Mark the web contents as pending resume, then immediately do
3865 // the resume if the delegate wants it.
3866 created->is_resume_pending_ = true;
3867 if (delegate->ShouldResumeRequestsForCreatedWindow())
3868 created->ResumeLoadingCreatedWebContents();
3869
3870 base::WeakPtr<WebContentsImpl> weak_created =
3871 created->weak_factory_.GetWeakPtr();
Joel Hockey8c2011b22020-04-30 05:07:193872 delegate->AddNewContents(this, std::move(owned_created->contents),
Joel Hockey891e88062020-04-30 05:38:443873 std::move(owned_created->target_url), disposition,
Mike Wassermandabad612020-08-13 04:26:273874 adjusted_rect, user_gesture, nullptr);
danakje6c01622018-10-05 19:39:263875 // The delegate may delete |created| during AddNewContents().
3876 if (!weak_created)
3877 return;
[email protected]eda238a12012-09-07 23:44:003878 }
danakje6c01622018-10-05 19:39:263879
3880 RenderWidgetHostImpl* rwh = created->GetMainFrame()->GetRenderWidgetHost();
3881 DCHECK_EQ(main_frame_widget_route_id, rwh->GetRoutingID());
3882 rwh->Send(new WidgetMsg_SetBounds_ACK(rwh->GetRoutingID()));
[email protected]bafe6cd2012-05-23 23:09:503883}
3884
alexmosc2a8cec2016-05-23 22:19:533885void WebContentsImpl::ShowCreatedWidget(int process_id,
Albert J. Wongf6e13ed2018-09-18 15:25:473886 int widget_route_id,
bokan107a47f2015-02-03 23:23:393887 const gfx::Rect& initial_rect) {
Alexander Timin5fdeff22020-09-08 09:20:373888 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::ShowCreatedWidget",
3889 "process_id", process_id, "widget_route_id",
3890 widget_route_id);
Albert J. Wongf6e13ed2018-09-18 15:25:473891 ShowCreatedWidget(process_id, widget_route_id, false, initial_rect);
[email protected]bafe6cd2012-05-23 23:09:503892}
3893
alexmosc2a8cec2016-05-23 22:19:533894void WebContentsImpl::ShowCreatedFullscreenWidget(int process_id,
Albert J. Wongf6e13ed2018-09-18 15:25:473895 int widget_route_id) {
Alexander Timin5fdeff22020-09-08 09:20:373896 OPTIONAL_TRACE_EVENT2(
3897 "content", "WebContentsImpl::ShowCreatedFullscreenWidget", "process_id",
3898 process_id, "widget_route_id", widget_route_id);
Albert J. Wongf6e13ed2018-09-18 15:25:473899 ShowCreatedWidget(process_id, widget_route_id, true, gfx::Rect());
[email protected]bafe6cd2012-05-23 23:09:503900}
3901
alexmosc2a8cec2016-05-23 22:19:533902void WebContentsImpl::ShowCreatedWidget(int process_id,
3903 int route_id,
[email protected]bafe6cd2012-05-23 23:09:503904 bool is_fullscreen,
bokan107a47f2015-02-03 23:23:393905 const gfx::Rect& initial_rect) {
[email protected]cfd80b02014-05-01 17:46:483906 RenderWidgetHostViewBase* widget_host_view =
alexmosc2a8cec2016-05-23 22:19:533907 static_cast<RenderWidgetHostViewBase*>(
3908 GetCreatedWidget(process_id, route_id));
[email protected]bafe6cd2012-05-23 23:09:503909 if (!widget_host_view)
3910 return;
[email protected]cfd80b02014-05-01 17:46:483911
W. James MacLeanec4125c2019-09-27 18:56:003912 // GetOutermostWebContents() returns |this| if there are no outer WebContents.
W. James MacLean3c5f50462019-10-28 16:24:213913 auto* outer_web_contents = GetOuterWebContents();
3914 auto* outermost_web_contents = GetOutermostWebContents();
W. James MacLeanec4125c2019-09-27 18:56:003915 RenderWidgetHostView* view =
W. James MacLean3c5f50462019-10-28 16:24:213916 outermost_web_contents->GetRenderWidgetHostView();
3917 // It's not entirely obvious why we need the transform only in the case where
3918 // the outer webcontents is not the same as the outermost webcontents. It may
3919 // be due to the fact that oopifs that are children of the mainframe get
3920 // correct values for their screenrects, but deeper cross-process frames do
3921 // not. Hopefully this can be resolved with https://crbug.com/928825.
3922 // Handling these cases separately is needed for http://crbug.com/1015298.
3923 bool needs_transform = this != outermost_web_contents &&
3924 outermost_web_contents != outer_web_contents;
W. James MacLeanec4125c2019-09-27 18:56:003925
3926 gfx::Rect transformed_rect(initial_rect);
3927 RenderWidgetHostView* this_view = GetRenderWidgetHostView();
W. James MacLean3c5f50462019-10-28 16:24:213928 if (needs_transform) {
W. James MacLeanec4125c2019-09-27 18:56:003929 // We need to transform the coordinates of initial_rect.
3930 gfx::Point origin =
3931 this_view->TransformPointToRootCoordSpace(initial_rect.origin());
3932 gfx::Point bottom_right =
3933 this_view->TransformPointToRootCoordSpace(initial_rect.bottom_right());
3934 transformed_rect =
3935 gfx::Rect(origin.x(), origin.y(), bottom_right.x() - origin.x(),
3936 bottom_right.y() - origin.y());
[email protected]cfd80b02014-05-01 17:46:483937 }
3938
danakj0b246942018-09-17 21:30:273939 // Fullscreen child widgets are frames, other child widgets are popups.
[email protected]4aebbca2013-09-17 22:26:493940 if (is_fullscreen) {
[email protected]d7f80ba2013-10-12 07:42:313941 DCHECK_EQ(MSG_ROUTING_NONE, fullscreen_widget_routing_id_);
[email protected]0b431992014-06-24 00:08:033942 view_->StoreFocus();
alexmosc9e76ec2016-05-16 22:59:373943 fullscreen_widget_process_id_ =
3944 widget_host_view->GetRenderWidgetHost()->GetProcess()->GetID();
[email protected]d7f80ba2013-10-12 07:42:313945 fullscreen_widget_routing_id_ = route_id;
[email protected]4aebbca2013-09-17 22:26:493946 if (delegate_ && delegate_->EmbedsFullscreenWidget()) {
3947 widget_host_view->InitAsChild(GetRenderWidgetHostView()->GetNativeView());
Mike Wasserman4ca09792020-05-29 17:44:433948 delegate_->EnterFullscreenModeForTab(GetMainFrame(),
Dave Tapuskaa4189512019-10-15 20:27:343949 blink::mojom::FullscreenOptions());
[email protected]4aebbca2013-09-17 22:26:493950 } else {
[email protected]cfd80b02014-05-01 17:46:483951 widget_host_view->InitAsFullscreen(view);
[email protected]4aebbca2013-09-17 22:26:493952 }
Alexander Timin90c20c32020-08-12 15:28:323953 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3954 observer->DidShowFullscreenWidget();
3955 });
[email protected]4aebbca2013-09-17 22:26:493956 if (!widget_host_view->HasFocus())
3957 widget_host_view->Focus();
3958 } else {
W. James MacLeanec4125c2019-09-27 18:56:003959 widget_host_view->InitAsPopup(view, transformed_rect);
[email protected]4aebbca2013-09-17 22:26:493960 }
[email protected]89054502012-06-03 10:29:243961
yiyixcb1fbc4f2018-03-16 19:54:083962 RenderWidgetHostImpl* render_widget_host_impl = widget_host_view->host();
[email protected]89054502012-06-03 10:29:243963 render_widget_host_impl->Init();
[email protected]d7f80ba2013-10-12 07:42:313964 // Only allow privileged mouse lock for fullscreen render widget, which is
3965 // used to implement Pepper Flash fullscreen.
3966 render_widget_host_impl->set_allow_privileged_mouse_lock(is_fullscreen);
[email protected]bafe6cd2012-05-23 23:09:503967}
3968
Joel Hockey8c2011b22020-04-30 05:07:193969base::Optional<CreatedWindow> WebContentsImpl::GetCreatedWindow(
nick5ae4d2d2017-01-06 01:18:353970 int process_id,
3971 int main_frame_widget_route_id) {
Alexander Timin5fdeff22020-09-08 09:20:373972 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::GetCreatedWindow",
3973 "process_id", process_id, "main_frame_widget_route_id",
3974 main_frame_widget_route_id);
3975
Lukasz Anforowicz09060bdf72018-08-23 15:53:173976 auto key = GlobalRoutingID(process_id, main_frame_widget_route_id);
nick5ae4d2d2017-01-06 01:18:353977 auto iter = pending_contents_.find(key);
[email protected]bafe6cd2012-05-23 23:09:503978
3979 // Certain systems can block the creation of new windows. If we didn't succeed
3980 // in creating one, just return NULL.
alexmosc2a8cec2016-05-23 22:19:533981 if (iter == pending_contents_.end())
Joel Hockey8c2011b22020-04-30 05:07:193982 return base::nullopt;
[email protected]bafe6cd2012-05-23 23:09:503983
Joel Hockey8c2011b22020-04-30 05:07:193984 CreatedWindow result = std::move(iter->second);
3985 WebContentsImpl* new_contents = result.contents.get();
nick5ae4d2d2017-01-06 01:18:353986 pending_contents_.erase(key);
Joel Hockey8c2011b22020-04-30 05:07:193987 RemoveDestructionObserver(new_contents);
[email protected]bafe6cd2012-05-23 23:09:503988
[email protected]d70bea92013-04-05 04:23:343989 // Don't initialize the guest WebContents immediately.
Joel Hockey8c2011b22020-04-30 05:07:193990 if (BrowserPluginGuest::IsGuest(new_contents))
3991 return result;
[email protected]d70bea92013-04-05 04:23:343992
Lukasz Anforowicz5510ed652018-06-06 16:16:193993 if (!new_contents->GetMainFrame()->GetProcess()->IsInitializedAndNotDead() ||
nick5ae4d2d2017-01-06 01:18:353994 !new_contents->GetMainFrame()->GetView()) {
Joel Hockey8c2011b22020-04-30 05:07:193995 return base::nullopt;
nick5ae4d2d2017-01-06 01:18:353996 }
[email protected]bafe6cd2012-05-23 23:09:503997
Joel Hockey8c2011b22020-04-30 05:07:193998 return result;
[email protected]bafe6cd2012-05-23 23:09:503999}
4000
alexmosc2a8cec2016-05-23 22:19:534001RenderWidgetHostView* WebContentsImpl::GetCreatedWidget(int process_id,
4002 int route_id) {
Alexander Timin5fdeff22020-09-08 09:20:374003 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::GetCreatedWidget",
4004 "process_id", process_id, "route_id", route_id);
4005
Lukasz Anforowicz09060bdf72018-08-23 15:53:174006 auto iter = pending_widget_views_.find(GlobalRoutingID(process_id, route_id));
[email protected]bafe6cd2012-05-23 23:09:504007 if (iter == pending_widget_views_.end()) {
4008 DCHECK(false);
alexmosc2a8cec2016-05-23 22:19:534009 return nullptr;
[email protected]bafe6cd2012-05-23 23:09:504010 }
4011
4012 RenderWidgetHostView* widget_host_view = iter->second;
Lukasz Anforowicz09060bdf72018-08-23 15:53:174013 pending_widget_views_.erase(GlobalRoutingID(process_id, route_id));
[email protected]bafe6cd2012-05-23 23:09:504014
4015 RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
Lukasz Anforowicz5510ed652018-06-06 16:16:194016 if (!widget_host->GetProcess()->IsInitializedAndNotDead()) {
[email protected]bafe6cd2012-05-23 23:09:504017 // The view has gone away or the renderer crashed. Nothing to do.
alexmosc2a8cec2016-05-23 22:19:534018 return nullptr;
[email protected]bafe6cd2012-05-23 23:09:504019 }
4020
4021 return widget_host_view;
4022}
4023
[email protected]f13b4202012-06-12 23:53:234024void WebContentsImpl::RequestMediaAccessPermission(
[email protected]33662e52013-01-07 21:31:094025 const MediaStreamRequest& request,
Mark Pilgrim57499082018-06-12 12:38:304026 MediaResponseCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:374027 OPTIONAL_TRACE_EVENT2("content",
4028 "WebContentsImpl::RequestMediaAccessPermission",
4029 "render_process_id", request.render_process_id,
4030 "render_frame_id", request.render_frame_id);
4031
[email protected]d19b84b2014-03-14 11:52:374032 if (delegate_) {
Mark Pilgrim57499082018-06-12 12:38:304033 delegate_->RequestMediaAccessPermission(this, request, std::move(callback));
[email protected]d19b84b2014-03-14 11:52:374034 } else {
Antonio Gomes0d42960a2019-06-05 12:35:514035 std::move(callback).Run(
4036 blink::MediaStreamDevices(),
4037 blink::mojom::MediaStreamRequestResult::FAILED_DUE_TO_SHUTDOWN,
4038 std::unique_ptr<MediaStreamUI>());
[email protected]d19b84b2014-03-14 11:52:374039 }
[email protected]f13b4202012-06-12 23:53:234040}
4041
Chandan Padhia4b8bcb72017-09-12 16:41:044042bool WebContentsImpl::CheckMediaAccessPermission(
Raymes Khouryad7c24a12018-03-05 23:22:584043 RenderFrameHost* render_frame_host,
Chandan Padhia4b8bcb72017-09-12 16:41:044044 const url::Origin& security_origin,
Antonio Gomesc8b734b2019-06-05 18:22:164045 blink::mojom::MediaStreamType type) {
Alexander Timin5fdeff22020-09-08 09:20:374046 OPTIONAL_TRACE_EVENT2("content",
4047 "WebContentsImpl::CheckMediaAccessPermission",
4048 "render_frame_host", render_frame_host,
4049 "security_origin", security_origin.Serialize());
4050
Antonio Gomesc8b734b2019-06-05 18:22:164051 DCHECK(type == blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE ||
4052 type == blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE);
Chandan Padhia4b8bcb72017-09-12 16:41:044053 return delegate_ && delegate_->CheckMediaAccessPermission(
Raymes Khouryad7c24a12018-03-05 23:22:584054 render_frame_host, security_origin.GetURL(), type);
grunell657d4d82014-09-18 00:09:434055}
4056
Guido Urdaneta73fa6632019-01-14 18:46:264057std::string WebContentsImpl::GetDefaultMediaDeviceID(
Antonio Gomesc8b734b2019-06-05 18:22:164058 blink::mojom::MediaStreamType type) {
Alexander Timin5fdeff22020-09-08 09:20:374059 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::GetDefaultMediaDeviceID",
4060 "type", static_cast<int>(type));
4061
guidou8a440b842017-01-30 13:58:434062 if (!delegate_)
4063 return std::string();
4064 return delegate_->GetDefaultMediaDeviceID(this, type);
4065}
4066
[email protected]cc9200432013-07-23 23:02:404067SessionStorageNamespace* WebContentsImpl::GetSessionStorageNamespace(
4068 SiteInstance* instance) {
4069 return controller_.GetSessionStorageNamespace(instance);
4070}
4071
[email protected]6de7fc482014-06-06 10:46:444072SessionStorageNamespaceMap WebContentsImpl::GetSessionStorageNamespaceMap() {
4073 return controller_.GetSessionStorageNamespaceMap();
4074}
4075
[email protected]9b159a52013-10-03 17:24:554076FrameTree* WebContentsImpl::GetFrameTree() {
4077 return &frame_tree_;
4078}
4079
aelias5252baa2016-04-10 01:18:024080bool WebContentsImpl::IsOverridingUserAgent() {
4081 return GetController().GetVisibleEntry() &&
4082 GetController().GetVisibleEntry()->GetIsOverridingUserAgent();
4083}
4084
avi85ee8362016-10-08 02:09:084085bool WebContentsImpl::IsJavaScriptDialogShowing() const {
4086 return is_showing_javascript_dialog_;
4087}
4088
avic031d392017-03-03 03:09:424089bool WebContentsImpl::ShouldIgnoreUnresponsiveRenderer() {
Dominique Fauteux-Chapleau99244382020-07-08 20:37:004090 if (suppress_unresponsive_renderer_count_ > 0)
4091 return true;
4092
avic031d392017-03-03 03:09:424093 // Ignore unresponsive renderers if the debugger is attached to them since the
4094 // unresponsiveness might be a result of the renderer sitting on a breakpoint.
4095 //
David Bienvenu525f8a02019-02-15 02:02:424096#ifdef OS_WIN
4097 // Check if a windows debugger is attached to the renderer process.
4098 base::ProcessHandle process_handle =
4099 GetMainFrame()->GetProcess()->GetProcess().Handle();
4100 BOOL debugger_present = FALSE;
4101 if (CheckRemoteDebuggerPresent(process_handle, &debugger_present) &&
4102 debugger_present)
4103 return true;
4104#endif // OS_WIN
4105
avic031d392017-03-03 03:09:424106 // TODO(pfeldman): Fix this to only return true if the renderer is *actually*
4107 // sitting on a breakpoint. https://crbug.com/684202
4108 return DevToolsAgentHost::IsDebuggerAttached(this);
4109}
4110
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414111ui::AXMode WebContentsImpl::GetAccessibilityMode() {
[email protected]95640212014-07-26 18:14:304112 return accessibility_mode_;
4113}
4114
Mario Sanchez Prada5d7f1ac2020-07-16 17:18:404115void WebContentsImpl::AXTreeIDForMainFrameHasChanged() {
Alexander Timin5fdeff22020-09-08 09:20:374116 OPTIONAL_TRACE_EVENT0("content",
4117 "WebContentsImpl::AXTreeIDForMainFrameHasChanged");
4118
Mario Sanchez Prada5d7f1ac2020-07-16 17:18:404119 RenderWidgetHostViewBase* rwhv =
4120 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
4121 if (rwhv)
4122 rwhv->SetMainFrameAXTreeID(GetMainFrame()->GetAXTreeID());
4123
Alexander Timin90c20c32020-08-12 15:28:324124 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4125 observer->AXTreeIDForMainFrameHasChanged();
4126 });
Mario Sanchez Prada5d7f1ac2020-07-16 17:18:404127}
4128
Dominic Mazzonia7b0edb22017-08-09 16:32:514129void WebContentsImpl::AccessibilityEventReceived(
Dominic Mazzoniccbaa9b2018-06-06 07:44:234130 const AXEventNotificationDetails& details) {
Alexander Timin5fdeff22020-09-08 09:20:374131 OPTIONAL_TRACE_EVENT0("content",
4132 "WebContentsImpl::AccessibilityEventReceived");
Alexander Timin90c20c32020-08-12 15:28:324133 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4134 observer->AccessibilityEventReceived(details);
4135 });
[email protected]31a71eaf2014-03-13 01:47:364136}
4137
dmazzoni2400c462016-08-23 15:07:134138void WebContentsImpl::AccessibilityLocationChangesReceived(
4139 const std::vector<AXLocationChangeNotificationDetails>& details) {
Alexander Timin5fdeff22020-09-08 09:20:374140 OPTIONAL_TRACE_EVENT0(
4141 "content", "WebContentsImpl::AccessibilityLocationChangesReceived");
Alexander Timin90c20c32020-08-12 15:28:324142 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4143 observer->AccessibilityLocationChangesReceived(details);
4144 });
dmazzoni2400c462016-08-23 15:07:134145}
4146
Alexander Surkov2ab51622020-09-02 12:01:424147std::string WebContentsImpl::DumpAccessibilityTree(
Abigail Kleinabb428332019-09-13 18:26:214148 bool internal,
4149 std::vector<AccessibilityTreeFormatter::PropertyFilter> property_filters) {
Alexander Timin5fdeff22020-09-08 09:20:374150 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DumpAccessibilityTree");
James Wallace-Leeeafc94cb92018-07-23 21:35:094151 auto* ax_mgr = GetOrCreateRootBrowserAccessibilityManager();
4152 DCHECK(ax_mgr);
Lei Zhangc98caa3822019-11-07 19:17:274153 return AccessibilityTreeFormatterBase::DumpAccessibilityTreeFromManager(
Abigail Kleinabb428332019-09-13 18:26:214154 ax_mgr, internal, property_filters);
James Wallace-Leeeafc94cb92018-07-23 21:35:094155}
4156
Abigail Kleinaa898742019-11-01 02:31:254157void WebContentsImpl::RecordAccessibilityEvents(
Abigail Kleinbb8304bd2020-05-18 21:44:184158 bool start_recording,
4159 base::Optional<AccessibilityEventCallback> callback) {
Alexander Timin5fdeff22020-09-08 09:20:374160 OPTIONAL_TRACE_EVENT0("content",
4161 "WebContentsImpl::RecordAccessibilityEvents");
Abigail Kleinbb8304bd2020-05-18 21:44:184162 // Only pass a callback to RecordAccessibilityEvents when starting to record.
4163 DCHECK_EQ(start_recording, callback.has_value());
4164 if (start_recording) {
Abigail Kleinaa898742019-11-01 02:31:254165 SetAccessibilityMode(ui::AXMode::kWebContents);
4166 auto* ax_mgr = GetOrCreateRootBrowserAccessibilityManager();
4167 DCHECK(ax_mgr);
4168 base::ProcessId pid = base::Process::Current().Pid();
Alexander Surkov97e969632020-09-29 02:30:054169 event_recorder_ = content::AccessibilityEventRecorder::Create(ax_mgr, pid);
Abigail Kleinbb8304bd2020-05-18 21:44:184170 event_recorder_->ListenToEvents(*callback);
Abigail Kleinaa898742019-11-01 02:31:254171 } else {
Abigail Kleinbb8304bd2020-05-18 21:44:184172 if (event_recorder_) {
4173 event_recorder_->FlushAsyncEvents();
4174 event_recorder_.reset(nullptr);
4175 }
Abigail Kleinaa898742019-11-01 02:31:254176 }
4177}
4178
Ke He7319dbe2017-11-09 05:54:444179device::mojom::GeolocationContext* WebContentsImpl::GetGeolocationContext() {
Alexander Timin5fdeff22020-09-08 09:20:374180 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GetGeolocationContext");
Ella Ge3e375b702020-06-05 15:57:164181 if (delegate_) {
4182 auto* installed_webapp_context =
4183 delegate_->GetInstalledWebappGeolocationContext();
4184 if (installed_webapp_context)
4185 return installed_webapp_context;
4186 }
4187
Ken Rockotce010f02019-12-12 23:32:324188 if (!geolocation_context_) {
4189 GetDeviceService().BindGeolocationContext(
4190 geolocation_context_.BindNewPipeAndPassReceiver());
4191 }
Conley Owens6894c4f2017-07-10 19:29:134192 return geolocation_context_.get();
blundellc57b93f2014-10-29 13:19:574193}
4194
ke.he98b761e2017-05-09 05:59:174195device::mojom::WakeLockContext* WebContentsImpl::GetWakeLockContext() {
blundelld8cd72b2017-03-28 07:18:384196 if (!wake_lock_context_host_)
Fergal Daly55b6d722020-09-11 07:56:334197 wake_lock_context_host_ = std::make_unique<WakeLockContextHost>(this);
blundelle75a8f92017-03-27 08:11:174198 return wake_lock_context_host_->GetWakeLockContext();
alogvinovf50445a2015-10-30 13:00:124199}
4200
blundellf5316fc2017-05-15 11:49:034201#if defined(OS_ANDROID)
Miyoung Shin59f39ff2019-09-17 07:23:204202void WebContentsImpl::GetNFC(
Reilly Grantafbe2242020-02-20 21:14:554203 RenderFrameHost* render_frame_host,
Miyoung Shin59f39ff2019-09-17 07:23:204204 mojo::PendingReceiver<device::mojom::NFC> receiver) {
Reilly Grantafbe2242020-02-20 21:14:554205 if (!nfc_host_)
4206 nfc_host_ = std::make_unique<NFCHost>(this);
4207 nfc_host_->GetNFC(render_frame_host, std::move(receiver));
blundellf5316fc2017-05-15 11:49:034208}
4209#endif
4210
Evan Stade5e750ad02017-08-07 21:59:274211void WebContentsImpl::SetNotWaitingForResponse() {
Alexander Timin5fdeff22020-09-08 09:20:374212 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetNotWaitingForResponse",
4213 "was_waiting_for_response", waiting_for_response_);
Evan Stade5e750ad02017-08-07 21:59:274214 if (waiting_for_response_ == false)
4215 return;
4216
4217 waiting_for_response_ = false;
Alexander Timin90c20c32020-08-12 15:28:324218 observers_.ForEachObserver(
4219 [&](WebContentsObserver* observer) { observer->DidReceiveResponse(); });
Bruce Dawsone1c5c842020-09-15 02:09:144220
4221 // LoadingStateChanged must be called last in case it triggers deletion of
4222 // |this| due to recursive message pumps.
4223 if (delegate_)
4224 delegate_->LoadingStateChanged(this, is_load_to_different_document_);
Evan Stade5e750ad02017-08-07 21:59:274225}
4226
lfgbb9c28a2016-03-01 03:19:494227void WebContentsImpl::SendScreenRects() {
Alexander Timin5fdeff22020-09-08 09:20:374228 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SendScreenRects");
kenrbc52e1b4e2016-03-20 01:03:374229 for (FrameTreeNode* node : frame_tree_.Nodes()) {
kenrb0e8dc202016-05-30 19:51:404230 if (node->current_frame_host()->is_local_root())
kenrbc52e1b4e2016-03-20 01:03:374231 node->current_frame_host()->GetRenderWidgetHost()->SendScreenRects();
4232 }
[email protected]32deec62013-05-15 23:55:044233}
4234
ekaramadadd882292016-06-08 15:22:564235TextInputManager* WebContentsImpl::GetTextInputManager() {
4236 if (GetOuterWebContents())
4237 return GetOuterWebContents()->GetTextInputManager();
4238
Ehsan Karamadc179dc02018-12-15 03:09:294239 if (!text_input_manager_ && !browser_plugin_guest_) {
Fergal Daly55b6d722020-09-11 07:56:334240 text_input_manager_ = std::make_unique<TextInputManager>(
Darren Shenca53d5f2018-05-15 04:56:014241 GetBrowserContext() &&
Fergal Daly55b6d722020-09-11 07:56:334242 !GetBrowserContext()->IsOffTheRecord() /* should_do_learning */);
Darren Shenca53d5f2018-05-15 04:56:014243 }
ekaramadadd882292016-06-08 15:22:564244
4245 return text_input_manager_.get();
4246}
4247
paulmeyer7f6f1d4f2016-11-15 00:00:274248bool WebContentsImpl::OnUpdateDragCursor() {
Alexander Timin5fdeff22020-09-08 09:20:374249 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnUpdateDragCursor");
Lei Zhang6410ec1a2019-01-31 21:38:584250 return browser_plugin_embedder_ &&
4251 browser_plugin_embedder_->OnUpdateDragCursor();
paulmeyer7f6f1d4f2016-11-15 00:00:274252}
4253
kenrb11f213a2017-03-24 18:12:064254bool WebContentsImpl::IsWidgetForMainFrame(
4255 RenderWidgetHostImpl* render_widget_host) {
4256 return render_widget_host == GetMainFrame()->GetRenderWidgetHost();
4257}
4258
[email protected]95640212014-07-26 18:14:304259BrowserAccessibilityManager*
Alexander Timin5fdeff22020-09-08 09:20:374260WebContentsImpl::GetRootBrowserAccessibilityManager() {
Carlos ILd51e7702020-05-07 18:51:394261 RenderFrameHostImpl* rfh = static_cast<RenderFrameHostImpl*>(GetMainFrame());
creisc014b402015-04-23 16:41:454262 return rfh ? rfh->browser_accessibility_manager() : nullptr;
[email protected]95640212014-07-26 18:14:304263}
4264
4265BrowserAccessibilityManager*
Alexander Timin5fdeff22020-09-08 09:20:374266WebContentsImpl::GetOrCreateRootBrowserAccessibilityManager() {
Carlos ILd51e7702020-05-07 18:51:394267 RenderFrameHostImpl* rfh = static_cast<RenderFrameHostImpl*>(GetMainFrame());
creisc014b402015-04-23 16:41:454268 return rfh ? rfh->GetOrCreateBrowserAccessibilityManager() : nullptr;
[email protected]95640212014-07-26 18:14:304269}
4270
Dave Tapuskab336b922017-07-06 19:24:054271void WebContentsImpl::ExecuteEditCommand(
4272 const std::string& command,
4273 const base::Optional<base::string16>& value) {
Alexander Timin5fdeff22020-09-08 09:20:374274 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ExecuteEditCommand");
Dave Tapuska58a099e2020-06-08 21:48:404275 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514276 if (!input_handler)
Dave Tapuskab336b922017-07-06 19:24:054277 return;
4278
Dave Tapuskae782bea2019-07-09 16:21:514279 input_handler->ExecuteEditCommand(command, value);
Dave Tapuskab336b922017-07-06 19:24:054280}
4281
mohsen7ab1ec16ec2015-07-02 18:26:234282void WebContentsImpl::MoveRangeSelectionExtent(const gfx::Point& extent) {
Alexander Timin5fdeff22020-09-08 09:20:374283 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MoveRangeSelectionExtent");
Dave Tapuska58a099e2020-06-08 21:48:404284 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514285 if (!input_handler)
mohsen7ab1ec16ec2015-07-02 18:26:234286 return;
4287
Dave Tapuskae782bea2019-07-09 16:21:514288 input_handler->MoveRangeSelectionExtent(extent);
mohsen7ab1ec16ec2015-07-02 18:26:234289}
4290
4291void WebContentsImpl::SelectRange(const gfx::Point& base,
4292 const gfx::Point& extent) {
Alexander Timin5fdeff22020-09-08 09:20:374293 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SelectRange");
Dave Tapuska58a099e2020-06-08 21:48:404294 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514295 if (!input_handler)
mohsen7ab1ec16ec2015-07-02 18:26:234296 return;
4297
Dave Tapuskae782bea2019-07-09 16:21:514298 input_handler->SelectRange(base, extent);
mohsen7ab1ec16ec2015-07-02 18:26:234299}
4300
Dave Tapuskab336b922017-07-06 19:24:054301void WebContentsImpl::MoveCaret(const gfx::Point& extent) {
Alexander Timin5fdeff22020-09-08 09:20:374302 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
4303 "WebContentsImpl::MoveCaret");
Dave Tapuska58a099e2020-06-08 21:48:404304 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514305 if (!input_handler)
Dave Tapuskab336b922017-07-06 19:24:054306 return;
4307
Dave Tapuskae782bea2019-07-09 16:21:514308 input_handler->MoveCaret(extent);
Dave Tapuskab336b922017-07-06 19:24:054309}
4310
Shimi Zhang37deeb22017-09-28 00:59:014311void WebContentsImpl::AdjustSelectionByCharacterOffset(
4312 int start_adjust,
4313 int end_adjust,
4314 bool show_selection_menu) {
Alexander Timin5fdeff22020-09-08 09:20:374315 OPTIONAL_TRACE_EVENT0("content",
4316 "WebContentsImpl::AdjustSelectionByCharacterOffset");
Dave Tapuska58a099e2020-06-08 21:48:404317 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514318 if (!input_handler)
aurimasab0319022015-07-10 21:57:384319 return;
4320
Shimi Zhang37deeb22017-09-28 00:59:014321 using blink::mojom::SelectionMenuBehavior;
Dave Tapuskae782bea2019-07-09 16:21:514322 input_handler->AdjustSelectionByCharacterOffset(
Shimi Zhang37deeb22017-09-28 00:59:014323 start_adjust, end_adjust,
4324 show_selection_menu ? SelectionMenuBehavior::kShow
4325 : SelectionMenuBehavior::kHide);
aurimasab0319022015-07-10 21:57:384326}
4327
[email protected]b172aee2012-04-10 17:05:264328void WebContentsImpl::UpdatePreferredSize(const gfx::Size& pref_size) {
Alexander Timin5fdeff22020-09-08 09:20:374329 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::UpdatePreferredSize");
[email protected]222f5822014-02-05 23:40:494330 const gfx::Size old_size = GetPreferredSize();
[email protected]bcd2815602012-01-14 18:17:234331 preferred_size_ = pref_size;
[email protected]222f5822014-02-05 23:40:494332 OnPreferredSizeChanged(old_size);
[email protected]0548c5352011-09-07 00:33:334333}
4334
avic3aa8422015-11-09 20:57:224335void WebContentsImpl::ResizeDueToAutoResize(
4336 RenderWidgetHostImpl* render_widget_host,
Fady Samuel97947112018-05-05 16:24:544337 const gfx::Size& new_size) {
Alexander Timin5fdeff22020-09-08 09:20:374338 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ResizeDueToAutoResize",
4339 "render_widget_host", render_widget_host);
avic3aa8422015-11-09 20:57:224340 if (render_widget_host != GetRenderViewHost()->GetWidget())
4341 return;
4342
[email protected]61e2b3cc2012-03-02 16:13:344343 if (delegate_)
4344 delegate_->ResizeDueToAutoResize(this, new_size);
4345}
4346
[email protected]b172aee2012-04-10 17:05:264347WebContents* WebContentsImpl::OpenURL(const OpenURLParams& params) {
Alexander Timin5fdeff22020-09-08 09:20:374348 TRACE_EVENT1("content", "WebContentsImpl::OpenURL", "url",
4349 base::trace_event::ValueToString(params.url));
Aaron Colwell9dab1652019-12-09 18:29:494350#if DCHECK_IS_ON()
4351 DCHECK(params.Valid());
4352#endif
4353
Bo Liu300c6052018-06-12 04:46:074354 if (!delegate_) {
4355 // Embedder can delay setting a delegate on new WebContents with
4356 // WebContentsDelegate::ShouldResumeRequestsForCreatedWindow. In the mean
4357 // time, navigations, including the initial one, that goes through OpenURL
4358 // should be delayed until embedder is ready to resume loading.
4359 delayed_open_url_params_ = std::make_unique<OpenURLParams>(params);
Nasko Oskov83a8cf92018-10-19 14:58:564360
4361 // If there was a navigation deferred when creating the window through
4362 // CreateNewWindow, drop it in favor of this navigation.
4363 delayed_load_url_params_.reset();
4364
Ivan Kotenkov2c0d2bb32017-11-01 15:41:284365 return nullptr;
Bo Liu300c6052018-06-12 04:46:074366 }
[email protected]00c37fc2011-08-02 00:22:504367
[email protected]e5d549d2011-12-28 01:29:204368 WebContents* new_contents = delegate_->OpenURLFromTab(this, params);
pnoland488944652017-02-22 18:58:544369
4370 RenderFrameHost* source_render_frame_host = RenderFrameHost::FromID(
4371 params.source_render_process_id, params.source_render_frame_id);
4372
4373 if (source_render_frame_host && params.source_site_instance) {
4374 CHECK_EQ(source_render_frame_host->GetSiteInstance(),
4375 params.source_site_instance.get());
4376 }
4377
4378 if (new_contents && source_render_frame_host && new_contents != this) {
Alexander Timin90c20c32020-08-12 15:28:324379 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4380 observer->DidOpenRequestedURL(
Lukasz Anforowicz48c9f872018-08-01 00:58:414381 new_contents, source_render_frame_host, params.url, params.referrer,
4382 params.disposition, params.transition,
4383 params.started_from_context_menu, params.is_renderer_initiated);
Alexander Timin90c20c32020-08-12 15:28:324384 });
pnoland488944652017-02-22 18:58:544385 }
4386
[email protected]e5d549d2011-12-28 01:29:204387 return new_contents;
[email protected]d5f942ba2008-09-26 19:30:344388}
4389
avi2b177592014-12-10 02:08:024390void WebContentsImpl::SetHistoryOffsetAndLength(int history_offset,
4391 int history_length) {
Alexander Timin5fdeff22020-09-08 09:20:374392 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetHistoryOffsetAndLength",
4393 "history_offset", history_offset, "history_length",
4394 history_length);
alexmos136fd6e62016-08-15 20:58:414395 SendPageMessage(new PageMsg_SetHistoryOffsetAndLength(
4396 MSG_ROUTING_NONE, history_offset, history_length));
avi2b177592014-12-10 02:08:024397}
4398
4399void WebContentsImpl::SetHistoryOffsetAndLengthForView(
4400 RenderViewHost* render_view_host,
4401 int history_offset,
4402 int history_length) {
Alexander Timin5fdeff22020-09-08 09:20:374403 OPTIONAL_TRACE_EVENT2(
4404 "content", "WebContentsImpl::SetHistoryOffsetAndLengthForView",
4405 "history_offset", history_offset, "history_length", history_length);
alexmos136fd6e62016-08-15 20:58:414406 render_view_host->Send(new PageMsg_SetHistoryOffsetAndLength(
avi2b177592014-12-10 02:08:024407 render_view_host->GetRoutingID(), history_offset, history_length));
[email protected]796931a92011-08-10 01:32:144408}
4409
arthursonzogni818c2642019-09-27 12:18:104410void WebContentsImpl::ReloadFocusedFrame() {
Alexander Timin5fdeff22020-09-08 09:20:374411 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ReloadFocusedFrame");
[email protected]1f3fc1d2014-04-03 14:50:174412 RenderFrameHost* focused_frame = GetFocusedFrame();
4413 if (!focused_frame)
4414 return;
4415
yilkal921048bd2019-10-09 23:51:044416 focused_frame->Reload();
[email protected]959be4c2014-04-08 15:01:334417}
4418
4419void WebContentsImpl::Undo() {
Alexander Timin5fdeff22020-09-08 09:20:374420 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Undo");
Dave Tapuska58a099e2020-06-08 21:48:404421 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514422 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334423 return;
4424
Dave Tapuskae782bea2019-07-09 16:21:514425 input_handler->Undo();
[email protected]959be4c2014-04-08 15:01:334426 RecordAction(base::UserMetricsAction("Undo"));
4427}
4428
4429void WebContentsImpl::Redo() {
Alexander Timin5fdeff22020-09-08 09:20:374430 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Redo");
Dave Tapuska58a099e2020-06-08 21:48:404431 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514432 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334433 return;
Dave Tapuskae782bea2019-07-09 16:21:514434
4435 input_handler->Redo();
[email protected]959be4c2014-04-08 15:01:334436 RecordAction(base::UserMetricsAction("Redo"));
4437}
4438
4439void WebContentsImpl::Cut() {
Alexander Timin5fdeff22020-09-08 09:20:374440 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Cut");
Dave Tapuska58a099e2020-06-08 21:48:404441 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514442 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334443 return;
4444
Dave Tapuskae782bea2019-07-09 16:21:514445 input_handler->Cut();
[email protected]959be4c2014-04-08 15:01:334446 RecordAction(base::UserMetricsAction("Cut"));
4447}
4448
4449void WebContentsImpl::Copy() {
Alexander Timin5fdeff22020-09-08 09:20:374450 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Copy");
Dave Tapuska58a099e2020-06-08 21:48:404451 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514452 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334453 return;
4454
Dave Tapuskae782bea2019-07-09 16:21:514455 input_handler->Copy();
[email protected]959be4c2014-04-08 15:01:334456 RecordAction(base::UserMetricsAction("Copy"));
4457}
4458
4459void WebContentsImpl::CopyToFindPboard() {
Alexander Timin5fdeff22020-09-08 09:20:374460 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::CopyToFindPboard");
Avi Drissman7c57be72020-07-29 20:09:464461#if defined(OS_MAC)
Dave Tapuska58a099e2020-06-08 21:48:404462 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514463 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334464 return;
4465
4466 // Windows/Linux don't have the concept of a find pasteboard.
Dave Tapuskae782bea2019-07-09 16:21:514467 input_handler->CopyToFindPboard();
[email protected]959be4c2014-04-08 15:01:334468 RecordAction(base::UserMetricsAction("CopyToFindPboard"));
4469#endif
4470}
4471
4472void WebContentsImpl::Paste() {
Alexander Timin5fdeff22020-09-08 09:20:374473 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Paste");
Dave Tapuska58a099e2020-06-08 21:48:404474 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514475 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334476 return;
4477
Dave Tapuskae782bea2019-07-09 16:21:514478 input_handler->Paste();
Alexander Timin90c20c32020-08-12 15:28:324479 observers_.ForEachObserver(
4480 [&](WebContentsObserver* observer) { observer->OnPaste(); });
[email protected]959be4c2014-04-08 15:01:334481 RecordAction(base::UserMetricsAction("Paste"));
4482}
4483
4484void WebContentsImpl::PasteAndMatchStyle() {
Alexander Timin5fdeff22020-09-08 09:20:374485 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::PasteAndMatchStyle");
Dave Tapuska58a099e2020-06-08 21:48:404486 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514487 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334488 return;
4489
Dave Tapuskae782bea2019-07-09 16:21:514490 input_handler->PasteAndMatchStyle();
Alexander Timin90c20c32020-08-12 15:28:324491 observers_.ForEachObserver(
4492 [&](WebContentsObserver* observer) { observer->OnPaste(); });
[email protected]959be4c2014-04-08 15:01:334493 RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
4494}
4495
4496void WebContentsImpl::Delete() {
Alexander Timin5fdeff22020-09-08 09:20:374497 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Delete");
Dave Tapuska58a099e2020-06-08 21:48:404498 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514499 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334500 return;
4501
Dave Tapuskae782bea2019-07-09 16:21:514502 input_handler->Delete();
[email protected]959be4c2014-04-08 15:01:334503 RecordAction(base::UserMetricsAction("DeleteSelection"));
4504}
4505
4506void WebContentsImpl::SelectAll() {
Alexander Timin5fdeff22020-09-08 09:20:374507 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SelectAll");
Dave Tapuska58a099e2020-06-08 21:48:404508 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514509 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334510 return;
4511
Dave Tapuskae782bea2019-07-09 16:21:514512 input_handler->SelectAll();
[email protected]959be4c2014-04-08 15:01:334513 RecordAction(base::UserMetricsAction("SelectAll"));
4514}
4515
yabinh351e7ec2017-03-10 02:43:244516void WebContentsImpl::CollapseSelection() {
Alexander Timin5fdeff22020-09-08 09:20:374517 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::CollapseSelection");
Dave Tapuska58a099e2020-06-08 21:48:404518 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514519 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334520 return;
4521
Dave Tapuskae782bea2019-07-09 16:21:514522 input_handler->CollapseSelection();
[email protected]1f3fc1d2014-04-03 14:50:174523}
4524
4525void WebContentsImpl::Replace(const base::string16& word) {
Alexander Timin5fdeff22020-09-08 09:20:374526 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Replace");
Dave Tapuska58a099e2020-06-08 21:48:404527 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514528 if (!input_handler)
[email protected]1f3fc1d2014-04-03 14:50:174529 return;
4530
Dave Tapuskae782bea2019-07-09 16:21:514531 input_handler->Replace(word);
[email protected]1f3fc1d2014-04-03 14:50:174532}
4533
4534void WebContentsImpl::ReplaceMisspelling(const base::string16& word) {
Alexander Timin5fdeff22020-09-08 09:20:374535 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ReplaceMisspelling");
Dave Tapuska58a099e2020-06-08 21:48:404536 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514537 if (!input_handler)
[email protected]1f3fc1d2014-04-03 14:50:174538 return;
4539
Dave Tapuskae782bea2019-07-09 16:21:514540 input_handler->ReplaceMisspelling(word);
[email protected]959be4c2014-04-08 15:01:334541}
4542
4543void WebContentsImpl::NotifyContextMenuClosed(
4544 const CustomContextMenuContext& context) {
Alexander Timin5fdeff22020-09-08 09:20:374545 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::NotifyContextMenuClosed");
[email protected]959be4c2014-04-08 15:01:334546 RenderFrameHost* focused_frame = GetFocusedFrame();
4547 if (!focused_frame)
4548 return;
4549
4550 focused_frame->Send(new FrameMsg_ContextMenuClosed(
4551 focused_frame->GetRoutingID(), context));
4552}
4553
4554void WebContentsImpl::ExecuteCustomContextMenuCommand(
4555 int action, const CustomContextMenuContext& context) {
Alexander Timin5fdeff22020-09-08 09:20:374556 OPTIONAL_TRACE_EVENT1("content",
4557 "WebContentsImpl::ExecuteCustomContextMenuCommand",
4558 "action", action);
[email protected]959be4c2014-04-08 15:01:334559 RenderFrameHost* focused_frame = GetFocusedFrame();
4560 if (!focused_frame)
4561 return;
4562
4563 focused_frame->Send(new FrameMsg_CustomContextMenuAction(
4564 focused_frame->GetRoutingID(), context, action));
[email protected]4fed3702014-04-01 09:08:004565}
4566
[email protected]fc2b46b2014-05-03 16:33:454567gfx::NativeView WebContentsImpl::GetNativeView() {
4568 return view_->GetNativeView();
4569}
4570
4571gfx::NativeView WebContentsImpl::GetContentNativeView() {
4572 return view_->GetContentNativeView();
4573}
4574
4575gfx::NativeWindow WebContentsImpl::GetTopLevelNativeWindow() {
4576 return view_->GetTopLevelNativeWindow();
4577}
4578
4579gfx::Rect WebContentsImpl::GetViewBounds() {
4580 return view_->GetViewBounds();
4581}
4582
4583gfx::Rect WebContentsImpl::GetContainerBounds() {
Jeremy Roman352239c2020-05-21 16:31:324584 return view_->GetContainerBounds();
[email protected]fc2b46b2014-05-03 16:33:454585}
4586
4587DropData* WebContentsImpl::GetDropData() {
4588 return view_->GetDropData();
4589}
4590
4591void WebContentsImpl::Focus() {
Alexander Timin5fdeff22020-09-08 09:20:374592 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Focus");
miu9e14e492014-10-25 02:39:044593 view_->Focus();
[email protected]fc2b46b2014-05-03 16:33:454594}
4595
4596void WebContentsImpl::SetInitialFocus() {
Alexander Timin5fdeff22020-09-08 09:20:374597 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetInitialFocus");
miu9e14e492014-10-25 02:39:044598 view_->SetInitialFocus();
[email protected]fc2b46b2014-05-03 16:33:454599}
4600
4601void WebContentsImpl::StoreFocus() {
Alexander Timin5fdeff22020-09-08 09:20:374602 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::StoreFocus");
miu9e14e492014-10-25 02:39:044603 view_->StoreFocus();
[email protected]fc2b46b2014-05-03 16:33:454604}
4605
4606void WebContentsImpl::RestoreFocus() {
Alexander Timin5fdeff22020-09-08 09:20:374607 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::RestoreFocus");
miu9e14e492014-10-25 02:39:044608 view_->RestoreFocus();
[email protected]fc2b46b2014-05-03 16:33:454609}
4610
[email protected]b172aee2012-04-10 17:05:264611void WebContentsImpl::FocusThroughTabTraversal(bool reverse) {
Alexander Timin5fdeff22020-09-08 09:20:374612 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::FocusThroughTabTraversal",
4613 "reverse", reverse);
Maxim Podgorodskiya926c4ff2017-11-20 02:06:394614 view_->FocusThroughTabTraversal(reverse);
[email protected]96d185d2009-04-24 03:28:544615}
4616
[email protected]b172aee2012-04-10 17:05:264617bool WebContentsImpl::IsSavable() {
[email protected]a53209b2012-01-20 16:48:164618 // WebKit creates Document object when MIME type is application/xhtml+xml,
4619 // so we also support this MIME type.
Yuzu Saijoc23e9b72020-06-25 07:21:274620 std::string mime_type = GetContentsMimeType();
4621 return mime_type == "text/html" || mime_type == "text/xml" ||
4622 mime_type == "application/xhtml+xml" || mime_type == "text/plain" ||
4623 mime_type == "text/css" ||
4624 blink::IsSupportedJavascriptMimeType(mime_type);
[email protected]a53209b2012-01-20 16:48:164625}
4626
[email protected]b172aee2012-04-10 17:05:264627void WebContentsImpl::OnSavePage() {
Alexander Timin5fdeff22020-09-08 09:20:374628 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnSavePage");
[email protected]c7dd2f62011-07-18 15:57:594629 // If we can not save the page, try to download it.
[email protected]a53209b2012-01-20 16:48:164630 if (!IsSavable()) {
Min Qinda0ed2062018-02-23 22:00:534631 download::RecordSavePackageEvent(
4632 download::SAVE_PACKAGE_DOWNLOAD_ON_NON_HTML);
nasko89ad7742015-03-05 22:14:194633 SaveFrame(GetLastCommittedURL(), Referrer());
[email protected]27678b2a2012-02-04 22:09:144634 return;
[email protected]c7dd2f62011-07-18 15:57:594635 }
4636
4637 Stop();
4638
4639 // Create the save package and possibly prompt the user for the name to save
4640 // the page as. The user prompt is an asynchronous operation that runs on
4641 // another thread.
4642 save_package_ = new SavePackage(this);
4643 save_package_->GetSaveInfo();
4644}
4645
4646// Used in automated testing to bypass prompting the user for file names.
4647// Instead, the names and paths are hard coded rather than running them through
4648// file name sanitation and extension / mime checking.
[email protected]2dec8ec2013-02-07 19:20:344649bool WebContentsImpl::SavePage(const base::FilePath& main_file,
4650 const base::FilePath& dir_path,
[email protected]8ff00d72012-10-23 19:12:214651 SavePageType save_type) {
Alexander Timin5fdeff22020-09-08 09:20:374652 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SavePage", "main_file",
4653 base::trace_event::ValueToString(main_file), "dir_path",
4654 base::trace_event::ValueToString(dir_path));
[email protected]c7dd2f62011-07-18 15:57:594655 // Stop the page from navigating.
4656 Stop();
4657
4658 save_package_ = new SavePackage(this, save_type, main_file, dir_path);
[email protected]8ff00d72012-10-23 19:12:214659 return save_package_->Init(SavePackageDownloadCreatedCallback());
[email protected]c7dd2f62011-07-18 15:57:594660}
4661
Alexander Timin5fdeff22020-09-08 09:20:374662void WebContentsImpl::SaveFrame(const GURL& url, const Referrer& referrer) {
4663 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SaveFrame");
Xing Liu10329bf2018-03-20 19:22:144664 SaveFrameWithHeaders(url, referrer, std::string(), base::string16());
kundaji6c7f9692015-03-09 18:00:374665}
4666
Xing Liu10329bf2018-03-20 19:22:144667void WebContentsImpl::SaveFrameWithHeaders(
4668 const GURL& url,
4669 const Referrer& referrer,
4670 const std::string& headers,
4671 const base::string16& suggested_filename) {
Alexander Timin5fdeff22020-09-08 09:20:374672 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SaveFrameWithHeaders",
4673 "url", base::trace_event::ValueToString(url), "headers",
4674 headers);
Lei Zhang13a42e42019-02-19 23:28:114675 // Check and see if the guest can handle this.
4676 if (delegate_) {
4677 WebContents* guest_web_contents = nullptr;
4678 if (browser_plugin_embedder_) {
4679 BrowserPluginGuest* guest = browser_plugin_embedder_->GetFullPageGuest();
4680 if (guest)
4681 guest_web_contents = guest->GetWebContents();
4682 } else if (browser_plugin_guest_) {
4683 guest_web_contents = this;
4684 }
4685
4686 if (guest_web_contents && delegate_->GuestSaveFrame(guest_web_contents))
4687 return;
4688 }
4689
nasko89ad7742015-03-05 22:14:194690 if (!GetLastCommittedURL().is_valid())
[email protected]3c71576ce2013-07-23 02:00:014691 return;
sammc92af61552014-11-19 23:27:404692 if (delegate_ && delegate_->SaveFrame(url, referrer))
4693 return;
4694
nasko89ad7742015-03-05 22:14:194695 // TODO(nasko): This check for main frame is incorrect and should be fixed
brettw760f7442016-05-23 21:19:224696 // by explicitly passing in which frame this method should target. This would
4697 // indicate whether it's the main frame, and also tell us the frame pointer
4698 // to use for routing.
nasko89ad7742015-03-05 22:14:194699 bool is_main_frame = (url == GetLastCommittedURL());
brettw760f7442016-05-23 21:19:224700 RenderFrameHost* frame_host = GetMainFrame();
[email protected]3c71576ce2013-07-23 02:00:014701
avib7348942015-12-25 20:57:104702 int64_t post_id = -1;
[email protected]3c71576ce2013-07-23 02:00:014703 if (is_main_frame) {
Lucas Furukawa Gadani5553a152019-01-08 18:55:574704 NavigationEntry* entry = controller_.GetLastCommittedEntry();
[email protected]3c71576ce2013-07-23 02:00:014705 if (entry)
4706 post_id = entry->GetPostID();
4707 }
Ramin Halavati24e21012017-07-10 12:56:064708 net::NetworkTrafficAnnotationTag traffic_annotation =
4709 net::DefineNetworkTrafficAnnotation("download_web_contents_frame", R"(
4710 semantics {
4711 sender: "Save Page Action"
4712 description:
4713 "Saves the given frame's URL to the local file system."
4714 trigger:
4715 "The user has triggered a save operation on the frame through a "
4716 "context menu or other mechanism."
4717 data: "None."
4718 destination: WEBSITE
4719 }
4720 policy {
Ramin Halavati3b979782017-07-21 11:40:264721 cookies_allowed: YES
Ramin Halavati24e21012017-07-10 12:56:064722 cookies_store: "user"
4723 setting:
4724 "This feature cannot be disabled by settings, but it's is only "
4725 "triggered by user request."
4726 policy_exception_justification: "Not implemented."
4727 })");
Min Qina904f3302018-02-13 23:33:344728 auto params = std::make_unique<download::DownloadUrlParameters>(
brettw760f7442016-05-23 21:19:224729 url, frame_host->GetProcess()->GetID(),
4730 frame_host->GetRenderViewHost()->GetRoutingID(),
Matt Menke0dcaebc32020-03-06 17:00:104731 frame_host->GetRoutingID(), traffic_annotation);
Min Qina904f3302018-02-13 23:33:344732 params->set_referrer(referrer.url);
4733 params->set_referrer_policy(
4734 Referrer::ReferrerPolicyForUrlRequest(referrer.policy));
[email protected]3c71576ce2013-07-23 02:00:014735 params->set_post_id(post_id);
[email protected]3c71576ce2013-07-23 02:00:014736 if (post_id >= 0)
4737 params->set_method("POST");
4738 params->set_prompt(true);
kundaji6c7f9692015-03-09 18:00:374739
4740 if (headers.empty()) {
4741 params->set_prefer_cache(true);
4742 } else {
Min Qina904f3302018-02-13 23:33:344743 for (download::DownloadUrlParameters::RequestHeadersNameValuePair
4744 key_value : ParseDownloadHeaders(headers)) {
Megan Jablonski2f6a4c52017-07-10 23:01:254745 params->add_request_header(key_value.first, key_value.second);
kundaji6c7f9692015-03-09 18:00:374746 }
4747 }
Xing Liu10329bf2018-03-20 19:22:144748 params->set_suggested_name(suggested_filename);
Min Qin0ca8e1ee2018-01-31 00:49:354749 params->set_download_source(download::DownloadSource::WEB_CONTENTS_API);
thestig859c78892017-05-15 21:17:064750 BrowserContext::GetDownloadManager(GetBrowserContext())
Ramin Halavati03efa732017-06-12 09:28:204751 ->DownloadUrl(std::move(params));
[email protected]3c71576ce2013-07-23 02:00:014752}
4753
[email protected]b172aee2012-04-10 17:05:264754void WebContentsImpl::GenerateMHTML(
dewittj6dc5747a2016-05-17 01:48:474755 const MHTMLGenerationParams& params,
Avi Drissman149b7832018-03-23 14:31:494756 base::OnceCallback<void(int64_t)> callback) {
Alexander Timin5fdeff22020-09-08 09:20:374757 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GenerateMHTML");
Angel Alvarez902496682019-08-27 22:58:424758 base::OnceCallback<void(const MHTMLGenerationResult&)> wrapper_callback =
4759 base::BindOnce(
4760 [](base::OnceCallback<void(int64_t)> size_callback,
4761 const MHTMLGenerationResult& result) {
4762 std::move(size_callback).Run(result.file_size);
4763 },
4764 std::move(callback));
4765 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, params,
4766 std::move(wrapper_callback));
4767}
4768
4769void WebContentsImpl::GenerateMHTMLWithResult(
4770 const MHTMLGenerationParams& params,
4771 MHTMLGenerationResult::GenerateMHTMLCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:374772 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GenerateMHTMLWithResult");
Avi Drissman149b7832018-03-23 14:31:494773 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, params,
4774 std::move(callback));
[email protected]aa4f3972012-03-01 18:12:124775}
4776
Tsuyoshi Horob0d8d902020-03-12 00:09:394777void WebContentsImpl::GenerateWebBundle(
4778 const base::FilePath& file_path,
4779 base::OnceCallback<void(uint64_t /* file_size */,
4780 data_decoder::mojom::WebBundlerError)> callback) {
Alexander Timin5fdeff22020-09-08 09:20:374781 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::GenerateWebBundle",
4782 "file_path",
4783 base::trace_event::ValueToString(file_path));
Tsuyoshi Horob0d8d902020-03-12 00:09:394784 SaveAsWebBundleJob::Start(this, file_path, std::move(callback));
4785}
4786
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414787const std::string& WebContentsImpl::GetContentsMimeType() {
Yuzu Saijoc23e9b72020-06-25 07:21:274788 return GetRenderViewHost()->contents_mime_type();
[email protected]0bfbf882011-12-22 18:19:274789}
4790
Leon Hanc819dc62019-01-28 04:30:194791blink::mojom::RendererPreferences* WebContentsImpl::GetMutableRendererPrefs() {
[email protected]0bfbf882011-12-22 18:19:274792 return &renderer_preferences_;
4793}
4794
[email protected]e35ccd52012-05-23 16:22:474795void WebContentsImpl::Close() {
Alexander Timin5fdeff22020-09-08 09:20:374796 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Close");
[email protected]e35ccd52012-05-23 16:22:474797 Close(GetRenderViewHost());
4798}
4799
Ella Ge80a52dce2017-11-15 18:01:524800void WebContentsImpl::DragSourceEndedAt(float client_x,
4801 float client_y,
4802 float screen_x,
4803 float screen_y,
Gyuyoung Kimbad7da7c7d2020-09-25 16:26:594804 blink::DragOperation operation,
Paul Meyer0c58c3712016-11-17 22:59:514805 RenderWidgetHost* source_rwh) {
Alexander Timin5fdeff22020-09-08 09:20:374806 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
4807 "WebContentsImpl::DragSourceEndedAt");
Lei Zhang6410ec1a2019-01-31 21:38:584808 if (browser_plugin_embedder_) {
W. James MacLean9437b5bf2019-12-06 17:33:444809 browser_plugin_embedder_->DragSourceEndedAt(client_x, client_y, screen_x,
4810 screen_y, operation);
Lei Zhang6410ec1a2019-01-31 21:38:584811 }
Paul Meyer0c58c3712016-11-17 22:59:514812 if (source_rwh) {
Ella Ge80a52dce2017-11-15 18:01:524813 source_rwh->DragSourceEndedAt(gfx::PointF(client_x, client_y),
4814 gfx::PointF(screen_x, screen_y), operation);
Paul Meyer0c58c3712016-11-17 22:59:514815 }
[email protected]cf200a562013-05-03 16:24:294816}
4817
jam73f892642016-09-11 06:04:064818void WebContentsImpl::LoadStateChanged(
Charles Harrison911fa062018-03-06 21:01:464819 const std::string& host,
jam73f892642016-09-11 06:04:064820 const net::LoadStateWithParam& load_state,
4821 uint64_t upload_position,
4822 uint64_t upload_size) {
Alexander Timin5fdeff22020-09-08 09:20:374823 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::LoadStateChanged", "host",
4824 host, "load_state", static_cast<int>(load_state.state));
Charles Harrison911fa062018-03-06 21:01:464825 base::string16 host16 = url_formatter::IDNToUnicode(host);
Elly Fong-Jonescad9c3d12018-01-31 17:26:104826 // Drop no-op updates.
4827 if (load_state_.state == load_state.state &&
4828 load_state_.param == load_state.param &&
4829 upload_position_ == upload_position && upload_size_ == upload_size &&
Charles Harrison911fa062018-03-06 21:01:464830 load_state_host_ == host16) {
Elly Fong-Jonescad9c3d12018-01-31 17:26:104831 return;
4832 }
jam73f892642016-09-11 06:04:064833 load_state_ = load_state;
4834 upload_position_ = upload_position;
4835 upload_size_ = upload_size;
Charles Harrison911fa062018-03-06 21:01:464836 load_state_host_ = host16;
jam73f892642016-09-11 06:04:064837 if (load_state_.state == net::LOAD_STATE_READING_RESPONSE)
4838 SetNotWaitingForResponse();
jam73f892642016-09-11 06:04:064839}
4840
Collin Baker989e0882019-11-01 01:27:174841void WebContentsImpl::SetVisibilityAndNotifyObservers(Visibility visibility) {
Alexander Timin5fdeff22020-09-08 09:20:374842 OPTIONAL_TRACE_EVENT1("content",
4843 "WebContentsImpl::SetVisibilityAndNotifyObservers",
4844 "visibility", static_cast<int>(visibility));
Francois Doraye6161152018-03-27 22:05:374845 const Visibility previous_visibility = visibility_;
4846 visibility_ = visibility;
4847
Francois Dorayfe4a1772018-02-17 04:17:094848 // Notify observers if the visibility changed or if WasShown() is being called
4849 // for the first time.
Francois Dorayfe4a1772018-02-17 04:17:094850 if (visibility != previous_visibility ||
4851 (visibility == Visibility::VISIBLE && !did_first_set_visible_)) {
Alexander Timin90c20c32020-08-12 15:28:324852 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4853 observer->OnVisibilityChanged(visibility);
4854 });
Francois Dorayfe4a1772018-02-17 04:17:094855 }
4856}
4857
Michael Thiessen896405db2017-07-20 17:52:324858void WebContentsImpl::NotifyWebContentsFocused(
4859 RenderWidgetHost* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:374860 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::NotifyWebContentsFocused",
4861 "render_widget_host", render_widget_host);
Alexander Timin90c20c32020-08-12 15:28:324862 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4863 observer->OnWebContentsFocused(render_widget_host);
4864 });
calamity7fe55ce2015-04-10 03:59:374865}
4866
Michael Thiessen896405db2017-07-20 17:52:324867void WebContentsImpl::NotifyWebContentsLostFocus(
4868 RenderWidgetHost* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:374869 OPTIONAL_TRACE_EVENT1("content",
4870 "WebContentsImpl::NotifyWebContentsLostFocus",
4871 "render_widget_host", render_widget_host);
Alexander Timin90c20c32020-08-12 15:28:324872 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4873 observer->OnWebContentsLostFocus(render_widget_host);
4874 });
zijiehe3bee08e22017-05-17 04:14:464875}
4876
Paul Meyer0c58c3712016-11-17 22:59:514877void WebContentsImpl::SystemDragEnded(RenderWidgetHost* source_rwh) {
Alexander Timin5fdeff22020-09-08 09:20:374878 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SystemDragEnded",
4879 "render_widget_host", source_rwh);
Paul Meyer0c58c3712016-11-17 22:59:514880 if (source_rwh)
4881 source_rwh->DragSourceSystemDragEnded();
Lei Zhang6410ec1a2019-01-31 21:38:584882 if (browser_plugin_embedder_)
[email protected]cf200a562013-05-03 16:24:294883 browser_plugin_embedder_->SystemDragEnded();
[email protected]7813bd72011-02-05 02:19:344884}
4885
[email protected]b172aee2012-04-10 17:05:264886void WebContentsImpl::SetClosedByUserGesture(bool value) {
Alexander Timin5fdeff22020-09-08 09:20:374887 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetClosedByUserGesture",
4888 "value", value);
[email protected]0bfbf882011-12-22 18:19:274889 closed_by_user_gesture_ = value;
4890}
4891
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414892bool WebContentsImpl::GetClosedByUserGesture() {
[email protected]0bfbf882011-12-22 18:19:274893 return closed_by_user_gesture_;
4894}
4895
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414896int WebContentsImpl::GetMinimumZoomPercent() {
[email protected]0bfbf882011-12-22 18:19:274897 return minimum_zoom_percent_;
4898}
4899
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414900int WebContentsImpl::GetMaximumZoomPercent() {
[email protected]0bfbf882011-12-22 18:19:274901 return maximum_zoom_percent_;
4902}
4903
Dave Tapuska8f7c3872020-02-07 01:16:384904void WebContentsImpl::SetPageScale(float scale_factor) {
Alexander Timin5fdeff22020-09-08 09:20:374905 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetPageScale",
4906 "scale_factor", scale_factor);
Dave Tapuska8f7c3872020-02-07 01:16:384907 GetMainFrame()->GetAssociatedLocalMainFrame()->SetScaleFactor(scale_factor);
ccameronb7c1d6c2015-03-09 17:08:244908}
4909
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414910gfx::Size WebContentsImpl::GetPreferredSize() {
Francois Doray24fc62c2017-12-11 17:27:334911 return IsBeingCaptured() ? preferred_size_for_capture_ : preferred_size_;
[email protected]bcd2815602012-01-14 18:17:234912}
4913
James Hollyerd5c9de462020-03-10 19:02:454914bool WebContentsImpl::GotResponseToLockMouseRequest(
4915 blink::mojom::PointerLockResult result) {
Alexander Timin5fdeff22020-09-08 09:20:374916 OPTIONAL_TRACE_EVENT0("content",
4917 "WebContentsImpl::GotResponseToLockMouseRequest");
lfgf0cd46e2017-01-04 00:05:234918 if (mouse_lock_widget_) {
4919 if (mouse_lock_widget_->delegate()->GetAsWebContents() != this) {
4920 return mouse_lock_widget_->delegate()
4921 ->GetAsWebContents()
James Hollyerd5c9de462020-03-10 19:02:454922 ->GotResponseToLockMouseRequest(result);
lfgf0cd46e2017-01-04 00:05:234923 }
lfgad8244352016-07-13 16:55:514924
James Hollyerd5c9de462020-03-10 19:02:454925 if (mouse_lock_widget_->GotResponseToLockMouseRequest(result))
lfgf0cd46e2017-01-04 00:05:234926 return true;
4927 }
4928
4929 for (WebContentsImpl* current = this; current;
4930 current = current->GetOuterWebContents()) {
4931 current->mouse_lock_widget_ = nullptr;
4932 }
4933
lfgbee1e0a2016-06-08 21:24:214934 return false;
[email protected]0bfbf882011-12-22 18:19:274935}
4936
James Hollyerd5c9de462020-03-10 19:02:454937void WebContentsImpl::GotLockMousePermissionResponse(bool allowed) {
4938 GotResponseToLockMouseRequest(
4939 allowed ? blink::mojom::PointerLockResult::kSuccess
4940 : blink::mojom::PointerLockResult::kPermissionDenied);
4941}
4942
Joe Downing13dd76b2018-04-09 18:32:154943bool WebContentsImpl::GotResponseToKeyboardLockRequest(bool allowed) {
Alexander Timin5fdeff22020-09-08 09:20:374944 OPTIONAL_TRACE_EVENT1("content",
4945 "WebContentsImpl::GotResponseToKeyboardLockRequest",
4946 "allowed", allowed);
4947
Joe Downing13dd76b2018-04-09 18:32:154948 if (!keyboard_lock_widget_)
4949 return false;
4950
4951 if (keyboard_lock_widget_->delegate()->GetAsWebContents() != this) {
4952 NOTREACHED();
4953 return false;
4954 }
4955
4956 // KeyboardLock is only supported when called by the top-level browsing
4957 // context and is not supported in embedded content scenarios.
4958 if (GetOuterWebContents())
4959 return false;
4960
4961 keyboard_lock_widget_->GotResponseToKeyboardLockRequest(allowed);
4962 return true;
4963}
4964
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414965bool WebContentsImpl::HasOpener() {
Ivan Kotenkov2c0d2bb32017-11-01 15:41:284966 return GetOpener() != nullptr;
[email protected]a0358d72012-03-09 14:06:504967}
4968
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414969RenderFrameHostImpl* WebContentsImpl::GetOpener() {
alexmose201c7cd2015-06-10 17:14:214970 FrameTreeNode* opener_ftn = frame_tree_.root()->opener();
lukasza6f8ac622017-06-06 03:10:204971 return opener_ftn ? opener_ftn->current_frame_host() : nullptr;
jochen55ff3502014-12-18 20:52:574972}
4973
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414974bool WebContentsImpl::HasOriginalOpener() {
Ivan Kotenkov2c0d2bb32017-11-01 15:41:284975 return GetOriginalOpener() != nullptr;
jochen6004a362017-02-04 00:11:404976}
4977
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414978RenderFrameHostImpl* WebContentsImpl::GetOriginalOpener() {
jochen6004a362017-02-04 00:11:404979 FrameTreeNode* opener_ftn = frame_tree_.root()->original_opener();
lukasza6f8ac622017-06-06 03:10:204980 return opener_ftn ? opener_ftn->current_frame_host() : nullptr;
jochen6004a362017-02-04 00:11:404981}
4982
[email protected]cb805452013-05-22 15:16:214983void WebContentsImpl::DidChooseColorInColorChooser(SkColor color) {
Alexander Timin5fdeff22020-09-08 09:20:374984 OPTIONAL_TRACE_EVENT1("content",
4985 "WebContentsImpl::DidChooseColorInColorChooser",
4986 "color", color);
Joel Hockey85b379d2017-12-11 10:42:134987 color_chooser_->DidChooseColorInColorChooser(color);
[email protected]da8543762012-03-20 08:52:204988}
4989
[email protected]cb805452013-05-22 15:16:214990void WebContentsImpl::DidEndColorChooser() {
Alexander Timin5fdeff22020-09-08 09:20:374991 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidEndColorChooser");
Joel Hockey85b379d2017-12-11 10:42:134992 color_chooser_.reset();
[email protected]da8543762012-03-20 08:52:204993}
4994
halton.huoca2eabd2015-07-06 08:17:404995int WebContentsImpl::DownloadImage(
4996 const GURL& url,
4997 bool is_favicon,
Fredrik Söderquistb2b39eb92019-11-18 16:16:504998 uint32_t preferred_size,
halton.huoca2eabd2015-07-06 08:17:404999 uint32_t max_bitmap_size,
5000 bool bypass_cache,
Avi Drissmana5a52dd2018-03-27 03:39:025001 WebContents::ImageDownloadCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:375002 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DownloadImage", "url",
5003 base::trace_event::ValueToString(url));
Danyao Wanga78f3dd22020-03-05 05:31:275004 return DownloadImageInFrame(GlobalFrameRoutingId(), url, is_favicon,
5005 preferred_size, max_bitmap_size, bypass_cache,
5006 std::move(callback));
5007}
5008
5009int WebContentsImpl::DownloadImageInFrame(
5010 const GlobalFrameRoutingId& initiator_frame_routing_id,
5011 const GURL& url,
5012 bool is_favicon,
5013 uint32_t preferred_size,
5014 uint32_t max_bitmap_size,
5015 bool bypass_cache,
5016 WebContents::ImageDownloadCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:375017 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DownloadImageInFrame");
amistry9f01b772015-07-29 01:54:555018 DCHECK_CURRENTLY_ON(BrowserThread::UI);
halton.huoca2eabd2015-07-06 08:17:405019 static int next_image_download_id = 0;
Danyao Wanga78f3dd22020-03-05 05:31:275020
5021 RenderFrameHostImpl* initiator_frame =
5022 initiator_frame_routing_id.child_id
5023 ? RenderFrameHostImpl::FromID(initiator_frame_routing_id)
5024 : GetMainFrame();
Julie Jeongeun Kimb1473572019-08-15 05:59:135025 const mojo::Remote<blink::mojom::ImageDownloader>& mojo_image_downloader =
Danyao Wanga78f3dd22020-03-05 05:31:275026 initiator_frame->GetMojoImageDownloader();
amistry9f01b772015-07-29 01:54:555027 const int download_id = ++next_image_download_id;
5028 if (!mojo_image_downloader) {
5029 // If the renderer process is dead (i.e. crash, or memory pressure on
5030 // Android), the downloader service will be invalid. Pre-Mojo, this would
Avi Drissmana5a52dd2018-03-27 03:39:025031 // hang the callback indefinitely since the IPC would be dropped. Now,
amistry9f01b772015-07-29 01:54:555032 // respond with a 400 HTTP error code to indicate that something went wrong.
Gabriel Charettee7cdc5cd2020-05-27 23:35:055033 GetUIThreadTaskRunner({})->PostTask(
5034 FROM_HERE,
tzike2aca992017-09-05 08:50:545035 base::BindOnce(&WebContentsImpl::OnDidDownloadImage,
Avi Drissmana5a52dd2018-03-27 03:39:025036 weak_factory_.GetWeakPtr(), std::move(callback),
5037 download_id, url, 400, std::vector<SkBitmap>(),
5038 std::vector<gfx::Size>()));
amistry9f01b772015-07-29 01:54:555039 return download_id;
5040 }
5041
halton.huoca2eabd2015-07-06 08:17:405042 mojo_image_downloader->DownloadImage(
Fredrik Söderquistb2b39eb92019-11-18 16:16:505043 url, is_favicon, preferred_size, max_bitmap_size, bypass_cache,
tzike2aca992017-09-05 08:50:545044 base::BindOnce(&WebContentsImpl::OnDidDownloadImage,
Avi Drissmana5a52dd2018-03-27 03:39:025045 weak_factory_.GetWeakPtr(), std::move(callback),
5046 download_id, url));
amistry9f01b772015-07-29 01:54:555047 return download_id;
[email protected]795c28972012-12-06 06:13:395048}
5049
[email protected]36ec24f2014-01-09 00:32:085050void WebContentsImpl::Find(int request_id,
5051 const base::string16& search_text,
Rakina Zata Amni3f77dff2018-09-08 16:19:435052 blink::mojom::FindOptionsPtr options) {
Alexander Timin5fdeff22020-09-08 09:20:375053 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Find");
thestig6057a6b22015-11-12 23:01:335054 // Cowardly refuse to search for no text.
5055 if (search_text.empty()) {
5056 NOTREACHED();
5057 return;
5058 }
5059
Rakina Zata Amni3f77dff2018-09-08 16:19:435060 GetOrCreateFindRequestManager()->Find(request_id, search_text,
5061 std::move(options));
[email protected]36ec24f2014-01-09 00:32:085062}
5063
5064void WebContentsImpl::StopFinding(StopFindAction action) {
Alexander Timin5fdeff22020-09-08 09:20:375065 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::StopFinding");
paulmeyerfeafc2d2017-04-25 21:46:405066 if (FindRequestManager* manager = GetFindRequestManager())
5067 manager->StopFinding(action);
[email protected]36ec24f2014-01-09 00:32:085068}
5069
Tommy Steimel18360512017-11-01 00:38:195070bool WebContentsImpl::WasEverAudible() {
5071 return was_ever_audible_;
5072}
5073
Avi Drissmana5a52dd2018-03-27 03:39:025074void WebContentsImpl::GetManifest(GetManifestCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:375075 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GetManifest");
Yuzu Saijofce18322020-05-14 05:02:095076 // TODO(yuzus, 1061899): Move this function to RenderFrameHostImpl.
5077 ManifestManagerHost* manifest_manager_host =
5078 ManifestManagerHost::GetOrCreateForCurrentDocument(GetMainFrame());
5079 manifest_manager_host->GetManifest(std::move(callback));
mlamouriefdca9d2014-09-16 16:55:405080}
5081
bokanece34a82016-01-28 19:49:465082void WebContentsImpl::ExitFullscreen(bool will_cause_resize) {
Alexander Timin5fdeff22020-09-08 09:20:375083 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ExitFullscreen");
mlamouri7a78d6fd2015-01-17 13:23:535084 // Clean up related state and initiate the fullscreen exit.
James Hollyerd5c9de462020-03-10 19:02:455085 GetRenderViewHost()->GetWidget()->RejectMouseLockOrUnlockIfNecessary(
5086 blink::mojom::PointerLockResult::kUserRejected);
bokanece34a82016-01-28 19:49:465087 ExitFullscreenMode(will_cause_resize);
mlamouri7a78d6fd2015-01-17 13:23:535088}
5089
Mike Wassermanb6bc0152020-08-25 22:46:205090base::ScopedClosureRunner WebContentsImpl::ForSecurityDropFullscreen(
5091 int64_t display_id) {
Alexander Timin5fdeff22020-09-08 09:20:375092 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ForSecurityDropFullscreen",
5093 "display_id", display_id);
Avi Drissman33972942020-06-19 14:16:015094 // Kick WebContentses that are "related" to this WebContents out of
5095 // fullscreen. This needs to be done with two passes, because it is simple to
5096 // walk _up_ the chain of openers and outer contents, but it not simple to
5097 // walk _down_ the chain.
5098
5099 // First, determine if any WebContents that is in fullscreen has this
5100 // WebContents as an upstream contents. Drop that WebContents out of
5101 // fullscreen if it does. This is theoretically quadratic-ish (fullscreen
5102 // contentses x each one's opener length) but neither of those is expected to
5103 // ever be a large number.
5104
Mike Wassermanb6bc0152020-08-25 22:46:205105 auto* screen = display::Screen::GetScreen();
5106
Avi Drissman33972942020-06-19 14:16:015107 auto fullscreen_set_copy = *FullscreenContentsSet(GetBrowserContext());
5108 for (auto* fullscreen_contents : fullscreen_set_copy) {
Avi Drissman97aef042020-06-30 21:04:485109 // Checking IsFullscreen() for tabs in the fullscreen set may seem
5110 // redundant, but teeeeechnically fullscreen is run by the delegate, and
5111 // it's possible that the delegate's notion of fullscreen may have changed
5112 // outside of WebContents's notice.
Mike Wassermanb6bc0152020-08-25 22:46:205113 if (fullscreen_contents->IsFullscreen() &&
5114 (display_id == display::kInvalidDisplayId || !screen ||
5115 display_id ==
5116 screen->GetDisplayNearestView(fullscreen_contents->GetNativeView())
5117 .id())) {
Avi Drissman33972942020-06-19 14:16:015118 auto opener_contentses = GetAllOpeningWebContents(fullscreen_contents);
5119 if (opener_contentses.count(this))
5120 fullscreen_contents->ExitFullscreen(true);
5121 }
5122 }
5123
5124 // Second, walk upstream from this WebContents, and drop the fullscreen of
5125 // all WebContentses that are in fullscreen. Block all the WebContentses in
5126 // the chain from entering fullscreen while the returned closure runner is
5127 // alive. It's OK that this set doesn't contain downstream WebContentses, as
5128 // any request to enter fullscreen will have the upstream of the WebContents
5129 // checked. (See CanEnterFullscreenMode().)
Avi Drissmanced52b62019-08-14 21:25:465130
Avi Drissman1a55a9d62020-03-10 18:56:455131 std::vector<base::WeakPtr<WebContentsImpl>> blocked_contentses;
5132
Avi Drissman33972942020-06-19 14:16:015133 for (auto* opener : GetAllOpeningWebContents(this)) {
Avi Drissman1a55a9d62020-03-10 18:56:455134 // Drop fullscreen if the WebContents is in it, and...
Mike Wassermanb6bc0152020-08-25 22:46:205135 if (opener->IsFullscreen() &&
5136 (display_id == display::kInvalidDisplayId || !screen ||
5137 display_id ==
5138 screen->GetDisplayNearestView(opener->GetNativeView()).id()))
Avi Drissman33972942020-06-19 14:16:015139 opener->ExitFullscreen(true);
Avi Drissmanced52b62019-08-14 21:25:465140
Avi Drissman1a55a9d62020-03-10 18:56:455141 // ...block the WebContents from entering fullscreen until further notice.
Avi Drissman33972942020-06-19 14:16:015142 ++opener->fullscreen_blocker_count_;
5143 blocked_contentses.push_back(opener->weak_factory_.GetWeakPtr());
Avi Drissmanced52b62019-08-14 21:25:465144 }
Avi Drissman1a55a9d62020-03-10 18:56:455145
5146 return base::ScopedClosureRunner(base::BindOnce(
5147 [](std::vector<base::WeakPtr<WebContentsImpl>> blocked_contentses) {
5148 for (base::WeakPtr<WebContentsImpl>& web_contents :
5149 blocked_contentses) {
5150 if (web_contents) {
5151 DCHECK_GT(web_contents->fullscreen_blocker_count_, 0);
5152 --web_contents->fullscreen_blocker_count_;
5153 }
5154 }
5155 },
5156 std::move(blocked_contentses)));
Avi Drissmanced52b62019-08-14 21:25:465157}
5158
mariakhomenko44bdc4732015-04-29 01:55:385159void WebContentsImpl::ResumeLoadingCreatedWebContents() {
Alexander Timin5fdeff22020-09-08 09:20:375160 OPTIONAL_TRACE_EVENT0("content",
5161 "WebContentsImpl::ResumeLoadingCreatedWebContents");
Nasko Oskov83a8cf92018-10-19 14:58:565162 if (delayed_load_url_params_.get()) {
5163 DCHECK(!delayed_open_url_params_);
5164 controller_.LoadURLWithParams(*delayed_load_url_params_.get());
5165 delayed_load_url_params_.reset(nullptr);
5166 return;
5167 }
5168
mariakhomenkoa4971c12015-07-21 19:04:375169 if (delayed_open_url_params_.get()) {
5170 OpenURL(*delayed_open_url_params_.get());
5171 delayed_open_url_params_.reset(nullptr);
5172 return;
5173 }
5174
mariakhomenko44bdc4732015-04-29 01:55:385175 // Resume blocked requests for both the RenderViewHost and RenderFrameHost.
5176 // TODO(brettw): It seems bogus to reach into here and initialize the host.
dfalcantarae6b7b46752015-07-10 18:14:165177 if (is_resume_pending_) {
5178 is_resume_pending_ = false;
avi0f1bbc9712015-11-17 02:58:135179 GetRenderViewHost()->GetWidget()->Init();
dfalcantarae6b7b46752015-07-10 18:14:165180 GetMainFrame()->Init();
5181 }
mariakhomenko44bdc4732015-04-29 01:55:385182}
5183
[email protected]b172aee2012-04-10 17:05:265184bool WebContentsImpl::FocusLocationBarByDefault() {
Alexander Timin5fdeff22020-09-08 09:20:375185 OPTIONAL_TRACE_EVENT0("content",
5186 "WebContentsImpl::FocusLocationBarByDefault");
Xiyuan Xia2a66b112018-12-06 15:52:165187 if (should_focus_location_bar_by_default_)
[email protected]0c9406632013-02-08 01:13:335188 return true;
Xiyuan Xia2a66b112018-12-06 15:52:165189
[email protected]0c9406632013-02-08 01:13:335190 return delegate_ && delegate_->ShouldFocusLocationBarByDefault(this);
[email protected]0bfbf882011-12-22 18:19:275191}
5192
Johann Koenig480ee7a2020-09-28 08:02:185193void WebContentsImpl::SetFocusToLocationBar() {
5194 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetFocusToLocationBar");
5195 if (delegate_)
5196 delegate_->SetFocusToLocationBar();
5197}
5198
clamy0e119882015-07-31 16:12:335199void WebContentsImpl::DidStartNavigation(NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:485200 TRACE_EVENT1("navigation", "WebContentsImpl::DidStartNavigation",
5201 "navigation_handle", navigation_handle);
Alan Cutterab48fc02020-02-24 12:26:425202 if (navigation_handle->IsInMainFrame())
5203 favicon_urls_.clear();
Mounir Lamouri7b4a1f232019-12-23 16:32:105204
Alexander Timin90c20c32020-08-12 15:28:325205 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5206 observer->DidStartNavigation(navigation_handle);
5207 });
Xiyuan Xia2a66b112018-12-06 15:52:165208 if (navigation_handle->IsInMainFrame()) {
5209 // When the browser is started with about:blank as the startup URL, focus
5210 // the location bar (which will also select its contents) so people can
5211 // simply begin typing to navigate elsewhere.
5212 //
5213 // We need to be careful not to trigger this for anything other than the
5214 // startup navigation. In particular, if we allow an attacker to open a
5215 // popup to about:blank, then navigate, focusing the Omnibox will cause the
5216 // end of the new URL to be scrolled into view instead of the start,
5217 // allowing the attacker to spoof other URLs. The conditions checked here
5218 // are all aimed at ensuring no such attacker-controlled navigation can
5219 // trigger this.
5220 should_focus_location_bar_by_default_ =
5221 controller_.IsInitialNavigation() &&
5222 !navigation_handle->IsRendererInitiated() &&
5223 navigation_handle->GetURL() == url::kAboutBlankURL;
5224 }
clamy0e119882015-07-31 16:12:335225}
5226
5227void WebContentsImpl::DidRedirectNavigation(
5228 NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:485229 TRACE_EVENT1("navigation", "WebContentsImpl::DidRedirectNavigation",
5230 "navigation_handle", navigation_handle);
Alexander Timin90c20c32020-08-12 15:28:325231 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5232 observer->DidRedirectNavigation(navigation_handle);
5233 });
jam5f358e52017-02-13 16:37:035234 // Notify accessibility if this is a reload. This has to called on the
5235 // BrowserAccessibilityManager associated with the old RFHI.
5236 if (navigation_handle->GetReloadType() != ReloadType::NONE) {
Mohamed Abdelhalim95794962019-09-20 11:16:495237 NavigationRequest* request = NavigationRequest::From(navigation_handle);
jam5f358e52017-02-13 16:37:035238 BrowserAccessibilityManager* manager =
Mohamed Abdelhalim95794962019-09-20 11:16:495239 request->frame_tree_node()
jam5f358e52017-02-13 16:37:035240 ->current_frame_host()
5241 ->browser_accessibility_manager();
5242 if (manager)
5243 manager->UserIsReloading();
5244 }
clamy0e119882015-07-31 16:12:335245}
5246
clamyefca29e2015-09-17 00:22:115247void WebContentsImpl::ReadyToCommitNavigation(
5248 NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:485249 TRACE_EVENT1("navigation", "WebContentsImpl::ReadyToCommitNavigation",
5250 "navigation_handle", navigation_handle);
Alexander Timin90c20c32020-08-12 15:28:325251 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5252 observer->ReadyToCommitNavigation(navigation_handle);
5253 });
Kenneth Russell954ed9ce2018-04-12 23:07:015254 // If any domains are blocked from accessing 3D APIs because they may
5255 // have caused the GPU to reset recently, unblock them here if the user
5256 // initiated this navigation. This implies that the user was involved in
5257 // the decision to navigate, so there's no concern about
5258 // denial-of-service issues. Want to do this as early as
5259 // possible to avoid race conditions with pages attempting to access
5260 // WebGL early on.
5261 //
5262 // TODO(crbug.com/617904): currently navigations initiated by the browser
5263 // (reload button, reload menu option, pressing return in the Omnibox)
5264 // return false from HasUserGesture(). If or when that is addressed,
5265 // remove the check for IsRendererInitiated() below.
5266 //
5267 // TODO(crbug.com/832180): HasUserGesture comes from the renderer
5268 // process and isn't validated. Until it is, don't trust it.
5269 if (!navigation_handle->IsRendererInitiated()) {
5270 GpuDataManagerImpl::GetInstance()->UnblockDomainFrom3DAPIs(
5271 navigation_handle->GetURL());
5272 }
5273
John Abd-El-Malekfde08e6da2017-12-05 04:06:245274 if (navigation_handle->IsSameDocument())
5275 return;
5276
Livvie Lin139bf442018-08-10 00:18:545277 // SSLInfo is not needed on subframe navigations since the main-frame
5278 // certificate is the only one that can be inspected (using the info
5279 // bubble) without refreshing the page with DevTools open.
Carlos ILaed1e7b2019-03-12 19:27:215280 // We don't call DidStartResourceResponse on net errors, since that results on
5281 // existing cert exceptions being revoked, which leads to weird behavior with
5282 // committed interstitials or while offline. We only need the error check for
5283 // the main frame case because unlike this method, SubresourceResponseStarted
5284 // does not get called on network errors.
5285 if (navigation_handle->IsInMainFrame() &&
5286 navigation_handle->GetNetErrorCode() == net::OK) {
Livvie Lin139bf442018-08-10 00:18:545287 controller_.ssl_manager()->DidStartResourceResponse(
Lukasz Anforowiczd334bba2020-02-10 23:32:555288 navigation_handle->GetURL(),
Camille Lamy62b826012019-02-26 09:15:475289 navigation_handle->GetSSLInfo().has_value()
5290 ? net::IsCertStatusError(
5291 navigation_handle->GetSSLInfo()->cert_status)
5292 : false);
5293 }
John Abd-El-Malekfde08e6da2017-12-05 04:06:245294
Bruce Dawsone1c5c842020-09-15 02:09:145295 // LoadingStateChanged must be called last in case it triggers deletion of
5296 // |this| due to recursive message pumps.
John Abd-El-Malekfde08e6da2017-12-05 04:06:245297 SetNotWaitingForResponse();
clamyefca29e2015-09-17 00:22:115298}
5299
clamy0e119882015-07-31 16:12:335300void WebContentsImpl::DidFinishNavigation(NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:485301 TRACE_EVENT1("navigation", "WebContentsImpl::DidFinishNavigation",
5302 "navigation_handle", navigation_handle);
Steven Holte38041342018-06-22 22:00:575303
Alexander Timin90c20c32020-08-12 15:28:325304 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5305 observer->DidFinishNavigation(navigation_handle);
5306 });
Becca Hughesd11d6502018-07-31 17:01:285307 if (display_cutout_host_impl_)
5308 display_cutout_host_impl_->DidFinishNavigation(navigation_handle);
5309
jam5f358e52017-02-13 16:37:035310 if (navigation_handle->HasCommitted()) {
Ian Prestcdd843d2020-01-28 18:59:585311 // TODO(domfarolino, dmazzoni): Do this using WebContentsObserver. See
5312 // https://crbug.com/981271.
5313 BrowserAccessibilityManager* manager =
5314 static_cast<RenderFrameHostImpl*>(
5315 navigation_handle->GetRenderFrameHost())
5316 ->browser_accessibility_manager();
5317 if (manager) {
5318 if (navigation_handle->IsErrorPage()) {
5319 manager->NavigationFailed();
5320 } else {
5321 manager->NavigationSucceeded();
5322 }
5323 }
5324
Yue Ru Sun979c4b162019-11-06 16:11:045325 if (navigation_handle->IsInMainFrame()) {
5326 last_committed_source_id_including_same_document_ =
Steven Holte38041342018-06-22 22:00:575327 ukm::ConvertToSourceId(navigation_handle->GetNavigationId(),
5328 ukm::SourceIdType::NAVIGATION_ID);
Yue Ru Sun979c4b162019-11-06 16:11:045329
5330 if (!navigation_handle->IsSameDocument()) {
5331 was_ever_audible_ = false;
Yue Ru Sun979c4b162019-11-06 16:11:045332 }
Tommy Steimel18360512017-11-01 00:38:195333 }
Lan Weif81c6e7c2020-02-12 16:46:095334
5335 if (!navigation_handle->IsSameDocument())
5336 last_screen_orientation_change_time_ = base::TimeTicks();
dmazzonibf8cec42015-02-08 08:28:085337 }
Xiyuan Xia2a66b112018-12-06 15:52:165338
5339 // If we didn't end up on about:blank after setting this in DidStartNavigation
5340 // then don't focus the location bar.
5341 if (should_focus_location_bar_by_default_ &&
5342 navigation_handle->GetURL() != url::kAboutBlankURL) {
5343 should_focus_location_bar_by_default_ = false;
5344 }
yilkal796e89e2019-10-02 23:58:285345
yilkal172da772019-11-06 22:49:075346 if (navigation_handle->IsInMainFrame() && first_navigation_completed_)
5347 RecordMaxFrameCountUMA(max_loaded_frame_count_);
yilkal796e89e2019-10-02 23:58:285348
yilkal172da772019-11-06 22:49:075349 // If navigation has successfully finished in the main frame, set
5350 // |first_navigation_completed_| to true so that we will record
5351 // |max_loaded_frame_count_| above when future main frame navigations finish.
5352 if (navigation_handle->IsInMainFrame() && !navigation_handle->IsErrorPage()) {
5353 first_navigation_completed_ = true;
5354
5355 // Navigation has completed in main frame. Reset |max_loaded_frame_count_|.
5356 // |max_loaded_frame_count_| is not necessarily 1 if the navigation was
5357 // served from BackForwardCache.
5358 max_loaded_frame_count_ =
5359 GetMainFrame()->frame_tree_node()->GetFrameTreeSize();
yilkal796e89e2019-10-02 23:58:285360 }
Rakina Zata Amni347b70902020-07-22 10:49:045361
5362 if (web_preferences_) {
5363 // Update the WebPreferences for this WebContents that depends on changes
5364 // that might occur during navigation. This will only update the preferences
5365 // that needs to be updated (and won't cause an update/overwrite preferences
5366 // that needs to stay the same after navigations).
5367 bool value_changed_due_to_override =
5368 GetContentClient()->browser()->OverrideWebPreferencesAfterNavigation(
5369 this, web_preferences_.get());
5370 // We need to update the WebPreferences value on the renderer if the value
5371 // is changed due to the override above, or if the navigation is served from
5372 // the back-forward cache, because the WebPreferences value stored in the
5373 // renderer might be stale (because we don't send WebPreferences updates to
5374 // bfcached renderers).
5375 // TODO(rakina): Maybe handle the back-forward cache case in
5376 // ReadyToCommitNavigation instead?
5377 if (value_changed_due_to_override ||
5378 NavigationRequest::From(navigation_handle)
5379 ->IsServedFromBackForwardCache()) {
5380 SetWebPreferences(*web_preferences_.get());
5381 }
5382 }
[email protected]400992b2012-06-14 00:03:545383}
5384
[email protected]b80624c2014-02-09 02:46:555385void WebContentsImpl::DidFailLoadWithError(
5386 RenderFrameHostImpl* render_frame_host,
[email protected]b80624c2014-02-09 02:46:555387 const GURL& url,
Dave Tapuska924ef3c2020-01-22 18:20:595388 int error_code) {
Alexander Timin5fdeff22020-09-08 09:20:375389 TRACE_EVENT2("content,navigation", "WebContentsImpl::DidFailLoadWithError",
5390 "render_frame_host",
5391 base::trace_event::ToTracedValue(render_frame_host), "url",
5392 base::trace_event::ValueToString(url));
Alexander Timin90c20c32020-08-12 15:28:325393 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5394 observer->DidFailLoad(render_frame_host, url, error_code);
5395 });
[email protected]b80624c2014-02-09 02:46:555396}
5397
[email protected]52913802013-12-10 05:52:185398void WebContentsImpl::NotifyChangedNavigationState(
5399 InvalidateTypes changed_flags) {
5400 NotifyNavigationStateChanged(changed_flags);
5401}
5402
lukasza1d025732016-09-28 21:36:085403bool WebContentsImpl::ShouldTransferNavigation(bool is_main_frame_navigation) {
Alexander Timin5fdeff22020-09-08 09:20:375404 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ShouldTransferNavigation",
5405 "is_main_frame_navigation", is_main_frame_navigation);
creis29460272015-12-16 04:38:225406 if (!delegate_)
5407 return true;
lukasza1d025732016-09-28 21:36:085408 return delegate_->ShouldTransferNavigation(is_main_frame_navigation);
creis29460272015-12-16 04:38:225409}
5410
[email protected]aa62afd2014-04-22 19:22:465411bool WebContentsImpl::ShouldPreserveAbortedURLs() {
Alexander Timin5fdeff22020-09-08 09:20:375412 OPTIONAL_TRACE_EVENT0("content",
5413 "WebContentsImpl::ShouldPreserveAbortedURLs");
[email protected]aa62afd2014-04-22 19:22:465414 if (!delegate_)
5415 return false;
5416 return delegate_->ShouldPreserveAbortedURLs(this);
5417}
5418
[email protected]0d0f4c492014-04-02 06:42:575419void WebContentsImpl::DidNavigateMainFramePreCommit(
[email protected]5cfbddc2014-06-23 23:52:235420 bool navigation_is_within_page) {
Alexander Timin5fdeff22020-09-08 09:20:375421 TRACE_EVENT1("content,navigation",
5422 "WebContentsImpl::DidNavigateMainFramePreCommit",
5423 "navigation_is_within_page", navigation_is_within_page);
[email protected]0d0f4c492014-04-02 06:42:575424 // Ensure fullscreen mode is exited before committing the navigation to a
5425 // different page. The next page will not start out assuming it is in
5426 // fullscreen mode.
[email protected]5cfbddc2014-06-23 23:52:235427 if (navigation_is_within_page) {
[email protected]dfc39cb2014-04-09 22:58:195428 // No page change? Then, the renderer and browser can remain in fullscreen.
[email protected]0d0f4c492014-04-02 06:42:575429 return;
5430 }
Avi Drissman97aef042020-06-30 21:04:485431 if (IsFullscreen())
bokanece34a82016-01-28 19:49:465432 ExitFullscreen(false);
Avi Drissman97aef042020-06-30 21:04:485433 DCHECK(!IsFullscreen());
Joe Downingc1a57efe2018-05-09 18:23:545434
5435 // Clean up keyboard lock state when navigating.
5436 CancelKeyboardLock(keyboard_lock_widget_);
[email protected]0d0f4c492014-04-02 06:42:575437}
5438
[email protected]37567b432014-02-12 01:12:225439void WebContentsImpl::DidNavigateMainFramePostCommit(
sky8b00392d2015-01-10 00:30:285440 RenderFrameHostImpl* render_frame_host,
[email protected]37567b432014-02-12 01:12:225441 const LoadCommittedDetails& details,
5442 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
Alexander Timin5fdeff22020-09-08 09:20:375443 OPTIONAL_TRACE_EVENT1(
5444 "content,navigation", "WebContentsImpl::DidNavigateMainFramePostCommit",
5445 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host));
[email protected]37567b432014-02-12 01:12:225446 if (details.is_navigation_to_different_page()) {
5447 // Clear the status bubble. This is a workaround for a bug where WebKit
5448 // doesn't let us know that the cursor left an element during a
5449 // transition (this is also why the mouse cursor remains as a hand after
5450 // clicking on a link); see bugs 1184641 and 980803. We don't want to
5451 // clear the bubble when a user navigates to a named anchor in the same
5452 // page.
Lukasz Anforowiczfd707142018-02-07 19:46:135453 ClearTargetURL();
lanwei9d343ad22015-02-11 01:46:005454
5455 RenderWidgetHostViewBase* rwhvb =
5456 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
5457 if (rwhvb)
5458 rwhvb->OnDidNavigateMainFrameToNewPage();
[email protected]37567b432014-02-12 01:12:225459 }
5460
[email protected]e85165c642014-06-10 14:34:315461 if (delegate_)
[email protected]37567b432014-02-12 01:12:225462 delegate_->DidNavigateMainFramePostCommit(this);
[email protected]e85165c642014-06-10 14:34:315463 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
Shivani Sharma985474f2019-05-23 21:36:475464
Alan Cutterd73a15d92020-08-21 07:12:455465 // The following events will not fire again if the page is restored from the
5466 // BackForwardCache. So fire them ourselves if needed.
Carlos Caballero91fffb22019-10-29 15:24:305467 if (details.is_navigation_to_different_page() &&
5468 GetRenderViewHost()->did_first_visually_non_empty_paint()) {
Carlos Caballero91fffb22019-10-29 15:24:305469 DidFirstVisuallyNonEmptyPaint(GetRenderViewHost());
5470 }
Alan Cutterd73a15d92020-08-21 07:12:455471 if (GetRenderViewHost()->theme_color() != last_sent_theme_color_)
Carlos Caballero1215f882019-10-29 15:58:435472 OnThemeColorChanged(GetRenderViewHost());
Alan Cutterd73a15d92020-08-21 07:12:455473 if (GetRenderViewHost()->background_color() != last_sent_background_color_)
5474 OnBackgroundColorChanged(GetRenderViewHost());
[email protected]37567b432014-02-12 01:12:225475}
5476
5477void WebContentsImpl::DidNavigateAnyFramePostCommit(
5478 RenderFrameHostImpl* render_frame_host,
5479 const LoadCommittedDetails& details,
5480 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
Alexander Timin5fdeff22020-09-08 09:20:375481 OPTIONAL_TRACE_EVENT1(
5482 "content,navigation", "WebContentsImpl::DidNavigateAnyFramePostCommit",
5483 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host));
[email protected]b4c84012014-04-28 19:51:105484 // Now that something has committed, we don't need to track whether the
5485 // initial page has been accessed.
5486 has_accessed_initial_document_ = false;
5487
[email protected]37567b432014-02-12 01:12:225488 // If we navigate off the page, close all JavaScript dialogs.
eugenebutee08663a2017-04-27 17:43:125489 if (!details.is_same_document)
creis89a0f782015-05-27 16:13:175490 CancelActiveAndPendingDialogs();
[email protected]37567b432014-02-12 01:12:225491
avid53461d2016-02-25 17:15:045492 // If this is a user-initiated navigation, start allowing JavaScript dialogs
5493 // again.
avi5d3b8692016-10-12 22:00:465494 if (params.gesture == NavigationGestureUser && dialog_manager_) {
avi6879fcf2017-01-21 05:27:535495 dialog_manager_->CancelDialogs(this, /*reset_state=*/true);
avi5d3b8692016-10-12 22:00:465496 }
[email protected]37567b432014-02-12 01:12:225497}
5498
[email protected]277857a2014-06-03 10:38:015499bool WebContentsImpl::CanOverscrollContent() const {
Alexander Timin5fdeff22020-09-08 09:20:375500 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::CanOverscrollContent");
[email protected]e85165c642014-06-10 14:34:315501 // Disable overscroll when touch emulation is on. See crbug.com/369938.
[email protected]34ff1cfc2014-08-20 06:16:055502 if (force_disable_overscroll_content_)
[email protected]e85165c642014-06-10 14:34:315503 return false;
5504
[email protected]37567b432014-02-12 01:12:225505 if (delegate_)
5506 return delegate_->CanOverscrollContent();
5507
5508 return false;
5509}
5510
Carlos Caballero1215f882019-10-29 15:58:435511void WebContentsImpl::OnThemeColorChanged(RenderViewHostImpl* source) {
Alexander Timin5fdeff22020-09-08 09:20:375512 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnThemeColorChanged",
5513 "render_view_host", source);
Carlos Caballero1215f882019-10-29 15:58:435514 if (source->did_first_visually_non_empty_paint() &&
5515 last_sent_theme_color_ != source->theme_color()) {
Alexander Timin90c20c32020-08-12 15:28:325516 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5517 observer->DidChangeThemeColor();
5518 });
Matt Jones36fc2882020-08-25 14:25:125519 last_sent_theme_color_ = source->theme_color();
peter90afaba2015-06-01 12:05:295520 }
[email protected]e7104762014-06-20 19:17:255521}
5522
Alan Cutterd73a15d92020-08-21 07:12:455523void WebContentsImpl::OnBackgroundColorChanged(RenderViewHostImpl* source) {
5524 if (source->did_first_visually_non_empty_paint() &&
5525 last_sent_background_color_ != source->background_color()) {
5526 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5527 observer->OnBackgroundColorChanged();
5528 });
5529 last_sent_background_color_ = source->background_color();
5530 }
5531}
5532
Gyuyoung Kim1905f7c2020-05-02 00:00:245533void WebContentsImpl::DidLoadResourceFromMemoryCache(
nicka0ac8382016-12-15 23:59:235534 RenderFrameHostImpl* source,
[email protected]724159a2010-12-30 01:11:185535 const GURL& url,
[email protected]70435962011-08-02 20:13:285536 const std::string& http_method,
[email protected]6d6cfb3a2012-05-23 22:53:185537 const std::string& mime_type,
Kinuko Yasuda433f710a2020-02-14 02:11:585538 network::mojom::RequestDestination request_destination) {
Alexander Timin5fdeff22020-09-08 09:20:375539 OPTIONAL_TRACE_EVENT2(
5540 "content", "WebContentsImpl::DidLoadResourceFromMemoryCache",
5541 "render_frame_host", base::trace_event::ToTracedValue(source), "url",
5542 base::trace_event::ValueToString(url));
Alexander Timin90c20c32020-08-12 15:28:325543 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5544 observer->DidLoadResourceFromMemoryCache(url, mime_type,
5545 request_destination);
5546 });
[email protected]b0f724c2013-09-05 04:21:135547
Steven Bingler674fb0822018-12-12 18:04:525548 if (url.is_valid() && url.SchemeIsHTTPOrHTTPS()) {
nicka0ac8382016-12-15 23:59:235549 StoragePartition* partition = source->GetProcess()->GetStoragePartition();
John Abd-El-Malekf4fe9d82019-07-31 04:05:595550 partition->GetNetworkContext()->NotifyExternalCacheHit(
Matt Menke2a33dee2019-12-02 17:01:545551 url, http_method, source->GetNetworkIsolationKey());
[email protected]8bfc8272013-09-09 20:10:535552 }
[email protected]724159a2010-12-30 01:11:185553}
5554
carloskd9d97942017-02-16 08:58:095555void WebContentsImpl::DidDisplayInsecureContent() {
Alexander Timin5fdeff22020-09-08 09:20:375556 OPTIONAL_TRACE_EVENT0("content",
5557 "WebContentsImpl::DidDisplayInsecureContent");
estarkc2273502016-10-12 22:03:025558 controller_.ssl_manager()->DidDisplayMixedContent();
[email protected]724159a2010-12-30 01:11:185559}
5560
Dave Tapuskaa657d872019-10-21 20:23:215561void WebContentsImpl::DidContainInsecureFormAction() {
Alexander Timin5fdeff22020-09-08 09:20:375562 OPTIONAL_TRACE_EVENT0("content",
5563 "WebContentsImpl::DidContainInsecureFormAction");
elawrenceb2ac2a232017-03-27 21:46:255564 controller_.ssl_manager()->DidContainInsecureFormAction();
5565}
5566
Julie Jeongeun Kim0b103492020-01-29 05:30:515567void WebContentsImpl::DocumentAvailableInMainFrame() {
Alexander Timin5fdeff22020-09-08 09:20:375568 OPTIONAL_TRACE_EVENT0("content",
5569 "WebContentsImpl::DocumentAvailableInMainFrame");
Alexander Timin90c20c32020-08-12 15:28:325570 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5571 observer->DocumentAvailableInMainFrame();
5572 });
Julie Jeongeun Kim0b103492020-01-29 05:30:515573}
5574
nicka0ac8382016-12-15 23:59:235575void WebContentsImpl::OnDidRunInsecureContent(RenderFrameHostImpl* source,
5576 const GURL& security_origin,
estark910b4572015-12-09 20:55:415577 const GURL& target_url) {
Alexander Timin5fdeff22020-09-08 09:20:375578 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnDidRunInsecureContent",
5579 "render_frame_host",
5580 base::trace_event::ToTracedValue(source));
nicka0ac8382016-12-15 23:59:235581 // TODO(nick, estark): Should we call FilterURL using |source|'s process on
5582 // these parameters? |target_url| seems unused, except for a log message. And
5583 // |security_origin| might be replaceable with the origin of the main frame.
carloskd9d97942017-02-16 08:58:095584 DidRunInsecureContent(security_origin, target_url);
5585}
5586
5587void WebContentsImpl::DidRunInsecureContent(const GURL& security_origin,
5588 const GURL& target_url) {
Alexander Timin5fdeff22020-09-08 09:20:375589 OPTIONAL_TRACE_EVENT2(
5590 "content", "WebContentsImpl::DidRunInsecureContent", "security_origin",
5591 base::trace_event::ValueToString(security_origin), "target_url",
5592 base::trace_event::ValueToString(target_url));
[email protected]9450c462013-11-23 01:22:585593 LOG(WARNING) << security_origin << " ran insecure content from "
5594 << target_url.possibly_invalid_spec();
[email protected]e6e30ac2014-01-13 21:24:395595 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
estark910b4572015-12-09 20:55:415596 if (base::EndsWith(security_origin.spec(), kDotGoogleDotCom,
brettwa7ff1b292015-07-16 17:49:295597 base::CompareCase::INSENSITIVE_ASCII))
[email protected]e6e30ac2014-01-13 21:24:395598 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
estarkc2273502016-10-12 22:03:025599 controller_.ssl_manager()->DidRunMixedContent(security_origin);
[email protected]724159a2010-12-30 01:11:185600}
5601
carloskd9d97942017-02-16 08:58:095602void WebContentsImpl::PassiveInsecureContentFound(const GURL& resource_url) {
Alexander Timin5fdeff22020-09-08 09:20:375603 OPTIONAL_TRACE_EVENT1(
5604 "content", "WebContentsImpl::PassiveInsecureContentFound", "resource_url",
5605 base::trace_event::ValueToString(resource_url));
Sergey Kuznetsov3ebc01b2018-02-01 04:57:365606 if (delegate_) {
5607 delegate_->PassiveInsecureContentFound(resource_url);
5608 }
carloskd9d97942017-02-16 08:58:095609}
5610
5611bool WebContentsImpl::ShouldAllowRunningInsecureContent(
carloskd9d97942017-02-16 08:58:095612 bool allowed_per_prefs,
5613 const url::Origin& origin,
5614 const GURL& resource_url) {
Alexander Timin5fdeff22020-09-08 09:20:375615 OPTIONAL_TRACE_EVENT0("content",
5616 "WebContentsImpl::ShouldAllowRunningInsecureContent");
Sergey Kuznetsov3ebc01b2018-02-01 04:57:365617 if (delegate_) {
Carlos IL29294a62020-05-15 00:21:165618 return delegate_->ShouldAllowRunningInsecureContent(this, allowed_per_prefs,
5619 origin, resource_url);
Sergey Kuznetsov3ebc01b2018-02-01 04:57:365620 }
5621
5622 return allowed_per_prefs;
carloskd9d97942017-02-16 08:58:095623}
5624
Lukasz Anforowicze1b954d92017-10-30 21:28:065625void WebContentsImpl::ViewSource(RenderFrameHostImpl* frame) {
Alexander Timin5fdeff22020-09-08 09:20:375626 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ViewSource",
5627 "render_frame_host",
5628 base::trace_event::ToTracedValue(frame));
Lukasz Anforowicze1b954d92017-10-30 21:28:065629 DCHECK_EQ(this, WebContents::FromRenderFrameHost(frame));
5630
5631 // Don't do anything if there is no |delegate_| that could accept and show the
5632 // new WebContents containing the view-source.
5633 if (!delegate_)
5634 return;
5635
5636 // Use the last committed entry, since the pending entry hasn't loaded yet and
5637 // won't be copied into the cloned tab.
5638 NavigationEntryImpl* last_committed_entry =
Fergal Daly09d6c762020-05-29 02:05:185639 GetController().GetLastCommittedEntry();
Lukasz Anforowicze1b954d92017-10-30 21:28:065640 if (!last_committed_entry)
5641 return;
5642
5643 FrameNavigationEntry* frame_entry =
5644 last_committed_entry->GetFrameEntry(frame->frame_tree_node());
5645 if (!frame_entry)
5646 return;
5647
5648 // Any new WebContents opened while this WebContents is in fullscreen can be
5649 // used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:455650 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
5651 // The new view source contents will be independent of this contents, so
5652 // release the fullscreen block.
5653 fullscreen_block.RunAndReset();
Lukasz Anforowicze1b954d92017-10-30 21:28:065654
5655 // We intentionally don't share the SiteInstance with the original frame so
5656 // that view source has a consistent process model and always ends up in a new
5657 // process (https://crbug.com/699493).
5658 scoped_refptr<SiteInstanceImpl> site_instance_for_view_source = nullptr;
Lukasz Anforowicz435bcb582019-07-12 20:50:065659 // Referrer and initiator are not important, because view-source should not
5660 // hit the network, but should be served from the cache instead.
Lukasz Anforowicze1b954d92017-10-30 21:28:065661 Referrer referrer_for_view_source;
Lukasz Anforowicz435bcb582019-07-12 20:50:065662 base::Optional<url::Origin> initiator_for_view_source = base::nullopt;
Lukasz Anforowicze1b954d92017-10-30 21:28:065663 // Do not restore title, derive it from the url.
5664 base::string16 title_for_view_source;
5665 auto navigation_entry = std::make_unique<NavigationEntryImpl>(
5666 site_instance_for_view_source, frame_entry->url(),
Lukasz Anforowicz435bcb582019-07-12 20:50:065667 referrer_for_view_source, initiator_for_view_source,
5668 title_for_view_source, ui::PAGE_TRANSITION_LINK,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:095669 /* is_renderer_initiated = */ false,
5670 /* blob_url_loader_factory = */ nullptr);
Joel Hockey891e88062020-04-30 05:38:445671 const GURL url(content::kViewSourceScheme + std::string(":") +
5672 frame_entry->url().spec());
5673 navigation_entry->SetVirtualURL(url);
Matt Menkea56c5992020-04-10 20:53:565674 navigation_entry->set_isolation_info(
5675 frame->GetIsolationInfoForSubresources());
Yao Xiaof68f57d2019-10-03 04:20:055676
Lukasz Anforowicze1b954d92017-10-30 21:28:065677 // Do not restore scroller position.
5678 // TODO(creis, lukasza, arthursonzogni): Do not reuse the original PageState,
5679 // but start from a new one and only copy the needed data.
5680 const PageState& new_page_state =
5681 frame_entry->page_state().RemoveScrollOffset();
5682
5683 scoped_refptr<FrameNavigationEntry> new_frame_entry =
5684 navigation_entry->root_node()->frame_entry;
5685 new_frame_entry->set_method(frame_entry->method());
5686 new_frame_entry->SetPageState(new_page_state);
5687
5688 // Create a new WebContents, which is used to display the source code.
erikchenbee5c9622018-04-27 19:30:255689 std::unique_ptr<WebContents> view_source_contents =
Erik Chenbb8e738e2018-04-28 14:10:435690 Create(CreateParams(GetBrowserContext()));
Lukasz Anforowicze1b954d92017-10-30 21:28:065691
5692 // Restore the previously created NavigationEntry.
5693 std::vector<std::unique_ptr<NavigationEntry>> navigation_entries;
5694 navigation_entries.push_back(std::move(navigation_entry));
5695 view_source_contents->GetController().Restore(0, RestoreType::CURRENT_SESSION,
5696 &navigation_entries);
5697
5698 // Add |view_source_contents| as a new tab.
5699 gfx::Rect initial_rect;
5700 constexpr bool kUserGesture = true;
5701 bool ignored_was_blocked;
Joel Hockey891e88062020-04-30 05:38:445702 delegate_->AddNewContents(this, std::move(view_source_contents), url,
Lukasz Anforowicze1b954d92017-10-30 21:28:065703 WindowOpenDisposition::NEW_FOREGROUND_TAB,
5704 initial_rect, kUserGesture, &ignored_was_blocked);
5705 // Note that the |delegate_| could have deleted |view_source_contents| during
5706 // AddNewContents method call.
5707}
5708
Lukasz Anforowiczd334bba2020-02-10 23:32:555709void WebContentsImpl::SubresourceResponseStarted(const GURL& url,
5710 net::CertStatus cert_status) {
Alexander Timin5fdeff22020-09-08 09:20:375711 OPTIONAL_TRACE_EVENT1("content",
5712 "WebContentsImpl::SubresourceResponseStarted", "url",
5713 base::trace_event::ValueToString(url));
Lukasz Anforowiczd334bba2020-02-10 23:32:555714 controller_.ssl_manager()->DidStartResourceResponse(url, cert_status);
Jay Civellid5904f02018-03-23 19:43:575715 SetNotWaitingForResponse();
5716}
5717
Jay Civelli116683f2018-03-27 19:56:235718void WebContentsImpl::ResourceLoadComplete(
Jay Civelli52a63302018-04-30 22:39:555719 RenderFrameHost* render_frame_host,
Clark DuVall36164bd2018-08-09 22:49:085720 const GlobalRequestID& request_id,
Minggang Wangee5af392020-02-05 02:55:285721 blink::mojom::ResourceLoadInfoPtr resource_load_info) {
Alexander Timin5fdeff22020-09-08 09:20:375722 OPTIONAL_TRACE_EVENT2(
5723 "content", "WebContentsImpl::ResourceLoadComplete", "render_frame_host",
5724 base::trace_event::ToTracedValue(render_frame_host), "request_id",
5725 base::trace_event::TracedValue::Build(
5726 {{"child_id", request_id.child_id},
5727 {"request_id", request_id.request_id}}));
Alexander Timin90c20c32020-08-12 15:28:325728 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5729 observer->ResourceLoadComplete(render_frame_host, request_id,
5730 *resource_load_info);
5731 });
John Abd-El-Malekd4882642017-12-04 21:45:195732}
5733
Gyuyoung Kim1ac4ca782020-09-11 03:32:515734const blink::web_pref::WebPreferences&
5735WebContentsImpl::GetOrCreateWebPreferences() {
Alexander Timin5fdeff22020-09-08 09:20:375736 OPTIONAL_TRACE_EVENT0("content",
5737 "WebContentsImpl::GetOrCreateWebPreferences");
Rakina Zata Amni347b70902020-07-22 10:49:045738 // Compute WebPreferences based on the current state if it's null.
5739 if (!web_preferences_)
Rakina Zata Amni4029b6d2020-07-28 02:36:205740 OnWebPreferencesChanged();
Rakina Zata Amni347b70902020-07-22 10:49:045741 return *web_preferences_.get();
5742}
5743
5744bool WebContentsImpl::IsWebPreferencesSet() const {
5745 return web_preferences_.get();
5746}
5747
Gyuyoung Kim1ac4ca782020-09-11 03:32:515748void WebContentsImpl::SetWebPreferences(
5749 const blink::web_pref::WebPreferences& prefs) {
Alexander Timin5fdeff22020-09-08 09:20:375750 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetWebPreferences");
Gyuyoung Kim1ac4ca782020-09-11 03:32:515751 web_preferences_ = std::make_unique<blink::web_pref::WebPreferences>(prefs);
Rakina Zata Amni347b70902020-07-22 10:49:045752 // Get all the RenderViewHosts (except the ones for currently back-forward
5753 // cached pages), and make them send the current WebPreferences
5754 // to the renderer. WebPreferences updates for back-forward cached pages will
5755 // be sent when we restore those pages from the back-forward cache.
5756 for (auto& rvh : frame_tree_.render_view_hosts()) {
5757 rvh.second->SendWebPreferencesToRenderer();
5758 }
5759}
5760
5761void WebContentsImpl::RecomputeWebPreferencesSlow() {
Alexander Timin5fdeff22020-09-08 09:20:375762 OPTIONAL_TRACE_EVENT0("content",
5763 "WebContentsImpl::RecomputeWebPreferencesSlow");
Rakina Zata Amni4029b6d2020-07-28 02:36:205764 // OnWebPreferencesChanged is a no-op when this is true.
5765 if (updating_web_preferences_)
5766 return;
Rakina Zata Amni347b70902020-07-22 10:49:045767 // Resets |web_preferences_| so that we won't have any cached value for slow
5768 // attributes (which won't get recomputed if we have pre-existing values for
5769 // them).
5770 web_preferences_.reset();
Rakina Zata Amni4029b6d2020-07-28 02:36:205771 OnWebPreferencesChanged();
Rakina Zata Amni347b70902020-07-22 10:49:045772}
5773
Wei Li5bb659742018-02-14 03:07:585774void WebContentsImpl::PrintCrossProcessSubframe(
5775 const gfx::Rect& rect,
5776 int document_cookie,
5777 RenderFrameHost* subframe_host) {
Alexander Timin5fdeff22020-09-08 09:20:375778 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::PrintCrossProcessSubframe",
5779 "subframe",
5780 base::trace_event::ToTracedValue(subframe_host));
Wei Li5c0b4d12018-03-22 15:05:225781 auto* outer_contents = GetOuterWebContents();
5782 if (outer_contents) {
5783 // When an extension or app page is printed, the content should be
5784 // composited with outer content, so the outer contents should handle the
5785 // print request.
5786 outer_contents->PrintCrossProcessSubframe(rect, document_cookie,
5787 subframe_host);
5788 return;
5789 }
5790
Wei Li5bb659742018-02-14 03:07:585791 // If there is no delegate such as in tests or during deletion, do nothing.
5792 if (!delegate_)
5793 return;
5794
5795 delegate_->PrintCrossProcessSubframe(this, rect, document_cookie,
5796 subframe_host);
5797}
5798
ckitagawa8695799b2020-02-05 16:08:495799void WebContentsImpl::CapturePaintPreviewOfCrossProcessSubframe(
5800 const gfx::Rect& rect,
5801 const base::UnguessableToken& guid,
5802 RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:375803 OPTIONAL_TRACE_EVENT1(
5804 "content", "WebContentsImpl::CapturePaintPreviewOfCrossProcessSubframe",
5805 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host));
ckitagawa8695799b2020-02-05 16:08:495806 if (!delegate_)
5807 return;
ckitagawac43ac982020-07-07 17:41:175808 delegate_->CapturePaintPreviewOfSubframe(this, rect, guid, render_frame_host);
ckitagawa8695799b2020-02-05 16:08:495809}
5810
rob.buis300b0872017-03-10 20:43:585811#if defined(OS_ANDROID)
5812base::android::ScopedJavaLocalRef<jobject>
5813WebContentsImpl::GetJavaRenderFrameHostDelegate() {
5814 return GetJavaWebContents();
5815}
5816#endif
5817
Hiroki Nakagawa39d1bbe2020-07-14 16:15:525818void WebContentsImpl::OnDidDisplayContentWithCertificateErrors() {
Alexander Timin5fdeff22020-09-08 09:20:375819 OPTIONAL_TRACE_EVENT0(
5820 "content", "WebContentsImpl::OnDidDisplayContentWithCertificateErrors");
estarkc2273502016-10-12 22:03:025821 controller_.ssl_manager()->DidDisplayContentWithCertErrors();
estark910b4572015-12-09 20:55:415822}
5823
5824void WebContentsImpl::OnDidRunContentWithCertificateErrors(
Zhuoyu Qian4353f7f2018-01-08 05:33:005825 RenderFrameHostImpl* source) {
Alexander Timin5fdeff22020-09-08 09:20:375826 OPTIONAL_TRACE_EVENT1(
5827 "content", "WebContentsImpl::OnDidRunContentWithCertificateErrors",
5828 "render_frame_host", base::trace_event::ToTracedValue(source));
Emily Starkabbdd662020-06-05 02:40:135829 // For RenderFrameHosts that are inactive and going to be discarded, we can
5830 // disregard this message; there's no need to update the UI if the UI will
5831 // never be shown again.
5832 //
5833 // We still process this message for speculative RenderFrameHosts. This can
5834 // happen when a subframe's main resource has a certificate error. The
5835 // currently committed navigation entry will get marked as having run insecure
5836 // content and that will carry over to the navigation entry for the
5837 // speculative RFH when it commits.
5838 if (source->lifecycle_state() !=
5839 RenderFrameHostImpl::LifecycleState::kSpeculative &&
5840 source->IsInactiveAndDisallowReactivation()) {
estarkaeda1422016-05-10 02:31:125841 return;
Emily Starkabbdd662020-06-05 02:40:135842 }
estarkcd2e30c2016-08-12 06:51:155843 controller_.ssl_manager()->DidRunContentWithCertErrors(
Emily Starkabbdd662020-06-05 02:40:135844 source->GetMainFrame()->GetLastCommittedOrigin().GetURL());
estark910b4572015-12-09 20:55:415845}
5846
Kouhei Ueno97e0990d2019-09-25 02:57:275847void WebContentsImpl::DOMContentLoaded(RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:375848 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DOMContentLoaded",
5849 "render_frame_host",
5850 base::trace_event::ToTracedValue(render_frame_host));
Alexander Timin90c20c32020-08-12 15:28:325851 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5852 observer->DOMContentLoaded(render_frame_host);
5853 });
[email protected]724159a2010-12-30 01:11:185854}
5855
Gyuyoung Kim525e0c5d2020-03-09 15:04:195856void WebContentsImpl::OnDidFinishLoad(RenderFrameHost* render_frame_host,
nicka0ac8382016-12-15 23:59:235857 const GURL& url) {
Alexander Timin5fdeff22020-09-08 09:20:375858 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnDidFinishLoad",
5859 "render_frame_host",
5860 base::trace_event::ToTracedValue(render_frame_host),
5861 "url", base::trace_event::ValueToString(url));
[email protected]8b3af1e2014-01-24 13:29:125862 GURL validated_url(url);
Gyuyoung Kim525e0c5d2020-03-09 15:04:195863 render_frame_host->GetProcess()->FilterURL(false, &validated_url);
[email protected]028053d42014-03-05 22:20:375864
Alexander Timin90c20c32020-08-12 15:28:325865 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5866 observer->DidFinishLoad(render_frame_host, validated_url);
5867 });
yilkal172da772019-11-06 22:49:075868 size_t tree_size = frame_tree_.root()->GetFrameTreeSize();
5869 if (max_loaded_frame_count_ < tree_size)
5870 max_loaded_frame_count_ = tree_size;
5871
Gyuyoung Kim525e0c5d2020-03-09 15:04:195872 if (!render_frame_host->GetParent())
yilkal172da772019-11-06 22:49:075873 UMA_HISTOGRAM_COUNTS_1000("Navigation.MainFrame.FrameCount", tree_size);
[email protected]1a55c5be2011-11-29 11:36:315874}
5875
Dave Tapuska549baab2019-03-19 15:52:405876void WebContentsImpl::OnGoToEntryAtOffset(RenderFrameHostImpl* source,
Julie Jeongeun Kim144f8192020-01-18 06:59:035877 int32_t offset,
Dave Tapuska043b94a2019-09-10 14:14:355878 bool has_user_gesture) {
Alexander Timin5fdeff22020-09-08 09:20:375879 OPTIONAL_TRACE_EVENT2(
5880 "content", "WebContentsImpl::OnGoToEntryAtOffset", "render_frame_host",
5881 base::trace_event::ToTracedValue(source), "offset", offset);
Arthur Sonzognia7d715a2018-09-20 16:11:135882 // Non-user initiated navigations coming from the renderer should be ignored
5883 // if there is an ongoing browser-initiated navigation.
5884 // See https://crbug.com/879965.
5885 // TODO(arthursonzogni): See if this should check for ongoing navigations in
5886 // the frame(s) affected by the session history navigation, rather than just
5887 // the main frame.
Kevin McNee96851e12020-07-16 03:43:225888 if (Navigator::ShouldIgnoreIncomingRendererRequest(
5889 frame_tree_.root()->navigation_request(), has_user_gesture))
5890 return;
Arthur Sonzognia7d715a2018-09-20 16:11:135891
nicka0ac8382016-12-15 23:59:235892 // All frames are allowed to navigate the global history.
Dave Tapuska8bfd84c2019-03-26 20:47:165893 if (!delegate_ || delegate_->OnGoToEntryOffset(offset)) {
arthursonzognib93a4472020-04-10 07:38:005894 if (source->IsSandboxed(network::mojom::WebSandboxFlags::kTopNavigation)) {
Dave Tapuska8bfd84c2019-03-26 20:47:165895 // Keep track of whether this is a session history from a sandboxed iframe
5896 // with top level navigation disallowed.
5897 controller_.GoToOffsetInSandboxedFrame(offset,
5898 source->GetFrameTreeNodeId());
5899 } else {
5900 controller_.GoToOffset(offset);
5901 }
5902 }
[email protected]216813952011-05-19 22:21:265903}
5904
Dave Tapuska4c02911b2020-02-14 22:52:075905void WebContentsImpl::OnPageScaleFactorChanged(RenderFrameHostImpl* source,
nicka0ac8382016-12-15 23:59:235906 float page_scale_factor) {
Alexander Timin5fdeff22020-09-08 09:20:375907 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnPageScaleFactorChanged",
5908 "render_frame_host",
5909 base::trace_event::ToTracedValue(source),
5910 "page_scale_factor", page_scale_factor);
mcnee336ea2c2017-05-23 22:50:595911#if !defined(OS_ANDROID)
5912 // While page scale factor is used on mobile, this PageScaleFactorIsOne logic
5913 // is only needed on desktop.
mcnee432e47d2015-11-09 19:37:465914 bool is_one = page_scale_factor == 1.f;
5915 if (is_one != page_scale_factor_is_one_) {
5916 page_scale_factor_is_one_ = is_one;
5917
5918 HostZoomMapImpl* host_zoom_map =
5919 static_cast<HostZoomMapImpl*>(HostZoomMap::GetForWebContents(this));
5920
nicka0ac8382016-12-15 23:59:235921 if (host_zoom_map) {
mcnee432e47d2015-11-09 19:37:465922 host_zoom_map->SetPageScaleFactorIsOneForView(
Dave Tapuska4c02911b2020-02-14 22:52:075923 source->GetProcess()->GetID(),
5924 source->GetRenderViewHost()->GetRoutingID(),
mcnee432e47d2015-11-09 19:37:465925 page_scale_factor_is_one_);
5926 }
5927 }
mcnee336ea2c2017-05-23 22:50:595928#endif // !defined(OS_ANDROID)
mcnee432e47d2015-11-09 19:37:465929
Alexander Timin90c20c32020-08-12 15:28:325930 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5931 observer->OnPageScaleFactorChanged(page_scale_factor);
5932 });
mcnee432e47d2015-11-09 19:37:465933}
5934
W. James MacLean62198672019-06-04 16:46:105935void WebContentsImpl::OnTextAutosizerPageInfoChanged(
Henrique Ferreiroba535472020-04-21 11:38:365936 RenderFrameHostImpl* source,
5937 blink::mojom::TextAutosizerPageInfoPtr page_info) {
Alexander Timin5fdeff22020-09-08 09:20:375938 OPTIONAL_TRACE_EVENT1(
5939 "content", "WebContentsImpl::OnTextAutosizerPageInfoChanged",
5940 "render_frame_host", base::trace_event::ToTracedValue(source));
W. James MacLean62198672019-06-04 16:46:105941 // Keep a copy of |page_info| in case we create a new RenderView before
5942 // the next update.
Henrique Ferreiroba535472020-04-21 11:38:365943 text_autosizer_page_info_.main_frame_width = page_info->main_frame_width;
5944 text_autosizer_page_info_.main_frame_layout_width =
5945 page_info->main_frame_layout_width;
5946 text_autosizer_page_info_.device_scale_adjustment =
5947 page_info->device_scale_adjustment;
Antonio Gomesda7e03d2020-08-05 15:03:085948
5949 auto remote_frames_broadcast_callback = base::BindRepeating(
5950 [](const blink::mojom::TextAutosizerPageInfo& page_info,
5951 RenderFrameProxyHost* proxy_host) {
5952 DCHECK(proxy_host);
5953 proxy_host->GetAssociatedRemoteMainFrame()->UpdateTextAutosizerPageInfo(
5954 page_info.Clone());
5955 },
5956 text_autosizer_page_info_);
5957
5958 frame_tree_.root()->render_manager()->ExecuteRemoteFramesBroadcastMethod(
5959 std::move(remote_frames_broadcast_callback), source->GetSiteInstance());
W. James MacLean62198672019-06-04 16:46:105960}
5961
Kent Tamura8c9e0562018-11-06 07:02:195962void WebContentsImpl::EnumerateDirectory(
5963 RenderFrameHost* render_frame_host,
Kent Tamura3abb32d2020-07-02 00:23:015964 scoped_refptr<FileChooserImpl::FileSelectListenerImpl> listener,
Kent Tamura8c9e0562018-11-06 07:02:195965 const base::FilePath& directory_path) {
Alexander Timin5fdeff22020-09-08 09:20:375966 OPTIONAL_TRACE_EVENT2(
5967 "content", "WebContentsImpl::EnumerateDirectory", "render_frame_host",
5968 base::trace_event::ToTracedValue(render_frame_host), "directory_path",
5969 base::trace_event::ValueToString(directory_path));
Avi Drissman1a55a9d62020-03-10 18:56:455970 // Any explicit focusing of another window while this WebContents is in
5971 // fullscreen can be used to confuse the user, so drop fullscreen.
5972 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
5973 listener->SetFullscreenBlock(std::move(fullscreen_block));
5974
Kent Tamura8c9e0562018-11-06 07:02:195975 if (delegate_)
5976 delegate_->EnumerateDirectory(this, std::move(listener), directory_path);
5977 else
5978 listener->FileSelectionCanceled();
[email protected]3a29a6e2011-08-24 18:26:215979}
5980
Dave Tapuskaf9fc3122019-10-18 19:42:555981void WebContentsImpl::RegisterProtocolHandler(RenderFrameHostImpl* source,
5982 const std::string& protocol,
5983 const GURL& url,
5984 const base::string16& title,
5985 bool user_gesture) {
Alexander Timin5fdeff22020-09-08 09:20:375986 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RegisterProtocolHandler",
5987 "render_frame_host",
5988 base::trace_event::ToTracedValue(source), "protocol",
5989 protocol);
nicka0ac8382016-12-15 23:59:235990 // TODO(nick): Do we need to apply FilterURL to |url|?
[email protected]e5f2de02012-07-20 22:15:435991 if (!delegate_)
5992 return;
5993
Raymes Khoury58373df2019-08-06 06:29:205994 if (!AreValidRegisterProtocolHandlerArguments(
5995 protocol, url, source->GetLastCommittedOrigin())) {
5996 ReceivedBadMessage(source->GetProcess(),
5997 bad_message::REGISTER_PROTOCOL_HANDLER_INVALID_URL);
[email protected]b9535422012-02-09 01:47:595998 return;
Raymes Khoury58373df2019-08-06 06:29:205999 }
[email protected]8f810632013-06-06 22:33:326000
Carlos Caballero8a6c6b72020-07-20 16:56:226001 delegate_->RegisterProtocolHandler(source, protocol, url, user_gesture);
[email protected]7d189022011-08-25 22:54:206002}
6003
Dave Tapuskaf9fc3122019-10-18 19:42:556004void WebContentsImpl::UnregisterProtocolHandler(RenderFrameHostImpl* source,
6005 const std::string& protocol,
6006 const GURL& url,
6007 bool user_gesture) {
Alexander Timin5fdeff22020-09-08 09:20:376008 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::UnregisterProtocolHandler",
6009 "render_frame_host",
6010 base::trace_event::ToTracedValue(source), "protocol",
6011 protocol);
nicka0ac8382016-12-15 23:59:236012 // TODO(nick): Do we need to apply FilterURL to |url|?
[email protected]f5273e52014-07-14 16:30:206013 if (!delegate_)
6014 return;
6015
Raymes Khoury58373df2019-08-06 06:29:206016 if (!AreValidRegisterProtocolHandlerArguments(
6017 protocol, url, source->GetLastCommittedOrigin())) {
6018 ReceivedBadMessage(source->GetProcess(),
6019 bad_message::REGISTER_PROTOCOL_HANDLER_INVALID_URL);
[email protected]f5273e52014-07-14 16:30:206020 return;
Raymes Khoury58373df2019-08-06 06:29:206021 }
[email protected]f5273e52014-07-14 16:30:206022
Carlos Caballero8a6c6b72020-07-20 16:56:226023 delegate_->UnregisterProtocolHandler(source, protocol, url, user_gesture);
[email protected]f5273e52014-07-14 16:30:206024}
6025
Marijn Kruisselbrink7f519672019-02-05 19:12:506026void WebContentsImpl::OnAppCacheAccessed(const GURL& manifest_url,
[email protected]b172aee2012-04-10 17:05:266027 bool blocked_by_policy) {
Alexander Timin5fdeff22020-09-08 09:20:376028 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnAppCacheAccessed");
nicka0ac8382016-12-15 23:59:236029 // TODO(nick): Should we consider |source| here? Should we call FilterURL on
6030 // |manifest_url|?
6031
[email protected]7fc4bbb2011-09-08 21:23:106032 // Notify observers about navigation.
Alexander Timin90c20c32020-08-12 15:28:326033 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6034 observer->AppCacheAccessed(manifest_url, blocked_by_policy);
6035 });
[email protected]7fc4bbb2011-09-08 21:23:106036}
6037
Gyuyoung Kimc5f4ac12020-05-08 10:59:396038void WebContentsImpl::DomOperationResponse(const std::string& json_string) {
Alexander Timin5fdeff22020-09-08 09:20:376039 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DomOperationResponse",
6040 "json_string", json_string);
6041
Gyuyoung Kimc5f4ac12020-05-08 10:59:396042 // TODO(lukasza): The notification below should probably indicate which
6043 // RenderFrameHostImpl the message is coming from. This can enable tests to
6044 // talk to 2 frames at the same time, without being confused which frame a
6045 // given response comes from. See also a corresponding TODO in the
6046 // ExecuteScriptHelper in //content/public/test/browser_test_utils.cc
6047 NotificationService::current()->Notify(
6048 NOTIFICATION_DOM_OPERATION_RESPONSE, Source<WebContents>(this),
6049 Details<const std::string>(&json_string));
6050}
6051
Gyuyoung Kim4c50517842020-06-04 17:50:446052void WebContentsImpl::SavableResourceLinksResponse(
6053 RenderFrameHostImpl* source,
6054 const std::vector<GURL>& resources_list,
6055 blink::mojom::ReferrerPtr referrer,
6056 const std::vector<blink::mojom::SavableSubframePtr>& subframes) {
Alexander Timin5fdeff22020-09-08 09:20:376057 OPTIONAL_TRACE_EVENT1(
6058 "content", "WebContentsImpl::SavableResourceLinksResponse",
6059 "render_frame_host", base::trace_event::ToTracedValue(source));
Gyuyoung Kim4c50517842020-06-04 17:50:446060 save_package_->SavableResourceLinksResponse(source, resources_list,
6061 std::move(referrer), subframes);
6062}
6063
6064void WebContentsImpl::SavableResourceLinksError(RenderFrameHostImpl* source) {
Alexander Timin5fdeff22020-09-08 09:20:376065 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SavableResourceLinksError",
6066 "render_frame_host",
6067 base::trace_event::ToTracedValue(source));
Gyuyoung Kim4c50517842020-06-04 17:50:446068 save_package_->SavableResourceLinksError(source);
6069}
6070
Alexander Timin17edc742020-04-23 18:22:186071void WebContentsImpl::OnServiceWorkerAccessed(
6072 RenderFrameHost* render_frame_host,
6073 const GURL& scope,
6074 AllowServiceWorkerResult allowed) {
Alexander Timin5fdeff22020-09-08 09:20:376075 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnServiceWorkerAccessed",
6076 "render_frame_host",
6077 base::trace_event::ToTracedValue(render_frame_host),
6078 "scope", base::trace_event::ValueToString(scope));
Alexander Timin90c20c32020-08-12 15:28:326079 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6080 observer->OnServiceWorkerAccessed(render_frame_host, scope, allowed);
6081 });
Alexander Timin17edc742020-04-23 18:22:186082}
6083
6084void WebContentsImpl::OnServiceWorkerAccessed(
6085 NavigationHandle* navigation,
6086 const GURL& scope,
6087 AllowServiceWorkerResult allowed) {
Alexander Timin5fdeff22020-09-08 09:20:376088 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnServiceWorkerAccessed",
6089 "navigation_handle", navigation, "scope",
6090 base::trace_event::ValueToString(scope));
Alexander Timin90c20c32020-08-12 15:28:326091 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6092 observer->OnServiceWorkerAccessed(navigation, scope, allowed);
6093 });
Alexander Timin17edc742020-04-23 18:22:186094}
6095
Miyoung Shincb6475a2019-11-09 10:49:456096void WebContentsImpl::OnColorChooserFactoryReceiver(
Julie Jeongeun Kim8e2879e2019-08-06 23:55:206097 mojo::PendingReceiver<blink::mojom::ColorChooserFactory> receiver) {
Alexander Timin5fdeff22020-09-08 09:20:376098 OPTIONAL_TRACE_EVENT0("content",
6099 "WebContentsImpl::OnColorChooserFactoryReceiver");
Julie Jeongeun Kim8e2879e2019-08-06 23:55:206100 color_chooser_factory_receivers_.Add(this, std::move(receiver));
Joel Hockey85b379d2017-12-11 10:42:136101}
6102
6103void WebContentsImpl::OpenColorChooser(
Julie Jeongeun Kim8e2879e2019-08-06 23:55:206104 mojo::PendingReceiver<blink::mojom::ColorChooser> chooser_receiver,
6105 mojo::PendingRemote<blink::mojom::ColorChooserClient> client,
[email protected]8ed16472014-04-11 19:02:486106 SkColor color,
Joel Hockey163835a2017-12-20 11:51:576107 std::vector<blink::mojom::ColorSuggestionPtr> suggestions) {
Alexander Timin5fdeff22020-09-08 09:20:376108 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OpenColorChooser");
Joel Hockey85b379d2017-12-11 10:42:136109 content::ColorChooser* new_color_chooser =
Ivan Kotenkov2c0d2bb32017-11-01 15:41:286110 delegate_ ? delegate_->OpenColorChooser(this, color, suggestions)
6111 : nullptr;
[email protected]820957a2014-01-14 14:56:306112 if (!new_color_chooser)
[email protected]cb805452013-05-22 15:16:216113 return;
[email protected]8ed16472014-04-11 19:02:486114
Joel Hockey85b379d2017-12-11 10:42:136115 color_chooser_.reset();
6116 color_chooser_ = std::make_unique<ColorChooser>(
Julie Jeongeun Kim8e2879e2019-08-06 23:55:206117 new_color_chooser, std::move(chooser_receiver), std::move(client));
[email protected]da8543762012-03-20 08:52:206118}
6119
brettw4b461082016-11-19 18:55:166120#if BUILDFLAG(ENABLE_PLUGINS)
nicka0ac8382016-12-15 23:59:236121void WebContentsImpl::OnPepperInstanceCreated(RenderFrameHostImpl* source,
6122 int32_t pp_instance) {
Alexander Timin5fdeff22020-09-08 09:20:376123 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPepperInstanceCreated",
6124 "render_frame_host",
6125 base::trace_event::ToTracedValue(source));
Alexander Timin90c20c32020-08-12 15:28:326126 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6127 observer->PepperInstanceCreated();
6128 });
nicka0ac8382016-12-15 23:59:236129 pepper_playback_observer_->PepperInstanceCreated(source, pp_instance);
emaxxe70f5e12015-05-29 11:26:006130}
6131
nicka0ac8382016-12-15 23:59:236132void WebContentsImpl::OnPepperInstanceDeleted(RenderFrameHostImpl* source,
6133 int32_t pp_instance) {
Alexander Timin5fdeff22020-09-08 09:20:376134 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPepperInstanceDeleted",
6135 "render_frame_host",
6136 base::trace_event::ToTracedValue(source));
Alexander Timin90c20c32020-08-12 15:28:326137 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6138 observer->PepperInstanceDeleted();
6139 });
nicka0ac8382016-12-15 23:59:236140 pepper_playback_observer_->PepperInstanceDeleted(source, pp_instance);
emaxxe70f5e12015-05-29 11:26:006141}
6142
nicka0ac8382016-12-15 23:59:236143void WebContentsImpl::OnPepperPluginHung(RenderFrameHostImpl* source,
6144 int plugin_child_id,
tommyclie6633ca72014-10-31 00:40:426145 const base::FilePath& path,
6146 bool is_hung) {
Alexander Timin5fdeff22020-09-08 09:20:376147 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPepperPluginHung",
6148 "render_frame_host",
6149 base::trace_event::ToTracedValue(source));
Steven Holte95922222018-09-14 20:06:236150 UMA_HISTOGRAM_COUNTS_1M("Pepper.PluginHung", 1);
tommyclie6633ca72014-10-31 00:40:426151
Alexander Timin90c20c32020-08-12 15:28:326152 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6153 observer->PluginHungStatusChanged(plugin_child_id, path, is_hung);
6154 });
tommyclie6633ca72014-10-31 00:40:426155}
6156
nicka0ac8382016-12-15 23:59:236157void WebContentsImpl::OnPepperStartsPlayback(RenderFrameHostImpl* source,
6158 int32_t pp_instance) {
Alexander Timin5fdeff22020-09-08 09:20:376159 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPepperStartsPlayback",
6160 "render_frame_host",
6161 base::trace_event::ToTracedValue(source));
nicka0ac8382016-12-15 23:59:236162 pepper_playback_observer_->PepperStartsPlayback(source, pp_instance);
zqzhang181047e62016-07-01 13:37:176163}
6164
nicka0ac8382016-12-15 23:59:236165void WebContentsImpl::OnPepperStopsPlayback(RenderFrameHostImpl* source,
6166 int32_t pp_instance) {
Alexander Timin5fdeff22020-09-08 09:20:376167 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPepperStopsPlayback",
6168 "render_frame_host",
6169 base::trace_event::ToTracedValue(source));
nicka0ac8382016-12-15 23:59:236170 pepper_playback_observer_->PepperStopsPlayback(source, pp_instance);
zqzhang181047e62016-07-01 13:37:176171}
6172
nicka0ac8382016-12-15 23:59:236173void WebContentsImpl::OnPluginCrashed(RenderFrameHostImpl* source,
6174 const base::FilePath& plugin_path,
tommyclie6633ca72014-10-31 00:40:426175 base::ProcessId plugin_pid) {
Alexander Timin5fdeff22020-09-08 09:20:376176 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPluginCrashed",
6177 "render_frame_host",
6178 base::trace_event::ToTracedValue(source));
nicka0ac8382016-12-15 23:59:236179 // TODO(nick): Eliminate the |plugin_pid| parameter, which can't be trusted,
Gyuyoung Kim26c7bc92020-04-29 00:53:006180 // and is only used by WebTestControlHost.
Alexander Timin90c20c32020-08-12 15:28:326181 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6182 observer->PluginCrashed(plugin_path, plugin_pid);
6183 });
tommyclie6633ca72014-10-31 00:40:426184}
6185
[email protected]d8415ad92012-08-23 14:40:506186void WebContentsImpl::OnRequestPpapiBrokerPermission(
nicka0ac8382016-12-15 23:59:236187 RenderViewHostImpl* source,
6188 int ppb_broker_route_id,
[email protected]d8415ad92012-08-23 14:40:506189 const GURL& url,
[email protected]2dec8ec2013-02-07 19:20:346190 const base::FilePath& plugin_path) {
Alexander Timin5fdeff22020-09-08 09:20:376191 OPTIONAL_TRACE_EVENT1("content",
6192 "WebContentsImpl::OnRequestPpapiBrokerPermission",
6193 "render_view_host", source);
Avi Drissman0a2a967d2019-04-01 19:33:526194 base::OnceCallback<void(bool)> permission_result_callback = base::BindOnce(
nicka0ac8382016-12-15 23:59:236195 &WebContentsImpl::SendPpapiBrokerPermissionResult, base::Unretained(this),
6196 source->GetProcess()->GetID(), ppb_broker_route_id);
[email protected]8c8fc292012-11-23 18:57:166197 if (!delegate_) {
Tommy Nyquist4b749d02018-03-20 21:46:296198 std::move(permission_result_callback).Run(false);
[email protected]8c8fc292012-11-23 18:57:166199 return;
[email protected]d8415ad92012-08-23 14:40:506200 }
6201
Avi Drissman0a2a967d2019-04-01 19:33:526202 delegate_->RequestPpapiBrokerPermission(
6203 this, url, plugin_path, std::move(permission_result_callback));
[email protected]d8415ad92012-08-23 14:40:506204}
6205
nicka0ac8382016-12-15 23:59:236206void WebContentsImpl::SendPpapiBrokerPermissionResult(int process_id,
6207 int ppb_broker_route_id,
6208 bool result) {
Alexander Timin5fdeff22020-09-08 09:20:376209 OPTIONAL_TRACE_EVENT2(
6210 "content", "WebContentsImpl::SendPpapiBrokerPermissionResult",
6211 "process_id", process_id, "ppb_broker_route_id", ppb_broker_route_id);
nicka0ac8382016-12-15 23:59:236212 RenderProcessHost* rph = RenderProcessHost::FromID(process_id);
6213 if (rph) {
6214 // TODO(nick): Convert this from ViewMsg_ to a Ppapi msg, since it
6215 // is not routed to a RenderView.
6216 rph->Send(
6217 new ViewMsg_PpapiBrokerPermissionResult(ppb_broker_route_id, result));
6218 }
[email protected]d8415ad92012-08-23 14:40:506219}
brettw4b461082016-11-19 18:55:166220#endif // BUILDFLAG(ENABLE_PLUGINS)
[email protected]19be7a62012-10-01 23:03:376221
Miyoung Shin5709ab02020-02-19 06:50:416222void WebContentsImpl::UpdateFaviconURL(
6223 RenderFrameHost* source,
6224 std::vector<blink::mojom::FaviconURLPtr> candidates) {
Alexander Timin5fdeff22020-09-08 09:20:376225 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::UpdateFaviconURL",
6226 "render_frame_host",
6227 base::trace_event::ToTracedValue(source));
lukasza178ff092017-06-07 23:39:506228 // Ignore favicons for non-main frame.
6229 if (source->GetParent()) {
6230 NOTREACHED();
6231 return;
6232 }
6233
pkotwiczf9bc20592015-04-21 18:57:066234 // We get updated favicon URLs after the page stops loading. If a cross-site
6235 // navigation occurs while a page is still loading, the initial page
6236 // may stop loading and send us updated favicon URLs after the navigation
6237 // for the new page has committed.
lukasza178ff092017-06-07 23:39:506238 if (!source->IsCurrent())
pkotwiczf9bc20592015-04-21 18:57:066239 return;
6240
Miyoung Shin5709ab02020-02-19 06:50:416241 favicon_urls_ = std::move(candidates);
Mounir Lamouri7b4a1f232019-12-23 16:32:106242
Alexander Timin90c20c32020-08-12 15:28:326243 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6244 observer->DidUpdateFaviconURL(source, favicon_urls_);
6245 });
[email protected]795c28972012-12-06 06:13:396246}
6247
qinmin72e8bd02016-10-21 19:35:376248void WebContentsImpl::SetIsOverlayContent(bool is_overlay_content) {
Alexander Timin5fdeff22020-09-08 09:20:376249 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetIsOverlayContent",
6250 "is_overlay_content", is_overlay_content);
qinmin72e8bd02016-10-21 19:35:376251 is_overlay_content_ = is_overlay_content;
6252}
6253
Albert J. Wongfb64e142018-10-16 01:10:456254void WebContentsImpl::DidFirstVisuallyNonEmptyPaint(
6255 RenderViewHostImpl* source) {
Alexander Timin5fdeff22020-09-08 09:20:376256 OPTIONAL_TRACE_EVENT1("content",
6257 "WebContentsImpl::DidFirstVisuallyNonEmptyPaint",
6258 "render_view_host", source);
nicka0ac8382016-12-15 23:59:236259 // TODO(nick): When this is ported to FrameHostMsg_, we should only listen if
6260 // |source| is the main frame.
Alexander Timin90c20c32020-08-12 15:28:326261 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6262 observer->DidFirstVisuallyNonEmptyPaint();
6263 });
Carlos Caballero1215f882019-10-29 15:58:436264 if (source->theme_color() != last_sent_theme_color_) {
yusufod41c5f92015-03-06 00:14:286265 // Theme color should have updated by now if there was one.
Alexander Timin90c20c32020-08-12 15:28:326266 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6267 observer->DidChangeThemeColor();
6268 });
Carlos Caballero1215f882019-10-29 15:58:436269 last_sent_theme_color_ = source->theme_color();
yusufod41c5f92015-03-06 00:14:286270 }
Alan Cutterd73a15d92020-08-21 07:12:456271
6272 if (source->background_color() != last_sent_background_color_) {
6273 // Background color should have updated by now if there was one.
6274 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6275 observer->OnBackgroundColorChanged();
6276 });
6277 last_sent_background_color_ = source->background_color();
6278 }
[email protected]9f268072013-11-07 00:02:156279}
[email protected]d9030b82013-07-19 08:26:066280
Kevin McNee068c3eb2020-04-03 18:24:196281bool WebContentsImpl::IsPortal() {
Adithya Srinivasan46b8a792019-02-01 14:47:236282 return portal();
6283}
6284
Kevin McNee94ea52f52020-06-23 17:42:066285WebContentsImpl* WebContentsImpl::GetPortalHostWebContents() {
6286 return portal() ? portal()->GetPortalHostContents() : nullptr;
6287}
6288
[email protected]17e286e2013-03-01 23:29:396289void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
Alexander Timin5fdeff22020-09-08 09:20:376290 OPTIONAL_TRACE_EVENT0("content",
6291 "WebContentsImpl::NotifyBeforeFormRepostWarningShow");
Alexander Timin90c20c32020-08-12 15:28:326292 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6293 observer->BeforeFormRepostWarningShow();
6294 });
[email protected]17e286e2013-03-01 23:29:396295}
6296
[email protected]ec6c05f2013-10-23 18:41:576297void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
Alexander Timin5fdeff22020-09-08 09:20:376298 OPTIONAL_TRACE_EVENT0(
6299 "content", "WebContentsImpl::ActivateAndShowRepostFormWarningDialog");
[email protected]ec6c05f2013-10-23 18:41:576300 Activate();
6301 if (delegate_)
6302 delegate_->ShowRepostFormWarningDialog(this);
6303}
6304
[email protected]b4c84012014-04-28 19:51:106305bool WebContentsImpl::HasAccessedInitialDocument() {
6306 return has_accessed_initial_document_;
6307}
6308
afakhry6f0c1ec22016-07-14 13:55:136309void WebContentsImpl::UpdateTitleForEntry(NavigationEntry* entry,
[email protected]fcf75d42013-12-03 20:11:266310 const base::string16& title) {
Alexander Timin5fdeff22020-09-08 09:20:376311 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::UpdateTitleForEntry",
6312 "title", base::trace_event::ValueToString(title));
[email protected]fcf75d42013-12-03 20:11:266313 base::string16 final_title;
Avi Drissman93002212017-09-27 03:20:526314 base::TrimWhitespace(title, base::TRIM_ALL, &final_title);
[email protected]420ae012009-04-24 05:16:326315
[email protected]987fc3a2011-05-26 14:18:096316 // If a page is created via window.open and never navigated,
6317 // there will be no navigation entry. In this situation,
[email protected]73eb2602012-02-09 19:50:556318 // |page_title_when_no_navigation_entry_| will be used for page title.
[email protected]987fc3a2011-05-26 14:18:096319 if (entry) {
[email protected]36fc0392011-12-25 03:59:516320 if (final_title == entry->GetTitle())
afakhry6f0c1ec22016-07-14 13:55:136321 return; // Nothing changed, don't bother.
[email protected]420ae012009-04-24 05:16:326322
[email protected]36fc0392011-12-25 03:59:516323 entry->SetTitle(final_title);
Avi Drissman93002212017-09-27 03:20:526324
6325 // The title for display may differ from the title just set; grab it.
6326 final_title = entry->GetTitleForDisplay();
[email protected]987fc3a2011-05-26 14:18:096327 } else {
6328 if (page_title_when_no_navigation_entry_ == final_title)
afakhry6f0c1ec22016-07-14 13:55:136329 return; // Nothing changed, don't bother.
[email protected]987fc3a2011-05-26 14:18:096330
6331 page_title_when_no_navigation_entry_ = final_title;
6332 }
[email protected]420ae012009-04-24 05:16:326333
[email protected]420ae012009-04-24 05:16:326334 // Lastly, set the title for the view.
[email protected]790e2fd2011-09-21 20:28:236335 view_->SetPageTitle(final_title);
[email protected]420ae012009-04-24 05:16:326336
Alexander Timin90c20c32020-08-12 15:28:326337 observers_.ForEachObserver(
6338 [&](WebContentsObserver* observer) { observer->TitleWasSet(entry); });
afakhry6f0c1ec22016-07-14 13:55:136339 // Broadcast notifications when the UI should be updated.
6340 if (entry == controller_.GetEntryAtOffset(0))
6341 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE);
[email protected]420ae012009-04-24 05:16:326342}
6343
fdegansa696e5112015-04-17 01:57:596344void WebContentsImpl::SendChangeLoadProgress() {
Alexander Timin5fdeff22020-09-08 09:20:376345 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SendChangeLoadProgress",
6346 "load_progress", frame_tree_.load_progress());
[email protected]960b0372014-05-19 18:01:006347 loading_last_progress_update_ = base::TimeTicks::Now();
Alexander Timin90c20c32020-08-12 15:28:326348 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6349 observer->LoadProgressChanged(frame_tree_.load_progress());
6350 });
[email protected]960b0372014-05-19 18:01:006351}
6352
6353void WebContentsImpl::ResetLoadProgressState() {
Alexander Timin5fdeff22020-09-08 09:20:376354 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ResetLoadProgressState");
fdegans1d16355162015-03-26 11:58:346355 frame_tree_.ResetLoadProgress();
[email protected]960b0372014-05-19 18:01:006356 loading_weak_factory_.InvalidateWeakPtrs();
6357 loading_last_progress_update_ = base::TimeTicks();
6358}
6359
clamy44e84ce2016-02-22 15:38:256360// Notifies the RenderWidgetHost instance about the fact that the page is
6361// loading, or done loading.
6362void WebContentsImpl::LoadingStateChanged(bool to_different_document,
clamy44e84ce2016-02-22 15:38:256363 LoadNotificationDetails* details) {
Nate Chapin22ea6592019-03-05 22:29:026364 if (is_being_destroyed_)
6365 return;
clamy44e84ce2016-02-22 15:38:256366
6367 bool is_loading = IsLoading();
6368
Alexander Timin5fdeff22020-09-08 09:20:376369 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::LoadingStateChanged",
6370 "is_loading", is_loading);
6371
clamy44e84ce2016-02-22 15:38:256372 if (!is_loading) {
6373 load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
6374 base::string16());
6375 load_state_host_.clear();
6376 upload_size_ = 0;
6377 upload_position_ = 0;
6378 }
6379
6380 GetRenderManager()->SetIsLoading(is_loading);
6381
6382 waiting_for_response_ = is_loading;
6383 is_load_to_different_document_ = to_different_document;
6384
6385 if (delegate_)
6386 delegate_->LoadingStateChanged(this, to_different_document);
6387 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD);
6388
6389 std::string url = (details ? details->url.possibly_invalid_spec() : "NULL");
6390 if (is_loading) {
6391 TRACE_EVENT_ASYNC_BEGIN2("browser,navigation", "WebContentsImpl Loading",
6392 this, "URL", url, "Main FrameTreeNode id",
6393 GetFrameTree()->root()->frame_tree_node_id());
Alexander Timin90c20c32020-08-12 15:28:326394 observers_.ForEachObserver(
6395 [&](WebContentsObserver* observer) { observer->DidStartLoading(); });
clamy44e84ce2016-02-22 15:38:256396 } else {
6397 TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
6398 this, "URL", url);
Alexander Timin90c20c32020-08-12 15:28:326399 observers_.ForEachObserver(
6400 [&](WebContentsObserver* observer) { observer->DidStopLoading(); });
clamy44e84ce2016-02-22 15:38:256401 }
6402
6403 // TODO(avi): Remove. http://crbug.com/170921
6404 int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP;
6405 NotificationDetails det = NotificationService::NoDetails();
6406 if (details)
6407 det = Details<LoadNotificationDetails>(details);
6408 NotificationService::current()->Notify(
6409 type, Source<NavigationController>(&controller_), det);
6410}
6411
danakja0bce4c952020-05-12 20:40:286412void WebContentsImpl::NotifyViewSwapped(RenderViewHost* old_view,
6413 RenderViewHost* new_view) {
Alexander Timin5fdeff22020-09-08 09:20:376414 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::NotifyViewSwapped",
6415 "old_view", old_view, "new_view", new_view);
danakja0bce4c952020-05-12 20:40:286416 DCHECK_NE(old_view, new_view);
[email protected]420ae012009-04-24 05:16:326417 // After sending out a swap notification, we need to send a disconnect
6418 // notification so that clients that pick up a pointer to |this| can NULL the
6419 // pointer. See Bug 1230284.
6420 notify_disconnection_ = true;
Alexander Timin90c20c32020-08-12 15:28:326421 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6422 observer->RenderViewHostChanged(old_view, new_view);
6423 });
danakja0bce4c952020-05-12 20:40:286424 view_->RenderViewHostChanged(old_view, new_view);
Jinsuk Kimdc5284c22018-07-11 02:22:066425
Lucas Furukawa Gadanif9ea4fc2018-08-03 23:57:136426 // If this is an inner WebContents that has swapped views, we need to reattach
6427 // it to its outer WebContents.
6428 if (node_.outer_web_contents())
6429 ReattachToOuterWebContentsFrame();
6430
[email protected]7a846df2012-09-20 19:17:396431 // Ensure that the associated embedder gets cleared after a RenderViewHost
6432 // gets swapped, so we don't reuse the same embedder next time a
6433 // RenderViewHost is attached to this WebContents.
6434 RemoveBrowserPluginEmbedder();
[email protected]420ae012009-04-24 05:16:326435}
6436
danakja0bce4c952020-05-12 20:40:286437void WebContentsImpl::NotifyFrameSwapped(RenderFrameHost* old_frame,
6438 RenderFrameHost* new_frame,
Jinsuk Kim895b2c52018-07-03 06:49:166439 bool is_main_frame) {
Alexander Timin5fdeff22020-09-08 09:20:376440 TRACE_EVENT2("content", "WebContentsImpl::NotifyFrameSwapped", "old_frame",
6441 base::trace_event::ToTracedValue(old_frame), "new_frame",
6442 base::trace_event::ToTracedValue(new_frame));
Bo Liu168c8642017-08-28 18:26:026443#if defined(OS_ANDROID)
danakja0bce4c952020-05-12 20:40:286444 // Copy importance from |old_frame| if |new_frame| is a main frame.
6445 if (old_frame && !new_frame->GetParent()) {
6446 RenderWidgetHostImpl* old_widget =
6447 static_cast<RenderFrameHostImpl*>(old_frame)->GetRenderWidgetHost();
6448 RenderWidgetHostImpl* new_widget =
6449 static_cast<RenderFrameHostImpl*>(new_frame)->GetRenderWidgetHost();
6450 new_widget->SetImportance(old_widget->importance());
Bo Liu7c6779e92017-08-16 02:02:286451 }
Bo Liu168c8642017-08-28 18:26:026452#endif
Alexander Timin90c20c32020-08-12 15:28:326453 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6454 observer->RenderFrameHostChanged(old_frame, new_frame);
6455 });
[email protected]02d7b6e2014-06-24 21:01:506456}
6457
[email protected]da7a7182013-09-06 08:11:116458// TODO(avi): Remove this entire function because this notification is already
6459// covered by two observer functions. http://crbug.com/170921
[email protected]b172aee2012-04-10 17:05:266460void WebContentsImpl::NotifyDisconnected() {
Alexander Timin5fdeff22020-09-08 09:20:376461 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::NotifyDisconnected");
[email protected]420ae012009-04-24 05:16:326462 if (!notify_disconnection_)
6463 return;
6464
6465 notify_disconnection_ = false;
[email protected]8ff00d72012-10-23 19:12:216466 NotificationService::current()->Notify(
6467 NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
6468 Source<WebContents>(this),
6469 NotificationService::NoDetails());
[email protected]420ae012009-04-24 05:16:326470}
6471
[email protected]cbb1ef592013-06-05 19:49:466472void WebContentsImpl::NotifyNavigationEntryCommitted(
6473 const LoadCommittedDetails& load_details) {
Alexander Timin5fdeff22020-09-08 09:20:376474 OPTIONAL_TRACE_EVENT0("content",
6475 "WebContentsImpl::NotifyNavigationEntryCommitted");
Alexander Timin90c20c32020-08-12 15:28:326476 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6477 observer->NavigationEntryCommitted(load_details);
6478 });
[email protected]cbb1ef592013-06-05 19:49:466479}
6480
Sam McNally5c087a32017-08-25 01:46:146481void WebContentsImpl::NotifyNavigationEntryChanged(
6482 const EntryChangedDetails& change_details) {
Alexander Timin5fdeff22020-09-08 09:20:376483 OPTIONAL_TRACE_EVENT0("content",
6484 "WebContentsImpl::NotifyNavigationEntryChanged");
Alexander Timin90c20c32020-08-12 15:28:326485 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6486 observer->NavigationEntryChanged(change_details);
6487 });
Sam McNally5c087a32017-08-25 01:46:146488}
6489
6490void WebContentsImpl::NotifyNavigationListPruned(
6491 const PrunedDetails& pruned_details) {
Alexander Timin5fdeff22020-09-08 09:20:376492 OPTIONAL_TRACE_EVENT0("content",
6493 "WebContentsImpl::NotifyNavigationListPruned");
Alexander Timin90c20c32020-08-12 15:28:326494 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6495 observer->NavigationListPruned(pruned_details);
6496 });
Sam McNally5c087a32017-08-25 01:46:146497}
6498
Christian Dullweber1af31e62018-02-22 11:49:486499void WebContentsImpl::NotifyNavigationEntriesDeleted() {
Alexander Timin5fdeff22020-09-08 09:20:376500 OPTIONAL_TRACE_EVENT0("content",
6501 "WebContentsImpl::NotifyNavigationEntriesDeleted");
Alexander Timin90c20c32020-08-12 15:28:326502 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6503 observer->NavigationEntriesDeleted();
6504 });
Christian Dullweber1af31e62018-02-22 11:49:486505}
6506
rockotf62002a2016-09-15 00:08:596507void WebContentsImpl::OnAssociatedInterfaceRequest(
6508 RenderFrameHost* render_frame_host,
6509 const std::string& interface_name,
6510 mojo::ScopedInterfaceEndpointHandle handle) {
Alexander Timin5fdeff22020-09-08 09:20:376511 OPTIONAL_TRACE_EVENT2(
6512 "content", "WebContentsImpl::OnAssociatedInterfaceRequest",
6513 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host),
6514 "interface_name", interface_name);
Julie Jeongeun Kim7d0986172019-12-04 03:17:256515 auto it = receiver_sets_.find(interface_name);
6516 if (it != receiver_sets_.end())
6517 it->second->OnReceiverForFrame(render_frame_host, std::move(handle));
rockotf62002a2016-09-15 00:08:596518}
6519
Ben Goodger9e24929e2017-07-21 03:13:406520void WebContentsImpl::OnInterfaceRequest(
6521 RenderFrameHost* render_frame_host,
6522 const std::string& interface_name,
6523 mojo::ScopedMessagePipeHandle* interface_pipe) {
Alexander Timin5fdeff22020-09-08 09:20:376524 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnInterfaceRequest",
6525 "render_frame_host",
6526 base::trace_event::ToTracedValue(render_frame_host),
6527 "interface_name", interface_name);
Alexander Timin90c20c32020-08-12 15:28:326528 for (auto& observer : observers_.observer_list()) {
Ben Goodger9e24929e2017-07-21 03:13:406529 observer.OnInterfaceRequestFromFrame(render_frame_host, interface_name,
6530 interface_pipe);
6531 if (!interface_pipe->is_valid())
6532 break;
6533 }
6534}
6535
Varun Khaneja5da94302019-06-25 04:48:106536void WebContentsImpl::OnDidBlockNavigation(
6537 const GURL& blocked_url,
6538 const GURL& initiator_url,
Abhijeet Kandalkarde7348e2020-01-13 06:06:546539 blink::mojom::NavigationBlockedReason reason) {
Alexander Timin5fdeff22020-09-08 09:20:376540 OPTIONAL_TRACE_EVENT1(
6541 "content", "WebContentsImpl::OnDidBlockNavigation", "details",
6542 base::trace_event::TracedValue::Build(
6543 {{"blocked_url", base::trace_event::ValueToString(blocked_url)},
6544 {"initiator_url", base::trace_event::ValueToString(initiator_url)},
6545 {"reason", base::trace_event::ValueToString(reason)}}));
Nicolas Dossou-gbetebcab2472017-09-09 12:28:406546 if (delegate_)
Varun Khaneja5da94302019-06-25 04:48:106547 delegate_->OnDidBlockNavigation(this, blocked_url, initiator_url, reason);
Nicolas Dossou-gbetebcab2472017-09-09 12:28:406548}
6549
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416550const GURL& WebContentsImpl::GetMainFrameLastCommittedURL() {
[email protected]c31a84802014-04-03 15:55:496551 return GetLastCommittedURL();
6552}
6553
[email protected]b849847b2013-12-10 21:57:586554void WebContentsImpl::RenderFrameCreated(RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:376555 TRACE_EVENT1("content", "WebContentsImpl::RenderFrameCreated",
6556 "render_frame_host", render_frame_host);
Alexander Timin90c20c32020-08-12 15:28:326557 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6558 observer->RenderFrameCreated(render_frame_host);
6559 });
dmazzonif8a31042016-12-03 00:52:136560 UpdateAccessibilityModeOnFrame(render_frame_host);
clamy91b7abf2016-03-24 15:17:456561
Becca Hughesd11d6502018-07-31 17:01:286562 if (display_cutout_host_impl_)
6563 display_cutout_host_impl_->RenderFrameCreated(render_frame_host);
6564
clamy91b7abf2016-03-24 15:17:456565 if (!render_frame_host->IsRenderFrameLive() || render_frame_host->GetParent())
6566 return;
6567
6568 NavigationEntry* entry = controller_.GetPendingEntry();
6569 if (entry && entry->IsViewSourceMode()) {
6570 // Put the renderer in view source mode.
Dave Tapuska3c05e1c2019-11-27 18:34:186571 static_cast<RenderFrameHostImpl*>(render_frame_host)
6572 ->GetAssociatedLocalFrame()
6573 ->EnableViewSourceMode();
clamy91b7abf2016-03-24 15:17:456574 }
[email protected]b849847b2013-12-10 21:57:586575}
6576
6577void WebContentsImpl::RenderFrameDeleted(RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:376578 TRACE_EVENT1("content", "WebContentsImpl::RenderFrameDeleted",
6579 "render_frame_host",
6580 base::trace_event::ToTracedValue(render_frame_host));
yilkal172da772019-11-06 22:49:076581 if (IsBeingDestroyed() && !render_frame_host->GetParent() &&
6582 first_navigation_completed_ &&
Hajime Hoshibbc509c2020-04-06 08:55:086583 !render_frame_host->IsInBackForwardCache()) {
yilkal796e89e2019-10-02 23:58:286584 // Main frame has been deleted because WebContents is being destroyed.
Rakina Zata Amni74627df2019-10-15 02:03:176585 // Note that we aren't recording this here when the main frame is in the
6586 // back-forward cache because that means we've actually already navigated
6587 // away from it (and we got to this point because the WebContents is
yilkal172da772019-11-06 22:49:076588 // deleted), which means |max_loaded_frame_count_| is already overwritten.
6589 // The |max_loaded_frame_count_| value will instead be recorded from within
6590 // |WebContentsImpl::DidFinishNavigation()|.
6591 RecordMaxFrameCountUMA(max_loaded_frame_count_);
yilkal796e89e2019-10-02 23:58:286592 }
6593
Alexander Timin90c20c32020-08-12 15:28:326594 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6595 observer->RenderFrameDeleted(render_frame_host);
6596 });
zqzhang7b6f4f02016-12-07 22:10:226597#if BUILDFLAG(ENABLE_PLUGINS)
6598 pepper_playback_observer_->RenderFrameDeleted(render_frame_host);
6599#endif
Becca Hughesfd5d8f892018-06-14 18:23:366600
Becca Hughesd11d6502018-07-31 17:01:286601 if (display_cutout_host_impl_)
6602 display_cutout_host_impl_->RenderFrameDeleted(render_frame_host);
6603
Becca Hughesfd5d8f892018-06-14 18:23:366604 // Remove any fullscreen state that the frame has stored.
6605 FullscreenStateChanged(render_frame_host, false /* is_fullscreen */);
[email protected]b849847b2013-12-10 21:57:586606}
6607
[email protected]a09d53ce2014-01-31 00:46:426608void WebContentsImpl::ShowContextMenu(RenderFrameHost* render_frame_host,
6609 const ContextMenuParams& params) {
Alexander Timin5fdeff22020-09-08 09:20:376610 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ShowContextMenu",
6611 "render_frame_host",
6612 base::trace_event::ToTracedValue(render_frame_host));
avie9fd8722017-04-10 16:17:586613 // If a renderer fires off a second command to show a context menu before the
6614 // first context menu is closed, just ignore it. https://crbug.com/707534
ekaramadf6750aa2017-06-06 18:29:426615 if (showing_context_menu_)
avie9fd8722017-04-10 16:17:586616 return;
6617
[email protected]077e704b2014-05-23 19:24:106618 ContextMenuParams context_menu_params(params);
[email protected]a09d53ce2014-01-31 00:46:426619 // Allow WebContentsDelegates to handle the context menu operation first.
Joel Klinghed0ea22ea2019-02-20 22:04:226620 if (delegate_ &&
6621 delegate_->HandleContextMenu(render_frame_host, context_menu_params))
[email protected]a09d53ce2014-01-31 00:46:426622 return;
6623
[email protected]077e704b2014-05-23 19:24:106624 render_view_host_delegate_view_->ShowContextMenu(render_frame_host,
6625 context_menu_params);
[email protected]a09d53ce2014-01-31 00:46:426626}
6627
Avi Drissman4891b852018-09-25 18:12:586628namespace {
6629// Normalizes the line endings: \r\n -> \n, lone \r -> \n.
6630base::string16 NormalizeLineBreaks(const base::string16& source) {
6631 static const base::NoDestructor<base::string16> kReturnNewline(
6632 base::ASCIIToUTF16("\r\n"));
6633 static const base::NoDestructor<base::string16> kReturn(
6634 base::ASCIIToUTF16("\r"));
6635 static const base::NoDestructor<base::string16> kNewline(
6636 base::ASCIIToUTF16("\n"));
6637
6638 std::vector<base::StringPiece16> pieces;
6639
6640 for (const auto& rn_line : base::SplitStringPieceUsingSubstr(
6641 source, *kReturnNewline, base::KEEP_WHITESPACE,
6642 base::SPLIT_WANT_ALL)) {
6643 auto r_lines = base::SplitStringPieceUsingSubstr(
6644 rn_line, *kReturn, base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
6645 std::move(std::begin(r_lines), std::end(r_lines),
6646 std::back_inserter(pieces));
6647 }
6648
6649 return base::JoinString(pieces, *kNewline);
6650}
6651} // namespace
6652
Dave Tapuskacdf545cc2020-01-23 18:38:526653void WebContentsImpl::RunJavaScriptDialog(
6654 RenderFrameHost* render_frame_host,
6655 const base::string16& message,
6656 const base::string16& default_prompt,
6657 JavaScriptDialogType dialog_type,
6658 JavaScriptDialogCallback response_callback) {
Alexander Timin5fdeff22020-09-08 09:20:376659 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RunJavaScriptDialog",
6660 "render_frame_host",
6661 base::trace_event::ToTracedValue(render_frame_host));
Avi Drissman2ccbb402018-03-20 21:11:366662 // Ensure that if showing a dialog is the first thing that a page does, that
6663 // the contents of the previous page aren't shown behind it. This is required
6664 // because showing a dialog freezes the renderer, so no frames will be coming
6665 // from it. https://crbug.com/823353
6666 auto* render_widget_host_impl =
6667 static_cast<RenderFrameHostImpl*>(render_frame_host)
6668 ->GetRenderWidgetHost();
6669 if (render_widget_host_impl)
6670 render_widget_host_impl->ForceFirstFrameAfterNavigationTimeout();
6671
avi0720b02e2017-06-13 03:22:136672 // Running a dialog causes an exit to webpage-initiated fullscreen.
6673 // http://crbug.com/728276
Avi Drissman1a55a9d62020-03-10 18:56:456674 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
avi0720b02e2017-06-13 03:22:136675
Avi Drissman1a55a9d62020-03-10 18:56:456676 auto callback =
6677 base::BindOnce(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
6678 render_frame_host->GetProcess()->GetID(),
6679 render_frame_host->GetRoutingID(),
6680 std::move(response_callback), std::move(fullscreen_block));
Pavel Feldman3c1842b2017-08-02 05:00:166681
Pavel Feldman3c1842b2017-08-02 05:00:166682 std::vector<protocol::PageHandler*> page_handlers =
6683 protocol::PageHandler::EnabledForWebContents(this);
6684
Pavel Feldmanfab3cb62017-10-05 01:02:016685 if (delegate_)
6686 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
6687
Charlie Reis96077362019-07-04 00:34:046688 // While a JS message dialog is showing, defer commits in this WebContents.
6689 javascript_dialog_navigation_deferrer_ =
6690 std::make_unique<JavaScriptDialogNavigationDeferrer>();
6691
Carlos IL07f282f2020-05-15 22:58:296692 // Suppress JavaScript dialogs when requested.
6693 bool should_suppress = delegate_ && delegate_->ShouldSuppressDialogs(this);
Pavel Feldman1c587bc52018-04-04 21:16:056694 bool has_non_devtools_handlers = delegate_ && dialog_manager_;
6695 bool has_handlers = page_handlers.size() || has_non_devtools_handlers;
Pavel Feldmanfab3cb62017-10-05 01:02:016696 bool suppress_this_message = should_suppress || !has_handlers;
6697
6698 if (suppress_this_message) {
Avi Drissmane04d3992017-10-05 15:11:366699 std::move(callback).Run(true, false, base::string16());
Pavel Feldman3c1842b2017-08-02 05:00:166700 return;
6701 }
6702
6703 scoped_refptr<CloseDialogCallbackWrapper> wrapper =
Avi Drissmane04d3992017-10-05 15:11:366704 new CloseDialogCallbackWrapper(std::move(callback));
Pavel Feldman3c1842b2017-08-02 05:00:166705
6706 is_showing_javascript_dialog_ = true;
6707
Avi Drissman4891b852018-09-25 18:12:586708 base::string16 normalized_message = NormalizeLineBreaks(message);
6709
Pavel Feldman3c1842b2017-08-02 05:00:166710 for (auto* handler : page_handlers) {
Avi Drissmane04d3992017-10-05 15:11:366711 handler->DidRunJavaScriptDialog(
Avi Drissman4891b852018-09-25 18:12:586712 render_frame_host->GetLastCommittedURL(), normalized_message,
6713 default_prompt, dialog_type, has_non_devtools_handlers,
Avi Drissmane04d3992017-10-05 15:11:366714 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
Pavel Feldman3c1842b2017-08-02 05:00:166715 }
6716
6717 if (dialog_manager_) {
[email protected]87de04b02014-04-08 22:14:496718 dialog_manager_->RunJavaScriptDialog(
Avi Drissman4891b852018-09-25 18:12:586719 this, render_frame_host, dialog_type, normalized_message,
6720 default_prompt,
Avi Drissmane04d3992017-10-05 15:11:366721 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false),
6722 &suppress_this_message);
[email protected]87de04b02014-04-08 22:14:496723 }
6724
6725 if (suppress_this_message) {
6726 // If we are suppressing messages, just reply as if the user immediately
6727 // pressed "Cancel", passing true to |dialog_was_suppressed|.
Avi Drissmane04d3992017-10-05 15:11:366728 wrapper->Run(true, false, base::string16());
[email protected]87de04b02014-04-08 22:14:496729 }
[email protected]87de04b02014-04-08 22:14:496730}
6731
6732void WebContentsImpl::RunBeforeUnloadConfirm(
[email protected]39f2f9252014-05-03 00:54:016733 RenderFrameHost* render_frame_host,
[email protected]87de04b02014-04-08 22:14:496734 bool is_reload,
Dave Tapuskacdf545cc2020-01-23 18:38:526735 JavaScriptDialogCallback response_callback) {
Alexander Timin5fdeff22020-09-08 09:20:376736 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RunBeforeUnloadConfirm",
6737 "render_frame_host",
6738 base::trace_event::ToTracedValue(render_frame_host),
6739 "is_reload", is_reload);
Avi Drissman2ccbb402018-03-20 21:11:366740 // Ensure that if showing a dialog is the first thing that a page does, that
6741 // the contents of the previous page aren't shown behind it. This is required
6742 // because showing a dialog freezes the renderer, so no frames will be coming
6743 // from it. https://crbug.com/823353
6744 auto* render_widget_host_impl =
6745 static_cast<RenderFrameHostImpl*>(render_frame_host)
6746 ->GetRenderWidgetHost();
6747 if (render_widget_host_impl)
6748 render_widget_host_impl->ForceFirstFrameAfterNavigationTimeout();
6749
avi0720b02e2017-06-13 03:22:136750 // Running a dialog causes an exit to webpage-initiated fullscreen.
6751 // http://crbug.com/728276
Avi Drissman1a55a9d62020-03-10 18:56:456752 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
avi0720b02e2017-06-13 03:22:136753
[email protected]39f2f9252014-05-03 00:54:016754 RenderFrameHostImpl* rfhi =
6755 static_cast<RenderFrameHostImpl*>(render_frame_host);
[email protected]87de04b02014-04-08 22:14:496756 if (delegate_)
6757 delegate_->WillRunBeforeUnloadConfirm();
6758
Avi Drissman1a55a9d62020-03-10 18:56:456759 auto callback =
6760 base::BindOnce(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
6761 render_frame_host->GetProcess()->GetID(),
6762 render_frame_host->GetRoutingID(),
6763 std::move(response_callback), std::move(fullscreen_block));
Pavel Feldman3c1842b2017-08-02 05:00:166764
Pavel Feldman3c1842b2017-08-02 05:00:166765 std::vector<protocol::PageHandler*> page_handlers =
6766 protocol::PageHandler::EnabledForWebContents(this);
6767
Pavel Feldmanfab3cb62017-10-05 01:02:016768 if (delegate_)
6769 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
6770
Charlie Reis96077362019-07-04 00:34:046771 // While a JS beforeunload dialog is showing, defer commits in this
6772 // WebContents.
6773 javascript_dialog_navigation_deferrer_ =
6774 std::make_unique<JavaScriptDialogNavigationDeferrer>();
6775
Sreeja Kamishettyf352e302020-06-10 13:21:246776 bool should_suppress = !rfhi->IsCurrent() ||
Tarun Bansalc209b742019-12-24 06:53:256777 (delegate_ && delegate_->ShouldSuppressDialogs(this));
Pavel Feldman1c587bc52018-04-04 21:16:056778 bool has_non_devtools_handlers = delegate_ && dialog_manager_;
6779 bool has_handlers = page_handlers.size() || has_non_devtools_handlers;
Pavel Feldmanfab3cb62017-10-05 01:02:016780 if (should_suppress || !has_handlers) {
Avi Drissmane04d3992017-10-05 15:11:366781 std::move(callback).Run(false, true, base::string16());
[email protected]87de04b02014-04-08 22:14:496782 return;
6783 }
6784
6785 is_showing_before_unload_dialog_ = true;
Pavel Feldman3c1842b2017-08-02 05:00:166786
6787 scoped_refptr<CloseDialogCallbackWrapper> wrapper =
Avi Drissmane04d3992017-10-05 15:11:366788 new CloseDialogCallbackWrapper(std::move(callback));
Pavel Feldman3c1842b2017-08-02 05:00:166789
6790 GURL frame_url = rfhi->GetLastCommittedURL();
6791 for (auto* handler : page_handlers) {
Avi Drissmane04d3992017-10-05 15:11:366792 handler->DidRunBeforeUnloadConfirm(
Pavel Feldman1c587bc52018-04-04 21:16:056793 frame_url, has_non_devtools_handlers,
Avi Drissmane04d3992017-10-05 15:11:366794 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
Pavel Feldman3c1842b2017-08-02 05:00:166795 }
6796
6797 if (dialog_manager_) {
Avi Drissmane04d3992017-10-05 15:11:366798 dialog_manager_->RunBeforeUnloadDialog(
Avi Drissmanff9ed752017-11-28 21:18:126799 this, render_frame_host, is_reload,
Avi Drissmane04d3992017-10-05 15:11:366800 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
Pavel Feldman3c1842b2017-08-02 05:00:166801 }
[email protected]87de04b02014-04-08 22:14:496802}
6803
Kent Tamurac260c9a2018-09-14 09:10:566804void WebContentsImpl::RunFileChooser(
6805 RenderFrameHost* render_frame_host,
Kent Tamura3abb32d2020-07-02 00:23:016806 scoped_refptr<FileChooserImpl::FileSelectListenerImpl> listener,
Kent Tamurac260c9a2018-09-14 09:10:566807 const blink::mojom::FileChooserParams& params) {
Alexander Timin5fdeff22020-09-08 09:20:376808 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RunFileChooser",
6809 "render_frame_host",
6810 base::trace_event::ToTracedValue(render_frame_host));
Avi Drissman3d41e7712018-08-27 21:18:086811 // Any explicit focusing of another window while this WebContents is in
6812 // fullscreen can be used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:456813 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
6814 listener->SetFullscreenBlock(std::move(fullscreen_block));
Avi Drissman3d41e7712018-08-27 21:18:086815
naskoada75b22016-06-11 16:09:466816 if (delegate_)
Kent Tamura512a27e2018-10-04 00:49:326817 delegate_->RunFileChooser(render_frame_host, std::move(listener), params);
6818 else
6819 listener->FileSelectionCanceled();
naskoada75b22016-06-11 16:09:466820}
6821
[email protected]a86c0e962013-12-17 17:10:396822WebContents* WebContentsImpl::GetAsWebContents() {
6823 return this;
6824}
6825
mcnee336ea2c2017-05-23 22:50:596826#if !defined(OS_ANDROID)
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416827double WebContentsImpl::GetPendingPageZoomLevel() {
wjmaclean64951902016-04-29 20:59:126828 NavigationEntry* pending_entry = GetController().GetPendingEntry();
6829 if (!pending_entry)
6830 return HostZoomMap::GetZoomLevel(this);
6831
6832 GURL url = pending_entry->GetURL();
6833 return HostZoomMap::GetForWebContents(this)->GetZoomLevelForHostAndScheme(
6834 url.scheme(), net::GetHostOrSpecFromURL(url));
6835}
mcnee336ea2c2017-05-23 22:50:596836#endif // !defined(OS_ANDROID)
wjmaclean64951902016-04-29 20:59:126837
qinmin72e8bd02016-10-21 19:35:376838bool WebContentsImpl::HideDownloadUI() const {
6839 return is_overlay_content_;
6840}
6841
mlamouri5cd9ae82017-02-18 11:05:096842bool WebContentsImpl::HasPersistentVideo() const {
6843 return has_persistent_video_;
6844}
6845
Ian Vollick5d5c37f2019-06-19 22:50:576846bool WebContentsImpl::IsSpatialNavigationDisabled() const {
6847 return is_spatial_navigation_disabled_;
6848}
6849
Albert J. Wong65fe64d2019-09-20 02:48:146850RenderFrameHostImpl* WebContentsImpl::GetPendingMainFrame() {
clamy610c63b32017-12-22 15:05:186851 return GetRenderManager()->speculative_frame_host();
Alex Moshchuk27caae82017-09-11 23:11:186852}
6853
mlamourie52c1b542017-02-23 14:57:506854bool WebContentsImpl::HasActiveEffectivelyFullscreenVideo() const {
6855 return media_web_contents_observer_->HasActiveEffectivelyFullscreenVideo();
6856}
6857
François Beaufortad6c5232018-02-26 11:00:446858bool WebContentsImpl::IsPictureInPictureAllowedForFullscreenVideo() const {
6859 return media_web_contents_observer_
6860 ->IsPictureInPictureAllowedForFullscreenVideo();
6861}
6862
ekaramada110f642016-12-21 19:47:286863bool WebContentsImpl::IsFocusedElementEditable() {
6864 RenderFrameHostImpl* frame = GetFocusedFrame();
6865 return frame && frame->has_focused_editable_element();
6866}
6867
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416868bool WebContentsImpl::IsShowingContextMenu() {
ekaramadf6750aa2017-06-06 18:29:426869 return showing_context_menu_;
6870}
6871
6872void WebContentsImpl::SetShowingContextMenu(bool showing) {
Alexander Timin5fdeff22020-09-08 09:20:376873 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetShowingContextMenu",
6874 "showing", showing);
6875
ekaramadf6750aa2017-06-06 18:29:426876 DCHECK_NE(showing_context_menu_, showing);
6877 showing_context_menu_ = showing;
6878
6879 if (auto* view = GetRenderWidgetHostView()) {
6880 // Notify the main frame's RWHV to run the platform-specific code, if any.
6881 static_cast<RenderWidgetHostViewBase*>(view)->SetShowingContextMenu(
6882 showing);
6883 }
6884}
6885
ekaramada110f642016-12-21 19:47:286886void WebContentsImpl::ClearFocusedElement() {
Alexander Timin5fdeff22020-09-08 09:20:376887 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ClearFocusedElement");
ekaramada110f642016-12-21 19:47:286888 if (auto* frame = GetFocusedFrame())
6889 frame->ClearFocusedElement();
6890}
6891
danakj77eb7e82020-01-09 19:38:466892bool WebContentsImpl::IsNeverComposited() {
[email protected]7912e822014-04-16 02:37:036893 if (!delegate_)
6894 return false;
danakj77eb7e82020-01-09 19:38:466895 return delegate_->IsNeverComposited(this);
[email protected]7912e822014-04-16 02:37:036896}
6897
[email protected]5a3bdf52012-05-24 15:12:576898RenderViewHostDelegateView* WebContentsImpl::GetDelegateView() {
6899 return render_view_host_delegate_view_;
[email protected]420ae012009-04-24 05:16:326900}
6901
Peter Marshall2dc74e92020-07-29 20:02:306902blink::mojom::RendererPreferences WebContentsImpl::GetRendererPrefs() const {
[email protected]840b1512009-07-21 16:53:466903 return renderer_preferences_;
[email protected]80d96fa2009-06-10 22:34:516904}
6905
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166906RenderFrameHostImpl* WebContentsImpl::GetOuterWebContentsFrame() {
6907 if (GetOuterDelegateFrameTreeNodeId() ==
6908 FrameTreeNode::kFrameTreeNodeInvalidId) {
6909 return nullptr;
6910 }
6911
6912 FrameTreeNode* outer_node =
6913 FrameTreeNode::GloballyFindByID(GetOuterDelegateFrameTreeNodeId());
6914 // The outer node should be in the outer WebContents.
6915 DCHECK_EQ(outer_node->frame_tree(), GetOuterWebContents()->GetFrameTree());
Alexander Timin381e7e182020-04-28 19:04:036916 return outer_node->parent();
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166917}
6918
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416919WebContentsImpl* WebContentsImpl::GetOuterWebContents() {
Lucas Furukawa Gadani105de1e812018-05-31 19:38:396920 return node_.outer_web_contents();
avallee0206f782016-07-28 18:55:336921}
6922
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166923std::vector<WebContents*> WebContentsImpl::GetInnerWebContents() {
6924 std::vector<WebContents*> all_inner_contents;
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166925 const auto& inner_contents = node_.GetInnerWebContents();
6926 all_inner_contents.insert(all_inner_contents.end(), inner_contents.begin(),
6927 inner_contents.end());
6928 return all_inner_contents;
6929}
6930
Jeremy Roman7e70bf92020-01-07 23:23:586931WebContentsImpl* WebContentsImpl::GetResponsibleWebContents() {
6932 // Iteratively ask delegates which other contents is responsible until a fixed
6933 // point is found.
6934 WebContentsImpl* contents = this;
6935 while (WebContentsDelegate* delegate = contents->GetDelegate()) {
6936 auto* responsible_contents = static_cast<WebContentsImpl*>(
6937 delegate->GetResponsibleWebContents(contents));
6938 if (responsible_contents == contents)
6939 break;
6940 contents = responsible_contents;
6941 }
6942 return contents;
6943}
6944
avallee0206f782016-07-28 18:55:336945WebContentsImpl* WebContentsImpl::GetFocusedWebContents() {
lfg601233692017-03-06 22:45:446946 return GetOutermostWebContents()->node_.focused_web_contents();
avallee0206f782016-07-28 18:55:336947}
6948
avallee9993fca2016-11-17 06:16:506949bool WebContentsImpl::ContainsOrIsFocusedWebContents() {
6950 for (WebContentsImpl* focused_contents = GetFocusedWebContents();
6951 focused_contents;
6952 focused_contents = focused_contents->GetOuterWebContents()) {
6953 if (focused_contents == this)
6954 return true;
6955 }
6956
6957 return false;
6958}
6959
W. James MacLean9437b5bf2019-12-06 17:33:446960void WebContentsImpl::RemoveBrowserPluginEmbedder() {
Alexander Timin5fdeff22020-09-08 09:20:376961 OPTIONAL_TRACE_EVENT0("content",
6962 "WebContentsImpl::RemoveBrowserPluginEmbedder");
W. James MacLean9437b5bf2019-12-06 17:33:446963 browser_plugin_embedder_.reset();
6964}
6965
avallee0206f782016-07-28 18:55:336966WebContentsImpl* WebContentsImpl::GetOutermostWebContents() {
6967 WebContentsImpl* root = this;
6968 while (root->GetOuterWebContents())
6969 root = root->GetOuterWebContents();
6970 return root;
6971}
6972
avalleed68cdd12017-06-21 22:07:276973void WebContentsImpl::FocusOuterAttachmentFrameChain() {
Alexander Timin5fdeff22020-09-08 09:20:376974 OPTIONAL_TRACE_EVENT0("content",
6975 "WebContentsImpl::FocusOuterAttachmentFrameChain");
avalleed68cdd12017-06-21 22:07:276976 WebContentsImpl* outer_contents = GetOuterWebContents();
6977 if (!outer_contents)
6978 return;
6979
6980 FrameTreeNode* outer_node =
6981 FrameTreeNode::GloballyFindByID(GetOuterDelegateFrameTreeNodeId());
6982 outer_contents->frame_tree_.SetFocusedFrame(outer_node, nullptr);
6983
6984 // For a browser initiated focus change, let embedding renderer know of the
6985 // change. Otherwise, if the currently focused element is just across a
6986 // process boundary in focus order, it will not be possible to move across
6987 // that boundary. This is because the target element will already be focused
6988 // (that renderer was not notified) and drop the event.
6989 if (GetRenderManager()->GetProxyToOuterDelegate())
6990 GetRenderManager()->GetProxyToOuterDelegate()->SetFocusedFrame();
6991
6992 outer_contents->FocusOuterAttachmentFrameChain();
6993}
6994
Sean Toppingbbc4a2bd2019-01-30 02:16:146995void WebContentsImpl::InnerWebContentsCreated(WebContents* inner_web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:376996 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::InnerWebContentsCreated");
Alexander Timin90c20c32020-08-12 15:28:326997 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6998 observer->InnerWebContentsCreated(inner_web_contents);
6999 });
Sean Toppingbbc4a2bd2019-01-30 02:16:147000}
7001
Jeremy Roman03ce13ce2020-05-29 22:16:577002void WebContentsImpl::InnerWebContentsAttached(
7003 WebContents* inner_web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:377004 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::InnerWebContentsDetached");
Jeremy Roman03ce13ce2020-05-29 22:16:577005 if (inner_web_contents->IsCurrentlyAudible())
7006 OnAudioStateChanged();
7007}
7008
7009void WebContentsImpl::InnerWebContentsDetached(
7010 WebContents* inner_web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:377011 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::InnerWebContentsCreated");
Jeremy Roman03ce13ce2020-05-29 22:16:577012 if (!is_being_destroyed_)
7013 OnAudioStateChanged();
7014}
7015
[email protected]b172aee2012-04-10 17:05:267016void WebContentsImpl::RenderViewCreated(RenderViewHost* render_view_host) {
Alexander Timin5fdeff22020-09-08 09:20:377017 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderViewCreated",
7018 "render_view_host", render_view_host);
[email protected]86f98a22013-03-20 14:35:007019 if (delegate_)
[email protected]e85165c642014-06-10 14:34:317020 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
[email protected]a6b73c62013-02-11 23:05:087021
[email protected]8ff00d72012-10-23 19:12:217022 NotificationService::current()->Notify(
7023 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
7024 Source<WebContents>(this),
7025 Details<RenderViewHost>(render_view_host));
[email protected]420ae012009-04-24 05:16:327026
Alexander Timin90c20c32020-08-12 15:28:327027 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7028 observer->RenderViewCreated(render_view_host);
7029 });
Joel Einbinder848001c2017-09-19 21:39:317030 if (delegate_)
7031 RenderFrameDevToolsAgentHost::WebContentsCreated(this);
[email protected]420ae012009-04-24 05:16:327032}
7033
[email protected]b172aee2012-04-10 17:05:267034void WebContentsImpl::RenderViewReady(RenderViewHost* rvh) {
Alexander Timin5fdeff22020-09-08 09:20:377035 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderViewReady",
7036 "render_view_host", rvh);
[email protected]151a63d2011-12-20 22:32:527037 if (rvh != GetRenderViewHost()) {
[email protected]420ae012009-04-24 05:16:327038 // Don't notify the world, since this came from a renderer in the
7039 // background.
7040 return;
7041 }
7042
dmazzoni62111452017-04-28 23:46:557043 RenderWidgetHostViewBase* rwhv =
7044 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
7045 if (rwhv)
7046 rwhv->SetMainFrameAXTreeID(GetMainFrame()->GetAXTreeID());
7047
[email protected]da7a7182013-09-06 08:11:117048 notify_disconnection_ = true;
[email protected]da7a7182013-09-06 08:11:117049
[email protected]be1f56ab2011-12-22 06:55:317050 bool was_crashed = IsCrashed();
[email protected]443b80e2010-12-14 00:42:237051 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING, 0);
[email protected]9d8a4642009-07-29 17:25:307052
7053 // Restore the focus to the tab (otherwise the focus will be on the top
7054 // window).
[email protected]484ae5912010-09-29 19:16:147055 if (was_crashed && !FocusLocationBarByDefault() &&
7056 (!delegate_ || delegate_->ShouldFocusPageAfterCrash())) {
[email protected]f3615f02013-02-26 06:09:067057 view_->Focus();
[email protected]484ae5912010-09-29 19:16:147058 }
[email protected]32ded2212011-11-10 18:51:437059
Alexander Timin90c20c32020-08-12 15:28:327060 observers_.ForEachObserver(
7061 [&](WebContentsObserver* observer) { observer->RenderViewReady(); });
Jinsuk Kim895b2c52018-07-03 06:49:167062 view_->RenderViewReady();
[email protected]420ae012009-04-24 05:16:327063}
7064
[email protected]ec6a7eb2013-04-22 17:34:227065void WebContentsImpl::RenderViewTerminated(RenderViewHost* rvh,
7066 base::TerminationStatus status,
7067 int error_code) {
Alexander Timin5fdeff22020-09-08 09:20:377068 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RenderViewTerminated",
7069 "render_view_host", rvh, "status",
7070 static_cast<int>(status));
[email protected]151a63d2011-12-20 22:32:527071 if (rvh != GetRenderViewHost()) {
[email protected]420ae012009-04-24 05:16:327072 // The pending page's RenderViewHost is gone.
7073 return;
7074 }
[email protected]2fcdcc32014-03-05 02:14:077075 // Ensure fullscreen mode is exited in the |delegate_| since a crashed
7076 // renderer may not have made a clean exit.
Avi Drissman97aef042020-06-30 21:04:487077 if (IsFullscreen())
bokanece34a82016-01-28 19:49:467078 ExitFullscreenMode(false);
[email protected]2fcdcc32014-03-05 02:14:077079
Jennifer Apacibleb4b972a2018-06-07 04:41:027080 // Ensure any video in Picture-in-Picture is exited in the |delegate_| since
7081 // a crashed renderer may not have made a clean exit.
7082 if (HasPictureInPictureVideo())
7083 ExitPictureInPicture();
7084
[email protected]698191dc2014-02-25 01:06:137085 // Cancel any visible dialogs so they are not left dangling over the sad tab.
creis89a0f782015-05-27 16:13:177086 CancelActiveAndPendingDialogs();
[email protected]698191dc2014-02-25 01:06:137087
dalecurtis3d1e1302017-02-20 22:33:257088 audio_stream_monitor_.RenderProcessGone(rvh->GetProcess()->GetID());
7089
[email protected]960b0372014-05-19 18:01:007090 // Reset the loading progress. TODO(avi): What does it mean to have a
7091 // "renderer crash" when there is more than one renderer process serving a
7092 // webpage? Once this function is called at a more granular frame level, we
7093 // probably will need to more granularly reset the state here.
7094 ResetLoadProgressState();
clamy44e84ce2016-02-22 15:38:257095 NotifyDisconnected();
7096 SetIsCrashed(status, error_code);
[email protected]960b0372014-05-19 18:01:007097
Alexander Timin5fdeff22020-09-08 09:20:377098 TRACE_EVENT0("content",
7099 "Dispatching WebContentsObserver::RenderViewTerminated");
Alexander Timin90c20c32020-08-12 15:28:327100 // Some observers might destroy WebContents in RenderViewTerminated.
7101 base::WeakPtr<WebContentsImpl> weak_ptr = weak_factory_.GetWeakPtr();
7102 auto crashed_status = GetCrashedStatus();
7103 for (auto& observer : observers_.observer_list()) {
7104 observer.RenderProcessGone(crashed_status);
7105 if (!weak_ptr)
7106 return;
7107 }
7108
7109 // |this| might have been deleted. Do not add code here.
[email protected]420ae012009-04-24 05:16:327110}
7111
[email protected]b172aee2012-04-10 17:05:267112void WebContentsImpl::RenderViewDeleted(RenderViewHost* rvh) {
Alexander Timin5fdeff22020-09-08 09:20:377113 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderViewDeleted",
7114 "render_view_host", rvh);
Alexander Timin90c20c32020-08-12 15:28:327115 observers_.ForEachObserver(
7116 [&](WebContentsObserver* observer) { observer->RenderViewDeleted(rvh); });
[email protected]2e4633c2009-07-09 16:58:067117}
7118
Lukasz Anforowiczfd707142018-02-07 19:46:137119void WebContentsImpl::ClearTargetURL() {
Alexander Timin5fdeff22020-09-08 09:20:377120 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ClearTargetURL");
Mario Sanchez Pradadffbe66e2020-09-07 12:01:087121 frame_that_set_last_target_url_ = nullptr;
Lukasz Anforowiczfd707142018-02-07 19:46:137122 if (delegate_)
7123 delegate_->UpdateTargetURL(this, GURL());
7124}
7125
[email protected]b172aee2012-04-10 17:05:267126void WebContentsImpl::Close(RenderViewHost* rvh) {
Alexander Timin5fdeff22020-09-08 09:20:377127 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::Close", "render_view_host",
7128 rvh);
Avi Drissman7c57be72020-07-29 20:09:467129#if defined(OS_MAC)
[email protected]07707302009-11-06 00:50:297130 // The UI may be in an event-tracking loop, such as between the
7131 // mouse-down and mouse-up in text selection or a button click.
7132 // Defer the close until after tracking is complete, so that we
7133 // don't free objects out from under the UI.
[email protected]07707302009-11-06 00:50:297134 // TODO(shess): This could get more fine-grained. For instance,
7135 // closing a tab in another window while selecting text in the
7136 // current window's Omnibox should be just fine.
Christopher Cameron9ae31e0d2019-03-01 20:01:197137 if (view_->CloseTabAfterEventTrackingIfNeeded())
[email protected]07707302009-11-06 00:50:297138 return;
[email protected]60780f412013-02-25 16:34:107139#endif
[email protected]07707302009-11-06 00:50:297140
[email protected]420ae012009-04-24 05:16:327141 // Ignore this if it comes from a RenderViewHost that we aren't showing.
[email protected]151a63d2011-12-20 22:32:527142 if (delegate_ && rvh == GetRenderViewHost())
[email protected]6934a702011-12-20 00:04:517143 delegate_->CloseContents(this);
[email protected]420ae012009-04-24 05:16:327144}
7145
Avi Drissman014dec72018-06-07 02:34:017146void WebContentsImpl::RequestSetBounds(const gfx::Rect& new_bounds) {
Alexander Timin5fdeff22020-09-08 09:20:377147 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::RequestSetBounds");
Mike Wassermandabad612020-08-13 04:26:277148 if (!delegate_)
7149 return;
7150
7151 // Members of |new_bounds| may be 0 to indicate uninitialized values for newly
7152 // opened windows, even if the |GetContainerBounds()| inner rect is correct.
7153 // TODO(crbug.com/897300): Plumb values as specified; fallback on outer rect.
7154 auto bounds = new_bounds;
7155 if (bounds.IsEmpty())
7156 bounds.set_size(GetContainerBounds().size());
7157
7158 // Only requests from the main frame, not subframes, should reach this code.
Mike Wassermanb6bc0152020-08-25 22:46:207159 int64_t display_id = AdjustRequestedWindowBounds(&bounds, GetMainFrame());
7160
7161 // Drop fullscreen when placing a WebContents to prohibit deceptive behavior.
7162 // Only drop fullscreen on the specific destination display, which is known.
7163 // This supports sites using cross-screen window placement capabilities to
7164 // retain fullscreen and place a window on another screen.
7165 ForSecurityDropFullscreen(display_id).RunAndReset();
7166
Mike Wassermandabad612020-08-13 04:26:277167 delegate_->SetContentsBounds(this, bounds);
[email protected]420ae012009-04-24 05:16:327168}
7169
fdegansa696e5112015-04-17 01:57:597170void WebContentsImpl::DidStartLoading(FrameTreeNode* frame_tree_node,
[email protected]e3b10d12014-03-28 16:06:097171 bool to_different_document) {
Alexander Timin5fdeff22020-09-08 09:20:377172 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DidStartLoading",
7173 "frame_tree_node", frame_tree_node);
Evan Stadec3b26022017-07-14 19:50:247174 LoadingStateChanged(frame_tree_node->IsMainFrame() && to_different_document,
Carlos IL07f282f2020-05-15 22:58:297175 nullptr);
dmazzonibf8cec42015-02-08 08:28:087176
Xiyuan Xia2a66b112018-12-06 15:52:167177 // Reset the focus state from DidStartNavigation to false if a new load starts
7178 // afterward, in case loading logic triggers a FocusLocationBarByDefault call.
7179 should_focus_location_bar_by_default_ = false;
Ian Prestcdd843d2020-01-28 18:59:587180
7181 // Notify accessibility that the user is navigating away from the
7182 // current document.
7183 // TODO(domfarolino, dmazzoni): Do this using WebContentsObserver. See
7184 // https://crbug.com/981271.
7185 BrowserAccessibilityManager* manager =
7186 frame_tree_node->current_frame_host()->browser_accessibility_manager();
7187 if (manager)
7188 manager->UserIsNavigatingAway();
[email protected]420ae012009-04-24 05:16:327189}
7190
fdegansc73eec22015-03-19 14:47:547191void WebContentsImpl::DidStopLoading() {
Alexander Timin5fdeff22020-09-08 09:20:377192 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidStopLoading");
dcheng59716272016-04-09 05:19:087193 std::unique_ptr<LoadNotificationDetails> details;
[email protected]420ae012009-04-24 05:16:327194
[email protected]9595fd82013-04-19 21:28:497195 // Use the last committed entry rather than the active one, in case a
7196 // pending entry has been created.
7197 NavigationEntry* entry = controller_.GetLastCommittedEntry();
7198
[email protected]420ae012009-04-24 05:16:327199 // An entry may not exist for a stop when loading an initial blank page or
7200 // if an iframe injected by script into a blank page finishes loading.
7201 if (entry) {
Fergal Daly55b6d722020-09-11 07:56:337202 details = std::make_unique<LoadNotificationDetails>(
7203 entry->GetVirtualURL(), &controller_,
7204 controller_.GetCurrentEntryIndex());
[email protected]420ae012009-04-24 05:16:327205 }
7206
Carlos IL07f282f2020-05-15 22:58:297207 LoadingStateChanged(true, details.get());
[email protected]420ae012009-04-24 05:16:327208}
7209
fdegansa696e5112015-04-17 01:57:597210void WebContentsImpl::DidChangeLoadProgress() {
Alexander Timin5fdeff22020-09-08 09:20:377211 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidChangeLoadProgress");
Nate Chapin22ea6592019-03-05 22:29:027212 if (is_being_destroyed_)
7213 return;
fdegansa696e5112015-04-17 01:57:597214 double load_progress = frame_tree_.load_progress();
7215
7216 // The delegate is notified immediately for the first and last updates. Also,
7217 // since the message loop may be pretty busy when a page is loaded, it might
7218 // not execute a posted task in a timely manner so the progress report is sent
7219 // immediately if enough time has passed.
7220 base::TimeDelta min_delay =
7221 base::TimeDelta::FromMilliseconds(kMinimumDelayBetweenLoadingUpdatesMS);
7222 bool delay_elapsed = loading_last_progress_update_.is_null() ||
7223 base::TimeTicks::Now() - loading_last_progress_update_ > min_delay;
7224
7225 if (load_progress == 0.0 || load_progress == 1.0 || delay_elapsed) {
7226 // If there is a pending task to send progress, it is now obsolete.
7227 loading_weak_factory_.InvalidateWeakPtrs();
7228
7229 // Notify the load progress change.
7230 SendChangeLoadProgress();
7231
7232 // Clean-up the states if needed.
7233 if (load_progress == 1.0)
7234 ResetLoadProgressState();
7235 return;
7236 }
7237
7238 if (loading_weak_factory_.HasWeakPtrs())
7239 return;
7240
skyostil95082a62015-06-05 19:53:077241 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
tzike2aca992017-09-05 08:50:547242 FROM_HERE,
7243 base::BindOnce(&WebContentsImpl::SendChangeLoadProgress,
7244 loading_weak_factory_.GetWeakPtr()),
fdegansa696e5112015-04-17 01:57:597245 min_delay);
7246}
7247
avid6d88b912017-01-13 00:16:007248std::vector<std::unique_ptr<NavigationThrottle>>
7249WebContentsImpl::CreateThrottlesForNavigation(
clamycbf524d42016-09-27 12:48:357250 NavigationHandle* navigation_handle) {
Alexander Timin5fdeff22020-09-08 09:20:377251 OPTIONAL_TRACE_EVENT1("content",
7252 "WebContentsImpl::CreateThrottlesForNavigation",
7253 "navigation", navigation_handle);
Charlie Reis96077362019-07-04 00:34:047254 auto throttles = GetContentClient()->browser()->CreateThrottlesForNavigation(
clamycbf524d42016-09-27 12:48:357255 navigation_handle);
Charlie Reis96077362019-07-04 00:34:047256
7257 // This is not a normal place to be adding a throttle. However, in the case
7258 // javascript dialogs, related logic is present in the web_contents/ layer,
7259 // and the purpose of the throttle is to ensure that navigation commits are
7260 // deferred for the entire WebContents. Most throttles are either added by
7261 // the embederrer outside of content/, or are per-frame and added by
7262 // NavigationThrottleRunner.
7263 std::unique_ptr<content::NavigationThrottle> dialog_throttle =
7264 JavaScriptDialogNavigationThrottle::MaybeCreateThrottleFor(
7265 navigation_handle);
7266 if (dialog_throttle)
7267 throttles.push_back(std::move(dialog_throttle));
7268
7269 return throttles;
clamycbf524d42016-09-27 12:48:357270}
7271
clamy1e5574e2016-09-29 16:48:447272std::unique_ptr<NavigationUIData> WebContentsImpl::GetNavigationUIData(
7273 NavigationHandle* navigation_handle) {
Alexander Timin5fdeff22020-09-08 09:20:377274 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GetNavigationUIData");
clamy1e5574e2016-09-29 16:48:447275 return GetContentClient()->browser()->GetNavigationUIData(navigation_handle);
7276}
7277
W. James MacLean1c40862c2020-04-27 21:05:577278void WebContentsImpl::RegisterExistingOriginToPreventOptInIsolation(
W. James MacLeanb70fab82020-05-01 18:51:147279 const url::Origin& origin,
7280 NavigationRequest* navigation_request_to_exclude) {
Alexander Timin5fdeff22020-09-08 09:20:377281 OPTIONAL_TRACE_EVENT2(
7282 "content",
7283 "WebContentsImpl::RegisterExistingOriginToPreventOptInIsolation",
7284 "origin", base::trace_event::ValueToString(origin),
7285 "navigation_request_to_exclude", navigation_request_to_exclude);
W. James MacLean1c40862c2020-04-27 21:05:577286 // Note: This function can be made static if we ever need call it without
7287 // a WebContentsImpl instance, in which case we can use a wrapper to
7288 // implement the override from NavigatorDelegate.
7289 for (WebContentsImpl* web_contents : GetAllWebContents()) {
7290 web_contents->controller_.RegisterExistingOriginToPreventOptInIsolation(
7291 origin);
W. James MacLeanb70fab82020-05-01 18:51:147292 // Walk the frame tree to pick up any frames without FrameNavigationEntries.
7293 // * Some frames won't have FrameNavigationEntries (Issues 524208, 608402).
7294 // * Some pending navigations won't have NavigationEntries.
7295 web_contents->GetFrameTree()->RegisterExistingOriginToPreventOptInIsolation(
7296 origin, navigation_request_to_exclude);
W. James MacLean1c40862c2020-04-27 21:05:577297 }
7298}
7299
pdr15f5b5b2017-06-20 00:58:007300void WebContentsImpl::DidCancelLoading() {
Alexander Timin5fdeff22020-09-08 09:20:377301 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidCancelLoading");
pdr15f5b5b2017-06-20 00:58:007302 controller_.DiscardNonCommittedEntries();
7303
7304 // Update the URL display.
7305 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
7306}
7307
[email protected]59167c22013-06-03 18:07:327308void WebContentsImpl::DidAccessInitialDocument() {
Alexander Timin5fdeff22020-09-08 09:20:377309 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidAccessInitialDocument");
[email protected]b4c84012014-04-28 19:51:107310 has_accessed_initial_document_ = true;
7311
[email protected]d1371bf8e2014-04-19 03:26:247312 // We may have left a failed browser-initiated navigation in the address bar
7313 // to let the user edit it and try again. Clear it now that content might
7314 // show up underneath it.
7315 if (!IsLoading() && controller_.GetPendingEntry())
avi45a72532015-04-07 21:01:457316 controller_.DiscardPendingEntry(false);
[email protected]d1371bf8e2014-04-19 03:26:247317
[email protected]59167c22013-06-03 18:07:327318 // Update the URL display.
thestigc4cac8f2014-09-04 21:17:507319 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
[email protected]59167c22013-06-03 18:07:327320}
7321
alexmosbe2f4c32015-03-10 02:30:237322void WebContentsImpl::DidChangeName(RenderFrameHost* render_frame_host,
7323 const std::string& name) {
Alexander Timin5fdeff22020-09-08 09:20:377324 OPTIONAL_TRACE_EVENT2(
7325 "content", "WebContentsImpl::DidChangeName", "render_frame_host",
7326 base::trace_event::ToTracedValue(render_frame_host), "name", name);
Alexander Timin90c20c32020-08-12 15:28:327327 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7328 observer->FrameNameChanged(render_frame_host, name);
7329 });
alexmosbe2f4c32015-03-10 02:30:237330}
7331
John Delaneyedd8d6c2019-01-25 00:23:577332void WebContentsImpl::DidReceiveFirstUserActivation(
7333 RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:377334 OPTIONAL_TRACE_EVENT1(
7335 "content", "WebContentsImpl::DidReceiveFirstUserActivation",
7336 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host));
Alexander Timin90c20c32020-08-12 15:28:327337 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7338 observer->FrameReceivedFirstUserActivation(render_frame_host);
7339 });
John Delaneyedd8d6c2019-01-25 00:23:577340}
7341
John Delaney0146a742019-01-25 19:25:287342void WebContentsImpl::DidChangeDisplayState(RenderFrameHost* render_frame_host,
7343 bool is_display_none) {
Alexander Timin5fdeff22020-09-08 09:20:377344 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::DidChangeDisplayState",
7345 "render_frame_host",
7346 base::trace_event::ToTracedValue(render_frame_host),
7347 "is_display_none", is_display_none);
Alexander Timin90c20c32020-08-12 15:28:327348 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7349 observer->FrameDisplayStateChanged(render_frame_host, is_display_none);
7350 });
John Delaney0146a742019-01-25 19:25:287351}
7352
7353void WebContentsImpl::FrameSizeChanged(RenderFrameHost* render_frame_host,
7354 const gfx::Size& frame_size) {
Alexander Timin5fdeff22020-09-08 09:20:377355 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::FrameSizeChanged",
7356 "render_frame_host",
7357 base::trace_event::ToTracedValue(render_frame_host));
Alexander Timin90c20c32020-08-12 15:28:327358 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7359 observer->FrameSizeChanged(render_frame_host, frame_size);
7360 });
John Delaney0146a742019-01-25 19:25:287361}
7362
[email protected]39f2f9252014-05-03 00:54:017363void WebContentsImpl::DocumentOnLoadCompleted(
[email protected]50279492014-05-05 23:24:297364 RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:377365 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DocumentOnLoadCompleted",
7366 "render_frame_host",
7367 base::trace_event::ToTracedValue(render_frame_host));
falken52a56e32016-12-08 05:02:407368 ShowInsecureLocalhostWarningIfNeeded();
7369
Alexander Timindd0fa0c52019-11-06 13:03:377370 GetRenderViewHost()->DocumentOnLoadCompletedInMainFrame();
7371
Alexander Timin90c20c32020-08-12 15:28:327372 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7373 observer->DocumentOnLoadCompletedInMainFrame();
7374 });
[email protected]6578fef2013-10-14 02:35:097375
7376 // TODO(avi): Remove. http://crbug.com/170921
[email protected]8ff00d72012-10-23 19:12:217377 NotificationService::current()->Notify(
7378 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
7379 Source<WebContents>(this),
[email protected]50279492014-05-05 23:24:297380 NotificationService::NoDetails());
[email protected]25497492010-09-11 15:15:087381}
7382
creis8eb8ef22015-11-04 22:51:387383void WebContentsImpl::UpdateStateForFrame(RenderFrameHost* render_frame_host,
7384 const PageState& page_state) {
Alexander Timin5fdeff22020-09-08 09:20:377385 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::UpdateStateForFrame",
7386 "render_frame_host",
7387 base::trace_event::ToTracedValue(render_frame_host));
creis8eb8ef22015-11-04 22:51:387388 // The state update affects the last NavigationEntry associated with the given
7389 // |render_frame_host|. This may not be the last committed NavigationEntry (as
7390 // in the case of an UpdateState from a frame being swapped out). We track
7391 // which entry this is in the RenderFrameHost's nav_entry_id.
7392 RenderFrameHostImpl* rfhi =
7393 static_cast<RenderFrameHostImpl*>(render_frame_host);
7394 NavigationEntryImpl* entry =
7395 controller_.GetEntryWithUniqueID(rfhi->nav_entry_id());
7396 if (!entry)
7397 return;
7398
7399 FrameNavigationEntry* frame_entry =
7400 entry->GetFrameEntry(rfhi->frame_tree_node());
7401 if (!frame_entry)
7402 return;
7403
creisd06a9422015-11-11 03:08:457404 // The SiteInstance might not match if we do a cross-process navigation with
7405 // replacement (e.g., auto-subframe), in which case the swap out of the old
7406 // RenderFrameHost runs in the background after the old FrameNavigationEntry
7407 // has already been replaced and destroyed.
7408 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
7409 return;
7410
creis8eb8ef22015-11-04 22:51:387411 if (page_state == frame_entry->page_state())
7412 return; // Nothing to update.
7413
creis0cade2e2017-02-28 06:37:477414 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
nasko34634672016-07-29 18:46:067415
7416 // The document_sequence_number and item_sequence_number recorded in the
7417 // FrameNavigationEntry should not differ from the one coming with the update,
7418 // since it must come from the same document. Do not update it if a difference
7419 // is detected, as this indicates that |frame_entry| is not the correct one.
7420 ExplodedPageState exploded_state;
7421 if (!DecodePageState(page_state.ToEncodedData(), &exploded_state))
7422 return;
7423
7424 if (exploded_state.top.document_sequence_number !=
7425 frame_entry->document_sequence_number() ||
7426 exploded_state.top.item_sequence_number !=
7427 frame_entry->item_sequence_number()) {
7428 return;
7429 }
7430
nasko04a322f25a2016-09-01 00:00:347431 frame_entry->SetPageState(page_state);
creis8eb8ef22015-11-04 22:51:387432 controller_.NotifyEntryChanged(entry);
7433}
7434
[email protected]ef3adfc2014-05-11 00:04:547435void WebContentsImpl::UpdateTitle(RenderFrameHost* render_frame_host,
[email protected]ef3adfc2014-05-11 00:04:547436 const base::string16& title,
7437 base::i18n::TextDirection title_direction) {
Alexander Timin5fdeff22020-09-08 09:20:377438 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::UpdateTitle",
7439 "render_frame_host",
7440 base::trace_event::ToTracedValue(render_frame_host),
7441 "title", base::trace_event::ValueToString(title));
[email protected]ef3adfc2014-05-11 00:04:547442 // Try to find the navigation entry, which might not be the current one.
avi286019ce2015-07-29 01:26:587443 // For example, it might be from a recently swapped out RFH.
avi1edc8552016-10-13 21:37:167444 NavigationEntryImpl* entry = controller_.GetEntryWithUniqueID(
creisad8c31a2016-05-24 17:07:047445 static_cast<RenderFrameHostImpl*>(render_frame_host)->nav_entry_id());
[email protected]ef3adfc2014-05-11 00:04:547446
7447 // We can handle title updates when we don't have an entry in
7448 // UpdateTitleForEntry, but only if the update is from the current RVH.
7449 // TODO(avi): Change to make decisions based on the RenderFrameHost.
avi286019ce2015-07-29 01:26:587450 if (!entry && render_frame_host != GetMainFrame())
[email protected]ef3adfc2014-05-11 00:04:547451 return;
7452
7453 // TODO(evan): make use of title_direction.
7454 // http://code.google.com/p/chromium/issues/detail?id=27094
afakhry6f0c1ec22016-07-14 13:55:137455 UpdateTitleForEntry(entry, title);
[email protected]ef3adfc2014-05-11 00:04:547456}
7457
Mario Sanchez Pradadffbe66e2020-09-07 12:01:087458void WebContentsImpl::UpdateTargetURL(RenderFrameHost* render_frame_host,
7459 const GURL& url) {
Alexander Timin5fdeff22020-09-08 09:20:377460 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::UpdateTargetURL",
7461 "render_frame_host",
7462 base::trace_event::ToTracedValue(render_frame_host),
7463 "url", base::trace_event::ValueToString(url));
Mario Sanchez Pradadffbe66e2020-09-07 12:01:087464 if (fullscreen_widget_routing_id_ != MSG_ROUTING_NONE) {
7465 // If we're in flash fullscreen (i.e. Pepper plugin fullscreen) only update
7466 // the url if it's from the fullscreen renderer.
7467 RenderWidgetHostView* fs = GetFullscreenRenderWidgetHostView();
7468 RenderViewHost* render_view_host = render_frame_host->GetRenderViewHost();
7469 if (fs && fs->GetRenderWidgetHost() != render_view_host->GetWidget())
7470 return;
7471 }
7472
7473 // In case of racey updates from multiple RenderViewHosts, the last URL should
7474 // be shown - see also some discussion in https://crbug.com/807776.
7475 if (!url.is_valid() && render_frame_host != frame_that_set_last_target_url_)
7476 return;
7477 frame_that_set_last_target_url_ =
7478 url.is_valid() ? render_frame_host : nullptr;
7479
7480 if (delegate_)
7481 delegate_->UpdateTargetURL(this, url);
7482}
7483
alexmose7da5a12015-04-09 02:22:167484bool WebContentsImpl::ShouldRouteMessageEvent(
7485 RenderFrameHost* target_rfh,
7486 SiteInstance* source_site_instance) const {
Alexander Timin5fdeff22020-09-08 09:20:377487 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::ShouldRouteMessageEvent",
7488 "render_frame_host",
7489 base::trace_event::ToTracedValue(target_rfh),
7490 "source_site_instance", source_site_instance);
alexmose7da5a12015-04-09 02:22:167491 // Allow the message if this WebContents is dedicated to a browser plugin
7492 // guest.
[email protected]0eba810b2012-10-18 03:19:367493 // Note: This check means that an embedder could theoretically receive a
7494 // postMessage from anyone (not just its own guests). However, this is
7495 // probably not a risk for apps since other pages won't have references
7496 // to App windows.
alexmose7da5a12015-04-09 02:22:167497 return GetBrowserPluginGuest() || GetBrowserPluginEmbedder();
7498}
[email protected]f546640b2012-05-15 00:03:497499
alexmos58729042015-06-18 23:20:007500void WebContentsImpl::EnsureOpenerProxiesExist(RenderFrameHost* source_rfh) {
Alexander Timin5fdeff22020-09-08 09:20:377501 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::EnsureOpenerProxiesExist",
7502 "render_frame_host",
7503 base::trace_event::ToTracedValue(source_rfh));
alexmose7da5a12015-04-09 02:22:167504 WebContentsImpl* source_web_contents = static_cast<WebContentsImpl*>(
7505 WebContents::FromRenderFrameHost(source_rfh));
[email protected]f546640b2012-05-15 00:03:497506
alexmose7da5a12015-04-09 02:22:167507 if (source_web_contents) {
lazyboy6ec48b2a2015-06-29 15:18:147508 // If this message is going to outer WebContents from inner WebContents,
7509 // then we should not create a RenderView. AttachToOuterWebContentsFrame()
7510 // already created a RenderFrameProxyHost for that purpose.
7511 if (GetBrowserPluginEmbedder() &&
W. James MacLean2539adb32019-12-13 00:40:447512 source_web_contents->browser_plugin_guest_) {
lazyboy6ec48b2a2015-06-29 15:18:147513 return;
W. James MacLean2539adb32019-12-13 00:40:447514 }
lazyboy6ec48b2a2015-06-29 15:18:147515
lfg812874d2016-02-09 22:26:137516 if (this != source_web_contents && GetBrowserPluginGuest()) {
naskob3041b98a42016-03-12 04:43:067517 // We create a RenderFrameProxyHost for the embedder in the guest's render
7518 // process but we intentionally do not expose the embedder's opener chain
7519 // to it.
7520 source_web_contents->GetRenderManager()->CreateRenderFrameProxy(
7521 GetSiteInstance());
[email protected]f546640b2012-05-15 00:03:497522 } else {
alexmos58729042015-06-18 23:20:007523 RenderFrameHostImpl* source_rfhi =
7524 static_cast<RenderFrameHostImpl*>(source_rfh);
7525 source_rfhi->frame_tree_node()->render_manager()->CreateOpenerProxies(
alexmos90325cf2015-09-02 17:18:397526 GetSiteInstance(), nullptr);
[email protected]f546640b2012-05-15 00:03:497527 }
7528 }
[email protected]f546640b2012-05-15 00:03:497529}
7530
avallee9993fca2016-11-17 06:16:507531void WebContentsImpl::SetAsFocusedWebContentsIfNecessary() {
Alexander Timin5fdeff22020-09-08 09:20:377532 OPTIONAL_TRACE_EVENT0("content",
7533 "WebContentsImpl::SetAsFocusedWebContentsIfNecessary");
Adithya Srinivasan11af2c52019-12-16 22:52:557534 DCHECK(!portal());
avallee9993fca2016-11-17 06:16:507535 // Only change focus if we are not currently focused.
7536 WebContentsImpl* old_contents = GetFocusedWebContents();
7537 if (old_contents == this)
7538 return;
7539
paulmeyerfeafc2d2017-04-25 21:46:407540 GetOutermostWebContents()->node_.SetFocusedWebContents(this);
7541
avallee9993fca2016-11-17 06:16:507542 // Send a page level blur to the old contents so that it displays inactive UI
7543 // and focus this contents to activate it.
7544 if (old_contents)
7545 old_contents->GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(false);
avalleec2ff1ef2017-01-21 00:12:307546
7547 // Make sure the outer web contents knows our frame is focused. Otherwise, the
7548 // outer renderer could have the element before or after the frame element
7549 // focused which would return early without actually advancing focus.
avalleed68cdd12017-06-21 22:07:277550 FocusOuterAttachmentFrameChain();
avalleec2ff1ef2017-01-21 00:12:307551
Carlos ILd51e7702020-05-07 18:51:397552 GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(true);
avallee9993fca2016-11-17 06:16:507553}
7554
avallee0206f782016-07-28 18:55:337555void WebContentsImpl::SetFocusedFrame(FrameTreeNode* node,
7556 SiteInstance* source) {
Alexander Timin5fdeff22020-09-08 09:20:377557 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetFocusedFrame",
7558 "frame_tree_node", node, "source_site_instance",
7559 source);
Adithya Srinivasan11af2c52019-12-16 22:52:557560 DCHECK(!portal());
avallee0206f782016-07-28 18:55:337561 frame_tree_.SetFocusedFrame(node, source);
avalleed68cdd12017-06-21 22:07:277562
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:577563 if (auto* inner_contents = node_.GetInnerWebContentsInFrame(node)) {
7564 // |this| is an outer WebContents and |node| represents an inner
7565 // WebContents. Transfer the focus to the inner contents if |this| is
7566 // focused.
7567 if (GetFocusedWebContents() == this)
7568 inner_contents->SetAsFocusedWebContentsIfNecessary();
7569 } else if (node_.OuterContentsFrameTreeNode() &&
7570 node_.OuterContentsFrameTreeNode()
7571 ->current_frame_host()
7572 ->GetSiteInstance() == source) {
7573 // |this| is an inner WebContents, |node| is its main FrameTreeNode and
7574 // the outer WebContents FrameTreeNode is at |source|'s SiteInstance.
7575 // Transfer the focus to the inner WebContents if the outer WebContents is
7576 // focused. This branch is used when an inner WebContents is focused through
Lowell Mannersa9530382019-08-01 09:46:577577 // its RenderFrameProxyHost (via FrameFocused mojo call, used to
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:577578 // implement the window.focus() API).
7579 if (GetFocusedWebContents() == GetOuterWebContents())
7580 SetAsFocusedWebContentsIfNecessary();
7581 } else if (!GetOuterWebContents()) {
7582 // This is an outermost WebContents.
7583 SetAsFocusedWebContentsIfNecessary();
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:577584 }
avalleed68cdd12017-06-21 22:07:277585}
7586
Avi Drissman36f801f2018-02-01 20:06:047587void WebContentsImpl::DidCallFocus() {
Alexander Timin5fdeff22020-09-08 09:20:377588 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidCallFocus");
Avi Drissman36f801f2018-02-01 20:06:047589 // Any explicit focusing of another window while this WebContents is in
7590 // fullscreen can be used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:457591 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
7592 // The other contents is independent of this contents, so release the
7593 // fullscreen block.
7594 fullscreen_block.RunAndReset();
Avi Drissman36f801f2018-02-01 20:06:047595}
7596
avalleed68cdd12017-06-21 22:07:277597RenderFrameHost* WebContentsImpl::GetFocusedFrameIncludingInnerWebContents() {
Alexander Timin5fdeff22020-09-08 09:20:377598 OPTIONAL_TRACE_EVENT0(
7599 "content", "WebContentsImpl::GetFocusedFrameIncludingInnerWebContents");
avalleed68cdd12017-06-21 22:07:277600 WebContentsImpl* contents = this;
7601 FrameTreeNode* focused_node = contents->frame_tree_.GetFocusedFrame();
7602
7603 // If there is no focused frame in the outer WebContents, we need to return
7604 // null.
7605 if (!focused_node)
7606 return nullptr;
7607
7608 // If the focused frame is embedding an inner WebContents, we must descend
7609 // into that contents. If the current WebContents does not have a focused
7610 // frame, return the main frame of this contents instead of the focused empty
7611 // frame embedding this contents.
7612 while (true) {
7613 contents = contents->node_.GetInnerWebContentsInFrame(focused_node);
7614 if (!contents)
7615 return focused_node->current_frame_host();
7616
7617 focused_node = contents->frame_tree_.GetFocusedFrame();
7618 if (!focused_node)
7619 return contents->GetMainFrame();
7620 }
avallee0206f782016-07-28 18:55:337621}
7622
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:577623void WebContentsImpl::OnAdvanceFocus(RenderFrameHostImpl* source_rfh) {
Alexander Timin5fdeff22020-09-08 09:20:377624 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnAdvanceFocus",
7625 "render_frame_host",
7626 base::trace_event::ToTracedValue(source_rfh));
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:577627 // When a RenderFrame needs to advance focus to a RenderFrameProxy (by hitting
7628 // TAB), the RenderFrameProxy sends an IPC to RenderFrameProxyHost. When this
7629 // RenderFrameProxyHost represents an inner WebContents, the outer WebContents
7630 // needs to focus the inner WebContents.
7631 if (GetOuterWebContents() &&
7632 GetOuterWebContents() == source_rfh->delegate()->GetAsWebContents() &&
7633 GetFocusedWebContents() == GetOuterWebContents()) {
7634 SetAsFocusedWebContentsIfNecessary();
7635 }
7636}
7637
ekaramada110f642016-12-21 19:47:287638void WebContentsImpl::OnFocusedElementChangedInFrame(
7639 RenderFrameHostImpl* frame,
Emily Stark023dbacc2020-08-27 22:31:407640 const gfx::Rect& bounds_in_root_view,
7641 blink::mojom::FocusType focus_type) {
Alexander Timin5fdeff22020-09-08 09:20:377642 OPTIONAL_TRACE_EVENT1(
7643 "content", "WebContentsImpl::OnFocusedElementChangedInFrame",
7644 "render_frame_host", base::trace_event::ToTracedValue(frame));
ekaramada110f642016-12-21 19:47:287645 RenderWidgetHostViewBase* root_view =
7646 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
7647 if (!root_view || !frame->GetView())
7648 return;
Katie De0131372020-07-09 23:03:107649 // Convert to screen coordinates from window coordinates by adding the
7650 // window's origin.
ekaramada110f642016-12-21 19:47:287651 gfx::Point origin = bounds_in_root_view.origin();
7652 origin += root_view->GetViewBounds().OffsetFromOrigin();
7653 gfx::Rect bounds_in_screen(origin, bounds_in_root_view.size());
7654
7655 root_view->FocusedNodeChanged(frame->has_focused_editable_element(),
7656 bounds_in_screen);
7657
7658 FocusedNodeDetails details = {frame->has_focused_editable_element(),
Emily Stark023dbacc2020-08-27 22:31:407659 bounds_in_screen, focus_type};
ekaramada110f642016-12-21 19:47:287660
7661 // TODO(ekaramad): We should replace this with an observer notification
7662 // (https://crbug.com/675975).
7663 NotificationService::current()->Notify(
7664 NOTIFICATION_FOCUS_CHANGED_IN_PAGE,
7665 Source<RenderViewHost>(GetRenderViewHost()),
7666 Details<FocusedNodeDetails>(&details));
Jeff Fisher709b4c52019-07-29 20:07:347667
Alexander Timin90c20c32020-08-12 15:28:327668 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7669 observer->OnFocusChangedInPage(&details);
7670 });
ekaramada110f642016-12-21 19:47:287671}
7672
Lowell Manners1de5242e2019-04-25 10:18:467673bool WebContentsImpl::DidAddMessageToConsole(
7674 blink::mojom::ConsoleMessageLevel log_level,
7675 const base::string16& message,
7676 int32_t line_no,
7677 const base::string16& source_id) {
Alexander Timin5fdeff22020-09-08 09:20:377678 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DidAddMessageToConsole",
7679 "message", base::trace_event::ValueToString(message));
7680
Alexander Timin90c20c32020-08-12 15:28:327681 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7682 observer->OnDidAddMessageToConsole(log_level, message, line_no, source_id);
7683 });
Alexander Timin5fdeff22020-09-08 09:20:377684
[email protected]a796f202012-05-30 14:14:257685 if (!delegate_)
7686 return false;
Lowell Manners1de5242e2019-04-25 10:18:467687 return delegate_->DidAddMessageToConsole(this, log_level, message, line_no,
avia90ae4e2016-11-11 20:49:337688 source_id);
[email protected]a796f202012-05-30 14:14:257689}
7690
Daniel Cheng90196c82018-04-25 21:49:147691void WebContentsImpl::DidReceiveInputEvent(
dominickn9c7ceaa32016-02-27 01:52:537692 RenderWidgetHostImpl* render_widget_host,
Emily Starkc7bd40c42020-07-21 19:12:557693 const blink::WebInputEvent& event) {
Alexander Timin5fdeff22020-09-08 09:20:377694 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DidReceiveInputEvent",
7695 "render_widget_host", render_widget_host);
7696
Emily Starkc7bd40c42020-07-21 19:12:557697 if (!IsUserInteractionInputType(event.GetType()))
Daniel Cheng90196c82018-04-25 21:49:147698 return;
7699
kenrb19221852016-04-29 17:21:407700 // Ignore unless the widget is currently in the frame tree.
7701 if (!HasMatchingWidgetHost(&frame_tree_, render_widget_host))
avic3aa8422015-11-09 20:57:227702 return;
7703
Emily Starkc7bd40c42020-07-21 19:12:557704 if (event.GetType() != blink::WebInputEvent::Type::kGestureScrollBegin)
Daniel Cheng90196c82018-04-25 21:49:147705 last_interactive_input_event_time_ = ui::EventTimeForNow();
dominickn9c7ceaa32016-02-27 01:52:537706
Alexander Timin90c20c32020-08-12 15:28:327707 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7708 observer->DidGetUserInteraction(event);
7709 });
dominickn2dd142dd2015-10-29 05:30:507710}
7711
Avi Drissman738ea192018-08-29 20:24:167712bool WebContentsImpl::ShouldIgnoreInputEvents() {
7713 WebContentsImpl* web_contents = this;
7714 while (web_contents) {
7715 if (web_contents->ignore_input_events_)
7716 return true;
7717 web_contents = web_contents->GetOuterWebContents();
7718 }
7719
7720 return false;
7721}
7722
avallee9993fca2016-11-17 06:16:507723void WebContentsImpl::FocusOwningWebContents(
7724 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:377725 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::FocusOwningWebContents",
7726 "render_widget_host", render_widget_host);
Alex Moshchukc4f0a722019-11-19 22:41:287727 RenderWidgetHostImpl* main_frame_widget_host =
7728 GetMainFrame()->GetRenderWidgetHost();
avallee9993fca2016-11-17 06:16:507729 RenderWidgetHostImpl* focused_widget =
Alex Moshchukc4f0a722019-11-19 22:41:287730 GetFocusedRenderWidgetHost(main_frame_widget_host);
avallee9993fca2016-11-17 06:16:507731
7732 if (focused_widget != render_widget_host &&
avallee8e881592016-11-19 00:39:307733 (!focused_widget ||
7734 focused_widget->delegate() != render_widget_host->delegate())) {
avallee9993fca2016-11-17 06:16:507735 SetAsFocusedWebContentsIfNecessary();
7736 }
7737}
7738
[email protected]b172aee2012-04-10 17:05:267739void WebContentsImpl::OnIgnoredUIEvent() {
Alexander Timin5fdeff22020-09-08 09:20:377740 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnIgnoredUIEvent");
[email protected]31145092011-09-30 01:49:447741 // Notify observers.
Alexander Timin90c20c32020-08-12 15:28:327742 observers_.ForEachObserver(
7743 [&](WebContentsObserver* observer) { observer->DidGetIgnoredUIEvent(); });
[email protected]fa1cf0b82010-01-15 21:49:447744}
7745
avic3aa8422015-11-09 20:57:227746void WebContentsImpl::RendererUnresponsive(
Lukasz Anforowicz52b93722018-06-20 16:11:397747 RenderWidgetHostImpl* render_widget_host,
7748 base::RepeatingClosure hang_monitor_restarter) {
Alexander Timin5fdeff22020-09-08 09:20:377749 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RendererUnresponsive",
7750 "render_widget_host", render_widget_host);
avic031d392017-03-03 03:09:427751 if (ShouldIgnoreUnresponsiveRenderer())
[email protected]e5fc1632011-08-08 07:51:537752 return;
7753
Lukasz Anforowicz4f0593d2018-09-21 18:33:547754 // Do not report hangs (to task manager, to hang renderer dialog, etc.) for
7755 // invisible tabs (like extension background page, background tabs). See
7756 // https://crbug.com/881812 for rationale and for choosing the visibility
7757 // (rather than process priority) as the signal here.
7758 if (GetVisibility() != Visibility::VISIBLE)
7759 return;
7760
Avi Drissman8920def2018-01-31 19:53:367761 if (!render_widget_host->renderer_initialized())
[email protected]55452902011-06-01 21:57:477762 return;
7763
Alexander Timin90c20c32020-08-12 15:28:327764 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7765 observer->OnRendererUnresponsive(render_widget_host->GetProcess());
7766 });
Dave Tapuskac6146c52017-12-20 22:48:157767 if (delegate_)
Lukasz Anforowicz52b93722018-06-20 16:11:397768 delegate_->RendererUnresponsive(this, render_widget_host,
7769 std::move(hang_monitor_restarter));
[email protected]420ae012009-04-24 05:16:327770}
7771
avic3aa8422015-11-09 20:57:227772void WebContentsImpl::RendererResponsive(
7773 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:377774 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderResponsive",
7775 "render_widget_host", render_widget_host);
Alexander Timin90c20c32020-08-12 15:28:327776 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7777 observer->OnRendererResponsive(render_widget_host->GetProcess());
7778 });
Alexander Timin5fdeff22020-09-08 09:20:377779
[email protected]6934a702011-12-20 00:04:517780 if (delegate_)
Avi Drissman1572e8c3c2018-02-02 19:06:367781 delegate_->RendererResponsive(this, render_widget_host);
[email protected]420ae012009-04-24 05:16:327782}
7783
Alex Moshchuk7b4f0652019-05-30 18:54:417784void WebContentsImpl::SubframeCrashed(
7785 blink::mojom::FrameVisibility visibility) {
Alexander Timin5fdeff22020-09-08 09:20:377786 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SubframeCrashed",
7787 "visibility",
7788 base::trace_event::ValueToString(visibility));
Alex Moshchuk7b4f0652019-05-30 18:54:417789 // If a subframe crashed on a hidden tab, mark the tab for reload to avoid
7790 // showing a sad frame to the user if they ever switch back to that tab. Do
7791 // this for subframes that are either visible in viewport or visible but
7792 // scrolled out of view, but skip subframes that are not rendered (e.g., via
7793 // "display:none"), since in that case the user wouldn't see a sad frame
7794 // anyway.
7795 bool did_mark_for_reload = false;
7796 if (IsHidden() && visibility != blink::mojom::FrameVisibility::kNotRendered &&
7797 base::FeatureList::IsEnabled(
7798 features::kReloadHiddenTabsWithCrashedSubframes)) {
7799 controller_.SetNeedsReload(
7800 NavigationControllerImpl::NeedsReloadType::kCrashedSubframe);
7801 did_mark_for_reload = true;
7802 UMA_HISTOGRAM_ENUMERATION(
7803 "Stability.ChildFrameCrash.TabMarkedForReload.Visibility", visibility);
7804 }
7805
7806 UMA_HISTOGRAM_BOOLEAN("Stability.ChildFrameCrash.TabMarkedForReload",
7807 did_mark_for_reload);
7808}
7809
[email protected]b172aee2012-04-10 17:05:267810void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
[email protected]feaded02012-09-25 19:12:557811 bool proceed, const base::TimeTicks& proceed_time,
[email protected]420ae012009-04-24 05:16:327812 bool* proceed_to_fire_unload) {
Alexander Timin5fdeff22020-09-08 09:20:377813 OPTIONAL_TRACE_EVENT0("content",
7814 "WebContentsImpl::BeforeUnloadFiredFromRenderManager");
Alexander Timin90c20c32020-08-12 15:28:327815 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7816 observer->BeforeUnloadFired(proceed, proceed_time);
7817 });
[email protected]6934a702011-12-20 00:04:517818 if (delegate_)
7819 delegate_->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
[email protected]e80af492013-06-24 21:52:097820 // Note: |this| might be deleted at this point.
[email protected]420ae012009-04-24 05:16:327821}
7822
[email protected]58d5cfe2013-07-10 02:40:527823void WebContentsImpl::RenderProcessGoneFromRenderManager(
[email protected]3a3d47472010-07-15 21:03:547824 RenderViewHost* render_view_host) {
[email protected]443b80e2010-12-14 00:42:237825 DCHECK(crashed_status_ != base::TERMINATION_STATUS_STILL_RUNNING);
[email protected]ec6a7eb2013-04-22 17:34:227826 RenderViewTerminated(render_view_host, crashed_status_, crashed_error_code_);
[email protected]3a3d47472010-07-15 21:03:547827}
7828
[email protected]af905902013-10-01 21:38:517829void WebContentsImpl::CancelModalDialogsForRenderManager() {
Alexander Timin5fdeff22020-09-08 09:20:377830 OPTIONAL_TRACE_EVENT0("content",
7831 "WebContentsImpl::CancelModalDialogsForRenderManager");
[email protected]af905902013-10-01 21:38:517832 // We need to cancel modal dialogs when doing a process swap, since the load
avi2460c762015-04-17 15:21:547833 // deferrer would prevent us from swapping out. We also clear the state
7834 // because this is a cross-process navigation, which means that it's a new
7835 // site that should not have to pay for the sins of its predecessor.
creis89a0f782015-05-27 16:13:177836 //
Lei Zhang6410ec1a2019-01-31 21:38:587837 // Note that we don't bother telling |browser_plugin_embedder_| because the
creis89a0f782015-05-27 16:13:177838 // cross-process navigation will either destroy the browser plugins or not
7839 // require their dialogs to close.
avi5d3b8692016-10-12 22:00:467840 if (dialog_manager_) {
avi6879fcf2017-01-21 05:27:537841 dialog_manager_->CancelDialogs(this, /*reset_state=*/true);
avi5d3b8692016-10-12 22:00:467842 }
[email protected]af905902013-10-01 21:38:517843}
7844
danakja0bce4c952020-05-12 20:40:287845void WebContentsImpl::NotifySwappedFromRenderManager(RenderFrameHost* old_frame,
7846 RenderFrameHost* new_frame,
[email protected]02d7b6e2014-06-24 21:01:507847 bool is_main_frame) {
Alexander Timin5fdeff22020-09-08 09:20:377848 TRACE_EVENT2(
7849 "content", "WebContentsImpl::NotifySwappedFromRenderManager",
7850 "old_render_frame_host", base::trace_event::ToTracedValue(old_frame),
7851 "new_render_frame_host", base::trace_event::ToTracedValue(new_frame));
[email protected]02d7b6e2014-06-24 21:01:507852 if (is_main_frame) {
danakja0bce4c952020-05-12 20:40:287853 // The |new_frame| and its various compadres are already swapped into place
7854 // for the WebContentsImpl when this method is called.
7855 DCHECK(GetMainFrame() == new_frame);
7856 DCHECK(GetRenderViewHost() == new_frame->GetRenderViewHost());
7857 DCHECK(GetRenderWidgetHostView() == new_frame->GetView());
7858
Fergal Daly6767b2e2020-02-04 03:15:167859 RenderViewHost* old_rvh =
danakja0bce4c952020-05-12 20:40:287860 old_frame ? old_frame->GetRenderViewHost() : nullptr;
7861 RenderViewHost* new_rvh = new_frame->GetRenderViewHost();
Fergal Daly6767b2e2020-02-04 03:15:167862 // |old_rvh| and |new_rvh| might be equal when navigating from a crashed
7863 // RenderFrameHost to a new same-site one. With RenderDocument, this will
7864 // happen for every same-site navigation.
7865 if (old_rvh != new_rvh)
7866 NotifyViewSwapped(old_rvh, new_rvh);
[email protected]a6b73c62013-02-11 23:05:087867
[email protected]02d7b6e2014-06-24 21:01:507868 // Make sure the visible RVH reflects the new delegate's preferences.
7869 if (delegate_)
7870 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
[email protected]d56a49e2013-02-23 00:47:397871
danakja0bce4c952020-05-12 20:40:287872 auto* rwhv = static_cast<RenderWidgetHostViewBase*>(new_frame->GetView());
7873 if (rwhv) {
7874 rwhv->SetMainFrameAXTreeID(new_frame->GetAXTreeID());
7875
7876 // The RenderWidgetHostView for the speculative RenderFrameHost is not
7877 // resized with the current RenderFrameHost while a navigation is
7878 // pending. So when we swap in the main frame, we need to update the
7879 // RenderWidgetHostView's size.
7880 //
7881 // Historically, this was done to fix b/1079768 for interstitials.
7882 rwhv->SetSize(GetSizeForMainFrame());
7883 }
[email protected]02d7b6e2014-06-24 21:01:507884 }
7885
danakja0bce4c952020-05-12 20:40:287886 NotifyFrameSwapped(old_frame, new_frame, is_main_frame);
[email protected]3a3d47472010-07-15 21:03:547887}
7888
naskof5940b9f2015-03-02 23:04:057889void WebContentsImpl::NotifyMainFrameSwappedFromRenderManager(
danakja0bce4c952020-05-12 20:40:287890 RenderFrameHost* old_frame,
7891 RenderFrameHost* new_frame) {
7892 NotifyViewSwapped(old_frame ? old_frame->GetRenderViewHost() : nullptr,
7893 new_frame->GetRenderViewHost());
naskof5940b9f2015-03-02 23:04:057894}
7895
[email protected]b172aee2012-04-10 17:05:267896NavigationControllerImpl& WebContentsImpl::GetControllerForRenderManager() {
[email protected]d1198fd2012-08-13 22:50:197897 return GetController();
[email protected]3a3d47472010-07-15 21:03:547898}
7899
dcheng59716272016-04-09 05:19:087900std::unique_ptr<WebUIImpl> WebContentsImpl::CreateWebUIForRenderFrameHost(
Miyoung Shin072d4052020-07-13 07:52:447901 RenderFrameHost* frame_host,
Denis Kuznetsov [CET]2c6f0159f2020-05-18 14:18:167902 const GURL& url) {
Miyoung Shin072d4052020-07-13 07:52:447903 return CreateWebUI(frame_host, url);
[email protected]420ae012009-04-24 05:16:327904}
7905
lfgbede6392015-09-11 21:54:067906void WebContentsImpl::CreateRenderWidgetHostViewForRenderManager(
7907 RenderViewHost* render_view_host) {
Alexander Timin5fdeff22020-09-08 09:20:377908 OPTIONAL_TRACE_EVENT1(
7909 "content", "WebContentsImpl::CreateRenderWidgetHostViewForRenderManager",
7910 "render_view_host", render_view_host);
lfgc740d4b22016-04-15 16:45:337911 RenderWidgetHostViewBase* rwh_view =
W. James MacLean13d834d2019-12-04 16:06:457912 view_->CreateViewForWidget(render_view_host->GetWidget());
danakja0bce4c952020-05-12 20:40:287913 rwh_view->SetSize(GetSizeForMainFrame());
lfgbede6392015-09-11 21:54:067914}
7915
7916bool WebContentsImpl::CreateRenderViewForRenderManager(
7917 RenderViewHost* render_view_host,
Antonio Gomesb3dd5fc2020-05-25 22:53:277918 const base::Optional<base::UnguessableToken>& opener_frame_token,
Daniel Chengabfdb002020-06-04 06:02:307919 int proxy_routing_id) {
Alexander Timin5fdeff22020-09-08 09:20:377920 TRACE_EVENT1("browser,navigation",
7921 "WebContentsImpl::CreateRenderViewForRenderManager",
7922 "render_view_host", render_view_host);
lfgbede6392015-09-11 21:54:067923
piman00cf9402017-04-03 17:09:207924 if (proxy_routing_id == MSG_ROUTING_NONE)
lfg9431efd2016-12-14 14:45:267925 CreateRenderWidgetHostViewForRenderManager(render_view_host);
lfg9431efd2016-12-14 14:45:267926
piman00cf9402017-04-03 17:09:207927 if (!static_cast<RenderViewHostImpl*>(render_view_host)
Daniel Chengabfdb002020-06-04 06:02:307928 ->CreateRenderView(opener_frame_token, proxy_routing_id,
Antonio Gomesb3dd5fc2020-05-25 22:53:277929 created_with_opener_)) {
[email protected]a4127722011-04-27 23:13:527930 return false;
[email protected]14392a52012-05-02 20:28:447931 }
W. James MacLean62198672019-06-04 16:46:107932 // Set the TextAutosizer state from the main frame's renderer on the new view,
7933 // but only if it's not for the main frame. Main frame renderers should create
7934 // this state themselves from up-to-date values, so we shouldn't override it
7935 // with the cached values.
7936 if (!render_view_host->GetMainFrame()) {
Antonio Gomesda7e03d2020-08-05 15:03:087937 auto* proxy_host = GetRenderManager()->GetRenderFrameProxyHost(
7938 render_view_host->GetSiteInstance());
7939 proxy_host->GetAssociatedRemoteMainFrame()->UpdateTextAutosizerPageInfo(
7940 text_autosizer_page_info_.Clone());
W. James MacLean62198672019-06-04 16:46:107941 }
[email protected]a4127722011-04-27 23:13:527942
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:147943 if (proxy_routing_id == MSG_ROUTING_NONE && node_.outer_web_contents())
7944 ReattachToOuterWebContentsFrame();
7945
avi2b177592014-12-10 02:08:027946 SetHistoryOffsetAndLengthForView(render_view_host,
7947 controller_.GetLastCommittedEntryIndex(),
7948 controller_.GetEntryCount());
7949
Avi Drissman7c57be72020-07-29 20:09:467950#if defined(OS_POSIX) && !defined(OS_MAC) && !defined(OS_ANDROID)
[email protected]f8233cc2011-05-31 20:24:507951 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
7952 // linux. See crbug.com/83941.
avif9ab5d942015-10-15 14:05:447953 RenderWidgetHostView* rwh_view = render_view_host->GetWidget()->GetView();
[email protected]245f7d52011-11-28 15:36:447954 if (rwh_view) {
7955 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
Fady Samuel0b911822018-04-25 13:22:167956 render_widget_host->SynchronizeVisualProperties();
[email protected]245f7d52011-11-28 15:36:447957 }
[email protected]f8233cc2011-05-31 20:24:507958#endif
7959
[email protected]420ae012009-04-24 05:16:327960 return true;
7961}
7962
mfomitchev2b8b066a2016-01-28 19:23:157963#if defined(OS_ANDROID)
[email protected]fc2b46b2014-05-03 16:33:457964
[email protected]155c7f22013-12-09 17:07:187965base::android::ScopedJavaLocalRef<jobject>
7966WebContentsImpl::GetJavaWebContents() {
mostynb042582e2015-03-16 22:13:407967 DCHECK_CURRENTLY_ON(BrowserThread::UI);
[email protected]0e813a52014-08-13 10:34:567968 return GetWebContentsAndroid()->GetJavaObject();
7969}
[email protected]155c7f22013-12-09 17:07:187970
[email protected]0e813a52014-08-13 10:34:567971WebContentsAndroid* WebContentsImpl::GetWebContentsAndroid() {
Kevin McNee576bb5d82019-05-29 16:47:517972 if (!web_contents_android_) {
7973 web_contents_android_ = std::make_unique<WebContentsAndroid>(this);
[email protected]155c7f22013-12-09 17:07:187974 }
Kevin McNee576bb5d82019-05-29 16:47:517975 return web_contents_android_.get();
7976}
7977
7978void WebContentsImpl::ClearWebContentsAndroid() {
7979 DCHECK_CURRENTLY_ON(BrowserThread::UI);
7980 web_contents_android_.reset();
[email protected]155c7f22013-12-09 17:07:187981}
7982
paulmeyerc0b762b2016-04-13 11:55:177983void WebContentsImpl::ActivateNearestFindResult(float x,
7984 float y) {
Alexander Timin5fdeff22020-09-08 09:20:377985 OPTIONAL_TRACE_EVENT0("content",
7986 "WebContentsImpl::ActivateNearestFindResult");
paulmeyerc0b762b2016-04-13 11:55:177987 GetOrCreateFindRequestManager()->ActivateNearestFindResult(x, y);
7988}
7989
7990void WebContentsImpl::RequestFindMatchRects(int current_version) {
Alexander Timin5fdeff22020-09-08 09:20:377991 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::RequestFindMatchRects");
paulmeyerc0b762b2016-04-13 11:55:177992 GetOrCreateFindRequestManager()->RequestFindMatchRects(current_version);
7993}
7994
rockot400ea35b2016-10-15 19:15:327995service_manager::InterfaceProvider* WebContentsImpl::GetJavaInterfaces() {
sammcf5f1b0f2016-09-20 23:05:117996 if (!java_interfaces_) {
Gyuyoung Kim6c9ce9022019-11-26 05:40:087997 mojo::PendingRemote<service_manager::mojom::InterfaceProvider> provider;
7998 BindInterfaceRegistryForWebContents(
7999 provider.InitWithNewPipeAndPassReceiver(), this);
rockot400ea35b2016-10-15 19:15:328000 java_interfaces_.reset(new service_manager::InterfaceProvider);
sammcf5f1b0f2016-09-20 23:05:118001 java_interfaces_->Bind(std::move(provider));
8002 }
8003 return java_interfaces_.get();
8004}
8005
Francois Doray6c26f3342018-08-24 17:17:228006#endif
8007
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:418008bool WebContentsImpl::CompletedFirstVisuallyNonEmptyPaint() {
Carlos Caballero91fffb22019-10-29 15:24:308009 return GetRenderViewHost()->did_first_visually_non_empty_paint();
spqchane72c3cb2017-06-30 23:02:108010}
8011
pkotwicz75ca8ffd2016-02-16 23:10:198012void WebContentsImpl::OnDidDownloadImage(
Avi Drissmana5a52dd2018-03-27 03:39:028013 ImageDownloadCallback callback,
pkotwicz75ca8ffd2016-02-16 23:10:198014 int id,
8015 const GURL& image_url,
leon.hancbc4bc3c2016-02-26 07:08:528016 int32_t http_status_code,
leon.hanc2228532016-08-16 05:59:188017 const std::vector<SkBitmap>& images,
8018 const std::vector<gfx::Size>& original_image_sizes) {
Alexander Timin5fdeff22020-09-08 09:20:378019 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnDidDownloadImage",
8020 "image_url",
8021 base::trace_event::ValueToString(image_url));
Avi Drissmana5a52dd2018-03-27 03:39:028022 std::move(callback).Run(id, http_status_code, image_url, images,
8023 original_image_sizes);
pkotwicz75ca8ffd2016-02-16 23:10:198024}
8025
[email protected]6fba26d2014-04-29 09:38:288026void WebContentsImpl::OnDialogClosed(int render_process_id,
8027 int render_frame_id,
Dave Tapuskacdf545cc2020-01-23 18:38:528028 JavaScriptDialogCallback response_callback,
Avi Drissman1a55a9d62020-03-10 18:56:458029 base::ScopedClosureRunner fullscreen_block,
[email protected]87de04b02014-04-08 22:14:498030 bool dialog_was_suppressed,
[email protected]b172aee2012-04-10 17:05:268031 bool success,
[email protected]fcf75d42013-12-03 20:11:268032 const base::string16& user_input) {
[email protected]6fba26d2014-04-29 09:38:288033 RenderFrameHostImpl* rfh = RenderFrameHostImpl::FromID(render_process_id,
8034 render_frame_id);
Alexander Timin5fdeff22020-09-08 09:20:378035 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnDialogClosed",
8036 "render_frame_host",
8037 base::trace_event::ToTracedValue(rfh));
[email protected]87de04b02014-04-08 22:14:498038 last_dialog_suppressed_ = dialog_was_suppressed;
Avi Drissman1a55a9d62020-03-10 18:56:458039 fullscreen_block.RunAndReset();
[email protected]87de04b02014-04-08 22:14:498040
Charlie Reis96077362019-07-04 00:34:048041 javascript_dialog_navigation_deferrer_.reset();
8042
[email protected]beb440c2009-11-06 04:08:548043 if (is_showing_before_unload_dialog_ && !success) {
clamybc6f4152016-04-01 20:14:238044 // It is possible for the current RenderFrameHost to have changed in the
8045 // meantime. Do not reset the navigation state in that case.
8046 if (rfh && rfh == rfh->frame_tree_node()->current_frame_host()) {
clamy44e84ce2016-02-22 15:38:258047 rfh->frame_tree_node()->BeforeUnloadCanceled();
clamybc6f4152016-04-01 20:14:238048 controller_.DiscardNonCommittedEntries();
8049 }
[email protected]ec8e8b02013-06-19 04:57:108050
Charles Reis15d60b132017-11-03 17:43:478051 // Update the URL display either way, to avoid showing a stale URL.
8052 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
8053
Alexander Timin90c20c32020-08-12 15:28:328054 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8055 observer->BeforeUnloadDialogCancelled();
8056 });
[email protected]beb440c2009-11-06 04:08:548057 }
[email protected]87de04b02014-04-08 22:14:498058
Dave Tapuskacdf545cc2020-01-23 18:38:528059 std::move(response_callback).Run(success, user_input);
Pavel Feldman3c1842b2017-08-02 05:00:168060
Dave Tapuskacdf545cc2020-01-23 18:38:528061 std::vector<protocol::PageHandler*> page_handlers =
8062 protocol::PageHandler::EnabledForWebContents(this);
8063 for (auto* handler : page_handlers)
8064 handler->DidCloseJavaScriptDialog(success, user_input);
avi1c51fb62017-02-27 20:43:038065
8066 is_showing_javascript_dialog_ = false;
8067 is_showing_before_unload_dialog_ = false;
[email protected]beb440c2009-11-06 04:08:548068}
8069
[email protected]1ac10dca2013-08-20 20:47:048070bool WebContentsImpl::IsHidden() {
Francois Doraye6161152018-03-27 22:05:378071 return !IsBeingCaptured() && visibility_ != Visibility::VISIBLE;
[email protected]1ac10dca2013-08-20 20:47:048072}
8073
rob97250742015-12-10 17:45:158074int WebContentsImpl::GetOuterDelegateFrameTreeNodeId() {
lfg601233692017-03-06 22:45:448075 return node_.outer_contents_frame_tree_node_id();
lazyboy6ec48b2a2015-06-29 15:18:148076}
8077
ekaramadaeb3c5c2016-11-09 03:22:358078RenderWidgetHostImpl* WebContentsImpl::GetFullscreenRenderWidgetHost() const {
8079 return RenderWidgetHostImpl::FromID(fullscreen_widget_process_id_,
8080 fullscreen_widget_routing_id_);
8081}
8082
[email protected]b0936d22013-11-28 06:47:368083RenderFrameHostManager* WebContentsImpl::GetRenderManager() const {
[email protected]fa944cb82013-11-15 17:51:218084 return frame_tree_.root()->render_manager();
8085}
8086
[email protected]f8497342013-02-05 22:15:028087BrowserPluginGuest* WebContentsImpl::GetBrowserPluginGuest() const {
[email protected]7a846df2012-09-20 19:17:398088 return browser_plugin_guest_.get();
8089}
8090
Albert J. Wongc55cc64d2018-10-12 02:50:048091void WebContentsImpl::SetBrowserPluginGuest(
8092 std::unique_ptr<BrowserPluginGuest> guest) {
Alexander Timin5fdeff22020-09-08 09:20:378093 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetBrowserPluginGuest");
Albert J. Wongc55cc64d2018-10-12 02:50:048094 DCHECK(!browser_plugin_guest_);
8095 DCHECK(guest);
8096 browser_plugin_guest_ = std::move(guest);
[email protected]738f57a2013-06-29 21:06:548097}
8098
Aidan Wolter52bcc12a2018-11-14 03:27:298099base::UnguessableToken WebContentsImpl::GetAudioGroupId() {
Aidan Wolter52bcc12a2018-11-14 03:27:298100 return GetAudioStreamFactory()->group_id();
8101}
8102
Miyoung Shin5709ab02020-02-19 06:50:418103const std::vector<blink::mojom::FaviconURLPtr>&
8104WebContentsImpl::GetFaviconURLs() {
Mounir Lamouri7b4a1f232019-12-23 16:32:108105 return favicon_urls_;
8106}
8107
Mugdha Lakhani0a0d7862020-07-29 09:58:458108// The Mac implementation of the next two methods is in
8109// web_contents_impl_mac.mm
Avi Drissmand4d79f72020-07-30 18:35:188110#if !defined(OS_MAC)
Mugdha Lakhani0a0d7862020-07-29 09:58:458111
8112void WebContentsImpl::Resize(const gfx::Rect& new_bounds) {
Alexander Timin5fdeff22020-09-08 09:20:378113 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Resize");
Mugdha Lakhani0a0d7862020-07-29 09:58:458114#if defined(USE_AURA)
8115 aura::Window* window = GetNativeView();
8116 window->SetBounds(gfx::Rect(window->bounds().origin(), new_bounds.size()));
8117#elif defined(OS_ANDROID)
8118 content::RenderWidgetHostView* view = GetRenderWidgetHostView();
8119 if (view)
8120 view->SetBounds(new_bounds);
8121#endif
8122}
8123
8124gfx::Size WebContentsImpl::GetSize() {
8125#if defined(USE_AURA)
8126 aura::Window* window = GetNativeView();
8127 return window->bounds().size();
8128#elif defined(OS_ANDROID)
8129 ui::ViewAndroid* view_android = GetNativeView();
8130 return view_android->bounds().size();
8131#endif
8132}
8133
Avi Drissmand4d79f72020-07-30 18:35:188134#endif // !defined(OS_MAC)
Mugdha Lakhani0a0d7862020-07-29 09:58:458135
[email protected]f8497342013-02-05 22:15:028136BrowserPluginEmbedder* WebContentsImpl::GetBrowserPluginEmbedder() const {
[email protected]7a846df2012-09-20 19:17:398137 return browser_plugin_embedder_.get();
8138}
[email protected]8ff00d72012-10-23 19:12:218139
fsamuel60b42282015-03-10 03:29:148140void WebContentsImpl::CreateBrowserPluginEmbedderIfNecessary() {
Alexander Timin5fdeff22020-09-08 09:20:378141 OPTIONAL_TRACE_EVENT0(
8142 "content", "WebContentsImpl::CreateBrowserPluginEmbedderIfNecessary");
fsamuel60b42282015-03-10 03:29:148143 if (browser_plugin_embedder_)
8144 return;
8145 browser_plugin_embedder_.reset(BrowserPluginEmbedder::Create(this));
8146}
8147
danakja0bce4c952020-05-12 20:40:288148gfx::Size WebContentsImpl::GetSizeForMainFrame() {
8149 if (delegate_) {
8150 // The delegate has a chance to specify a size independent of the UI.
8151 gfx::Size delegate_size = delegate_->GetSizeForNewRenderView(this);
8152 if (!delegate_size.IsEmpty())
8153 return delegate_size;
8154 }
8155
8156 // Device emulation, when enabled, can specify a size independent of the UI.
8157 if (!device_emulation_size_.IsEmpty())
8158 return device_emulation_size_;
8159
8160 return GetContainerBounds().size();
[email protected]dc0fd432013-08-27 15:29:218161}
8162
[email protected]ae7eeda2014-07-04 01:53:268163void WebContentsImpl::OnFrameRemoved(RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:378164 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnFrameRemoved",
8165 "render_frame_host",
8166 base::trace_event::ToTracedValue(render_frame_host));
Alexander Timin90c20c32020-08-12 15:28:328167 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8168 observer->FrameDeleted(render_frame_host);
8169 });
[email protected]9b159a52013-10-03 17:24:558170}
8171
[email protected]222f5822014-02-05 23:40:498172void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size& old_size) {
Alexander Timin5fdeff22020-09-08 09:20:378173 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnPreferredSizeChanged");
[email protected]222f5822014-02-05 23:40:498174 if (!delegate_)
8175 return;
8176 const gfx::Size new_size = GetPreferredSize();
8177 if (new_size != old_size)
8178 delegate_->UpdatePreferredSize(this, new_size);
8179}
8180
Miyoung Shin072d4052020-07-13 07:52:448181std::unique_ptr<WebUIImpl> WebContentsImpl::CreateWebUI(
8182 RenderFrameHost* frame_host,
8183 const GURL& url) {
Alexander Timin5fdeff22020-09-08 09:20:378184 TRACE_EVENT2("content", "WebContentsImpl::CreateWebUI", "frame_host",
8185 base::trace_event::ToTracedValue(frame_host), "url",
8186 base::trace_event::ValueToString(url));
Miyoung Shin072d4052020-07-13 07:52:448187 std::unique_ptr<WebUIImpl> web_ui =
8188 std::make_unique<WebUIImpl>(this, frame_host);
Lei Zhangee3b63ad2018-06-06 23:25:318189 std::unique_ptr<WebUIController> controller(
avie865b1d2016-10-24 19:42:598190 WebUIControllerFactoryRegistry::GetInstance()
Lei Zhangee3b63ad2018-06-06 23:25:318191 ->CreateWebUIControllerForURL(web_ui.get(), url));
dbeama1b926a2015-08-31 23:17:518192 if (controller) {
Lei Zhangee3b63ad2018-06-06 23:25:318193 web_ui->SetController(std::move(controller));
dbeama1b926a2015-08-31 23:17:518194 return web_ui;
8195 }
8196
avie865b1d2016-10-24 19:42:598197 return nullptr;
dbeama1b926a2015-08-31 23:17:518198}
8199
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:418200FindRequestManager* WebContentsImpl::GetFindRequestManager() {
8201 for (auto* contents = this; contents;
paulmeyerfeafc2d2017-04-25 21:46:408202 contents = contents->GetOuterWebContents()) {
8203 if (contents->find_request_manager_)
8204 return contents->find_request_manager_.get();
8205 }
8206
8207 return nullptr;
8208}
8209
paulmeyerc0b762b2016-04-13 11:55:178210FindRequestManager* WebContentsImpl::GetOrCreateFindRequestManager() {
paulmeyerfeafc2d2017-04-25 21:46:408211 if (FindRequestManager* manager = GetFindRequestManager())
8212 return manager;
8213
Ehsan Karamad6beb2ea2018-11-25 18:15:138214 DCHECK(!browser_plugin_guest_ || GetOuterWebContents());
8215
paulmeyerfeafc2d2017-04-25 21:46:408216 // No existing FindRequestManager found, so one must be created.
Fergal Daly55b6d722020-09-11 07:56:338217 find_request_manager_ = std::make_unique<FindRequestManager>(this);
paulmeyerfeafc2d2017-04-25 21:46:408218
8219 // Concurrent find sessions must not overlap, so destroy any existing
8220 // FindRequestManagers in any inner WebContentses.
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:168221 for (WebContents* contents : GetWebContentsAndAllInner()) {
8222 auto* web_contents_impl = static_cast<WebContentsImpl*>(contents);
8223 if (web_contents_impl == this)
paulmeyerfeafc2d2017-04-25 21:46:408224 continue;
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:168225 if (web_contents_impl->find_request_manager_) {
8226 web_contents_impl->find_request_manager_->StopFinding(
8227 STOP_FIND_ACTION_CLEAR_SELECTION);
8228 web_contents_impl->find_request_manager_.release();
paulmeyerfeafc2d2017-04-25 21:46:408229 }
8230 }
paulmeyerc0b762b2016-04-13 11:55:178231
8232 return find_request_manager_.get();
8233}
8234
8235void WebContentsImpl::NotifyFindReply(int request_id,
8236 int number_of_matches,
8237 const gfx::Rect& selection_rect,
8238 int active_match_ordinal,
8239 bool final_update) {
Alexander Timin5fdeff22020-09-08 09:20:378240 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::NotifyFindReply");
Sebastien Marchandcf97ed52017-07-24 23:50:348241 if (delegate_ && !is_being_destroyed_ &&
Lukasz Anforowicze9ae3722017-09-29 17:37:388242 !GetMainFrame()->GetProcess()->FastShutdownStarted()) {
paulmeyerc0b762b2016-04-13 11:55:178243 delegate_->FindReply(this, request_id, number_of_matches, selection_rect,
8244 active_match_ordinal, final_update);
8245 }
8246}
8247
ortuno467e5792016-06-10 04:32:398248void WebContentsImpl::IncrementBluetoothConnectedDeviceCount() {
Alexander Timin5fdeff22020-09-08 09:20:378249 OPTIONAL_TRACE_EVENT0(
8250 "content", "WebContentsImpl::IncrementBluetoothConnectedDeviceCount");
ortuno467e5792016-06-10 04:32:398251 // Trying to invalidate the tab state while being destroyed could result in a
8252 // use after free.
8253 if (IsBeingDestroyed()) {
8254 return;
8255 }
8256 // Notify for UI updates if the state changes.
8257 bluetooth_connected_device_count_++;
8258 if (bluetooth_connected_device_count_ == 1) {
Francois Doray66766a572019-12-17 20:56:498259 OnIsConnectedToBluetoothDeviceChanged(true);
ortuno467e5792016-06-10 04:32:398260 }
8261}
8262
8263void WebContentsImpl::DecrementBluetoothConnectedDeviceCount() {
Alexander Timin5fdeff22020-09-08 09:20:378264 OPTIONAL_TRACE_EVENT0(
8265 "content", "WebContentsImpl::DecrementBluetoothConnectedDeviceCount");
ortuno467e5792016-06-10 04:32:398266 // Trying to invalidate the tab state while being destroyed could result in a
8267 // use after free.
8268 if (IsBeingDestroyed()) {
8269 return;
8270 }
8271 // Notify for UI updates if the state changes.
Lukasz Anforowicze9ae3722017-09-29 17:37:388272 DCHECK_NE(bluetooth_connected_device_count_, 0u);
ortuno467e5792016-06-10 04:32:398273 bluetooth_connected_device_count_--;
8274 if (bluetooth_connected_device_count_ == 0) {
Francois Doray66766a572019-12-17 20:56:498275 OnIsConnectedToBluetoothDeviceChanged(false);
8276 }
8277}
8278
8279void WebContentsImpl::OnIsConnectedToBluetoothDeviceChanged(
8280 bool is_connected_to_bluetooth_device) {
Alexander Timin5fdeff22020-09-08 09:20:378281 OPTIONAL_TRACE_EVENT0(
8282 "content", "WebContentsImpl::OnIsConnectedToBluetoothDeviceChanged");
Francois Doray66766a572019-12-17 20:56:498283 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
Alexander Timin90c20c32020-08-12 15:28:328284 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8285 observer->OnIsConnectedToBluetoothDeviceChanged(
Francois Doray66766a572019-12-17 20:56:498286 is_connected_to_bluetooth_device);
Alexander Timin90c20c32020-08-12 15:28:328287 });
ortuno467e5792016-06-10 04:32:398288}
8289
Ovidio Henriquez76696f62020-07-08 03:06:598290void WebContentsImpl::IncrementBluetoothScanningSessionsCount() {
Alexander Timin5fdeff22020-09-08 09:20:378291 OPTIONAL_TRACE_EVENT0(
8292 "content", "WebContentsImpl::IncrementBluetoothScanningSessionsCount");
Ovidio Henriquez76696f62020-07-08 03:06:598293 // Trying to invalidate the tab state while being destroyed could result in a
8294 // use after free.
8295 if (IsBeingDestroyed())
8296 return;
8297
8298 // Notify for UI updates if the state changes.
8299 bluetooth_scanning_sessions_count_++;
8300 if (bluetooth_scanning_sessions_count_ == 1)
8301 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8302}
8303
8304void WebContentsImpl::DecrementBluetoothScanningSessionsCount() {
Alexander Timin5fdeff22020-09-08 09:20:378305 OPTIONAL_TRACE_EVENT0(
8306 "content", "WebContentsImpl::DecrementBluetoothScanningSessionsCount");
Ovidio Henriquez76696f62020-07-08 03:06:598307 // Trying to invalidate the tab state while being destroyed could result in a
8308 // use after free.
8309 if (IsBeingDestroyed())
8310 return;
8311
8312 DCHECK_NE(0u, bluetooth_scanning_sessions_count_);
8313 bluetooth_scanning_sessions_count_--;
8314 if (bluetooth_scanning_sessions_count_ == 0)
8315 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8316}
8317
Reilly Grant5e7c79b22019-04-09 17:26:208318void WebContentsImpl::IncrementSerialActiveFrameCount() {
Alexander Timin5fdeff22020-09-08 09:20:378319 OPTIONAL_TRACE_EVENT0("content",
8320 "WebContentsImpl::IncrementSerialActiveFrameCount");
Reilly Grant5e7c79b22019-04-09 17:26:208321 // Trying to invalidate the tab state while being destroyed could result in a
8322 // use after free.
8323 if (IsBeingDestroyed())
8324 return;
8325
8326 // Notify for UI updates if the state changes.
8327 serial_active_frame_count_++;
8328 if (serial_active_frame_count_ == 1)
8329 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8330}
8331
8332void WebContentsImpl::DecrementSerialActiveFrameCount() {
Alexander Timin5fdeff22020-09-08 09:20:378333 OPTIONAL_TRACE_EVENT0("content",
8334 "WebContentsImpl::DecrementSerialActiveFrameCount");
Reilly Grant5e7c79b22019-04-09 17:26:208335 // Trying to invalidate the tab state while being destroyed could result in a
8336 // use after free.
8337 if (IsBeingDestroyed())
8338 return;
8339
8340 // Notify for UI updates if the state changes.
8341 DCHECK_NE(0u, serial_active_frame_count_);
8342 serial_active_frame_count_--;
8343 if (serial_active_frame_count_ == 0)
8344 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8345}
8346
Matt Reynoldse8c6c1f2019-11-02 09:53:538347void WebContentsImpl::IncrementHidActiveFrameCount() {
Alexander Timin5fdeff22020-09-08 09:20:378348 OPTIONAL_TRACE_EVENT0("content",
8349 "WebContentsImpl::IncrementHidActiveFrameCount");
Matt Reynoldse8c6c1f2019-11-02 09:53:538350 // Trying to invalidate the tab state while being destroyed could result in a
8351 // use after free.
8352 if (IsBeingDestroyed())
8353 return;
8354
8355 // Notify for UI updates if the active frame count transitions from zero to
8356 // non-zero.
8357 hid_active_frame_count_++;
8358 if (hid_active_frame_count_ == 1)
8359 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8360}
8361
8362void WebContentsImpl::DecrementHidActiveFrameCount() {
Alexander Timin5fdeff22020-09-08 09:20:378363 OPTIONAL_TRACE_EVENT0("content",
8364 "WebContentsImpl::DecrementHidActiveFrameCount");
Matt Reynoldse8c6c1f2019-11-02 09:53:538365 // Trying to invalidate the tab state while being destroyed could result in a
8366 // use after free.
8367 if (IsBeingDestroyed())
8368 return;
8369
8370 // Notify for UI updates if the active frame count transitions from non-zero
8371 // to zero.
8372 DCHECK_NE(0u, hid_active_frame_count_);
8373 hid_active_frame_count_--;
8374 if (hid_active_frame_count_ == 0)
8375 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8376}
8377
Marijn Kruisselbrink29051042019-08-06 22:56:558378void WebContentsImpl::IncrementNativeFileSystemHandleCount() {
Alexander Timin5fdeff22020-09-08 09:20:378379 OPTIONAL_TRACE_EVENT0(
8380 "content", "WebContentsImpl::IncrementNativeFileSystemHandleCount");
Marijn Kruisselbrink29051042019-08-06 22:56:558381 // Trying to invalidate the tab state while being destroyed could result in a
8382 // use after free.
8383 if (IsBeingDestroyed())
8384 return;
8385
8386 // Notify for UI updates if the state changes. Need both TYPE_TAB and TYPE_URL
8387 // to update both the tab-level usage indicator and the usage indicator in the
8388 // omnibox.
8389 native_file_system_handle_count_++;
8390 if (native_file_system_handle_count_ == 1) {
8391 NotifyNavigationStateChanged(static_cast<content::InvalidateTypes>(
8392 INVALIDATE_TYPE_TAB | INVALIDATE_TYPE_URL));
8393 }
8394}
8395
8396void WebContentsImpl::DecrementNativeFileSystemHandleCount() {
Alexander Timin5fdeff22020-09-08 09:20:378397 OPTIONAL_TRACE_EVENT0(
8398 "content", "WebContentsImpl::DecrementNativeFileSystemHandleCount");
Marijn Kruisselbrink29051042019-08-06 22:56:558399 // Trying to invalidate the tab state while being destroyed could result in a
8400 // use after free.
8401 if (IsBeingDestroyed())
8402 return;
8403
8404 // Notify for UI updates if the state changes. Need both TYPE_TAB and TYPE_URL
8405 // to update both the tab-level usage indicator and the usage indicator in the
8406 // omnibox.
8407 DCHECK_NE(0u, native_file_system_handle_count_);
8408 native_file_system_handle_count_--;
8409 if (native_file_system_handle_count_ == 0) {
8410 NotifyNavigationStateChanged(static_cast<content::InvalidateTypes>(
8411 INVALIDATE_TYPE_TAB | INVALIDATE_TYPE_URL));
8412 }
8413}
8414
zqzhang8ac49002017-03-16 21:51:358415void WebContentsImpl::SetHasPersistentVideo(bool has_persistent_video) {
Alexander Timin5fdeff22020-09-08 09:20:378416 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetHasPersistentVideo",
8417 "has_persistent_video", has_persistent_video,
8418 "had_persistent_value", has_persistent_video_);
zqzhang8ac49002017-03-16 21:51:358419 if (has_persistent_video_ == has_persistent_video)
mlamouri5cd9ae82017-02-18 11:05:098420 return;
8421
zqzhang8ac49002017-03-16 21:51:358422 has_persistent_video_ = has_persistent_video;
mlamouri5cd9ae82017-02-18 11:05:098423 NotifyPreferencesChanged();
zqzhang8ac49002017-03-16 21:51:358424 media_web_contents_observer()->RequestPersistentVideo(has_persistent_video);
mlamouri5cd9ae82017-02-18 11:05:098425}
8426
Ian Vollick5d5c37f2019-06-19 22:50:578427void WebContentsImpl::SetSpatialNavigationDisabled(bool disabled) {
Alexander Timin5fdeff22020-09-08 09:20:378428 OPTIONAL_TRACE_EVENT2(
8429 "content", "WebContentsImpl::SetSpatialNavigationDisabled", "disabled",
8430 disabled, "was_disabled", is_spatial_navigation_disabled_);
Ian Vollick5d5c37f2019-06-19 22:50:578431 if (is_spatial_navigation_disabled_ == disabled)
8432 return;
8433
8434 is_spatial_navigation_disabled_ = disabled;
8435 NotifyPreferencesChanged();
8436}
8437
paulmeyerfeafc2d2017-04-25 21:46:408438void WebContentsImpl::BrowserPluginGuestWillDetach() {
Alexander Timin5fdeff22020-09-08 09:20:378439 OPTIONAL_TRACE_EVENT0("content",
8440 "WebContentsImpl::BrowserPluginGuestWillDetach");
paulmeyerfeafc2d2017-04-25 21:46:408441 WebContentsImpl* outermost = GetOutermostWebContents();
8442 if (this != outermost && ContainsOrIsFocusedWebContents())
8443 outermost->SetAsFocusedWebContentsIfNecessary();
8444}
8445
Becca Hughes112832e2019-06-11 17:19:028446PictureInPictureResult WebContentsImpl::EnterPictureInPicture(
Mounir Lamouri11e9ef42018-05-22 03:10:168447 const viz::SurfaceId& surface_id,
8448 const gfx::Size& natural_size) {
Alexander Timin5fdeff22020-09-08 09:20:378449 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::EnterPictureInPicture");
François Beaufortf09e4462019-01-18 14:34:518450 return delegate_
8451 ? delegate_->EnterPictureInPicture(this, surface_id, natural_size)
Becca Hughes112832e2019-06-11 17:19:028452 : PictureInPictureResult::kNotSupported;
Mounir Lamouri11e9ef42018-05-22 03:10:168453}
8454
Mounir Lamouri6d759e12018-05-16 20:01:308455void WebContentsImpl::ExitPictureInPicture() {
Alexander Timin5fdeff22020-09-08 09:20:378456 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ExitPictureInPicture");
Mounir Lamouri6d759e12018-05-16 20:01:308457 if (delegate_)
8458 delegate_->ExitPictureInPicture();
8459}
8460
paulmeyerc0b762b2016-04-13 11:55:178461#if defined(OS_ANDROID)
8462void WebContentsImpl::NotifyFindMatchRectsReply(
8463 int version,
8464 const std::vector<gfx::RectF>& rects,
8465 const gfx::RectF& active_rect) {
Alexander Timin5fdeff22020-09-08 09:20:378466 OPTIONAL_TRACE_EVENT0("content",
8467 "WebContentsImpl::NotifyFindMatchRectsReply");
paulmeyerc0b762b2016-04-13 11:55:178468 if (delegate_)
8469 delegate_->FindMatchRectsReply(this, version, rects, active_rect);
8470}
8471#endif
8472
[email protected]34ff1cfc2014-08-20 06:16:058473void WebContentsImpl::SetForceDisableOverscrollContent(bool force_disable) {
Alexander Timin5fdeff22020-09-08 09:20:378474 OPTIONAL_TRACE_EVENT1("content",
8475 "WebContentsImpl::SetForceDisableOverscrollContent",
8476 "force_disable", force_disable);
[email protected]34ff1cfc2014-08-20 06:16:058477 force_disable_overscroll_content_ = force_disable;
8478 if (view_)
8479 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
8480}
8481
Jianzhou Fengd8720c72018-01-18 03:06:308482bool WebContentsImpl::SetDeviceEmulationSize(const gfx::Size& new_size) {
Alexander Timin5fdeff22020-09-08 09:20:378483 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetDeviceEmulationSize");
Jianzhou Fengd8720c72018-01-18 03:06:308484 device_emulation_size_ = new_size;
8485 RenderWidgetHostView* rwhv = GetMainFrame()->GetView();
8486
8487 const gfx::Size current_size = rwhv->GetViewBounds().size();
8488 if (view_size_before_emulation_.IsEmpty())
8489 view_size_before_emulation_ = current_size;
8490
8491 if (current_size != new_size)
8492 rwhv->SetSize(new_size);
8493
8494 return current_size != new_size;
8495}
8496
8497void WebContentsImpl::ClearDeviceEmulationSize() {
Alexander Timin5fdeff22020-09-08 09:20:378498 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ClearDeviceEmulationSize");
Jianzhou Fengd8720c72018-01-18 03:06:308499 RenderWidgetHostView* rwhv = GetMainFrame()->GetView();
8500 // WebContentsView could get resized during emulation, which also resizes
8501 // RWHV. If it happens, assume user would like to keep using the size after
8502 // emulation.
8503 // TODO(jzfeng): Prohibit resizing RWHV through any other means (at least when
8504 // WebContentsView size changes).
Dmitry Gozmanc63707182018-03-06 00:09:398505 if (!view_size_before_emulation_.IsEmpty() && rwhv &&
8506 rwhv->GetViewBounds().size() == device_emulation_size_) {
Jianzhou Fengd8720c72018-01-18 03:06:308507 rwhv->SetSize(view_size_before_emulation_);
Dmitry Gozmanc63707182018-03-06 00:09:398508 }
Jianzhou Fengd8720c72018-01-18 03:06:308509 device_emulation_size_ = gfx::Size();
8510 view_size_before_emulation_ = gfx::Size();
8511}
8512
Max Morin5bc74f52018-05-09 07:00:218513ForwardingAudioStreamFactory* WebContentsImpl::GetAudioStreamFactory() {
8514 if (!audio_stream_factory_) {
8515 audio_stream_factory_.emplace(
8516 this,
Max Morinddebb972018-09-20 10:04:148517 // BrowserMainLoop::GetInstance() may be null in unit tests.
8518 BrowserMainLoop::GetInstance()
8519 ? static_cast<media::UserInputMonitorBase*>(
8520 BrowserMainLoop::GetInstance()->user_input_monitor())
8521 : nullptr,
Ken Rockot72964402019-12-06 10:40:518522 AudioStreamBrokerFactory::CreateImpl());
Max Morin5bc74f52018-05-09 07:00:218523 }
8524
8525 return &*audio_stream_factory_;
8526}
8527
dalecurtis88c240072015-12-09 02:11:188528void WebContentsImpl::MediaStartedPlaying(
billorr21c005d2016-11-17 03:57:048529 const WebContentsObserver::MediaPlayerInfo& media_info,
Mounir Lamouri0f5bdf52019-04-04 16:32:358530 const MediaPlayerId& id) {
Alexander Timin5fdeff22020-09-08 09:20:378531 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MediaStartedPlaying");
billorr21c005d2016-11-17 03:57:048532 if (media_info.has_video)
8533 currently_playing_video_count_++;
8534
Alexander Timin90c20c32020-08-12 15:28:328535 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8536 observer->MediaStartedPlaying(media_info, id);
8537 });
dalecurtis88c240072015-12-09 02:11:188538}
8539
8540void WebContentsImpl::MediaStoppedPlaying(
billorr21c005d2016-11-17 03:57:048541 const WebContentsObserver::MediaPlayerInfo& media_info,
Mounir Lamouri0f5bdf52019-04-04 16:32:358542 const MediaPlayerId& id,
Becca Hughes220bfc102017-11-14 18:24:078543 WebContentsObserver::MediaStoppedReason reason) {
Alexander Timin5fdeff22020-09-08 09:20:378544 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MediaStoppedPlaying");
billorr21c005d2016-11-17 03:57:048545 if (media_info.has_video)
8546 currently_playing_video_count_--;
8547
Alexander Timin90c20c32020-08-12 15:28:328548 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8549 observer->MediaStoppedPlaying(media_info, id, reason);
8550 });
billorr21c005d2016-11-17 03:57:048551}
8552
Mounir Lamouri0f5bdf52019-04-04 16:32:358553void WebContentsImpl::MediaResized(const gfx::Size& size,
8554 const MediaPlayerId& id) {
Alexander Timin5fdeff22020-09-08 09:20:378555 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MediaResized");
peconn257951522017-06-09 18:24:598556 cached_video_sizes_[id] = size;
8557
Alexander Timin90c20c32020-08-12 15:28:328558 observers_.ForEachObserver(
8559 [&](WebContentsObserver* observer) { observer->MediaResized(size, id); });
peconn257951522017-06-09 18:24:598560}
8561
Michael Crousee75c7a42020-07-31 21:11:558562void WebContentsImpl::MediaBufferUnderflow(const MediaPlayerId& id) {
Alexander Timin5fdeff22020-09-08 09:20:378563 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MediaBufferUnderflow");
Alexander Timin90c20c32020-08-12 15:28:328564 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8565 observer->MediaBufferUnderflow(id);
8566 });
Michael Crousee75c7a42020-07-31 21:11:558567}
8568
Peter E Conneccb34c22017-09-08 09:37:588569void WebContentsImpl::MediaEffectivelyFullscreenChanged(bool is_fullscreen) {
Alexander Timin5fdeff22020-09-08 09:20:378570 OPTIONAL_TRACE_EVENT1("content",
8571 "WebContentsImpl::MediaEffectivelyFullscreenChanged",
8572 "is_fullscreen", is_fullscreen);
Alexander Timin90c20c32020-08-12 15:28:328573 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8574 observer->MediaEffectivelyFullscreenChanged(is_fullscreen);
8575 });
Peter E Conneccb34c22017-09-08 09:37:588576}
8577
Peter Conn31c726a2017-08-17 11:07:348578base::Optional<gfx::Size> WebContentsImpl::GetFullscreenVideoSize() {
Mounir Lamouri0f5bdf52019-04-04 16:32:358579 base::Optional<MediaPlayerId> id =
Peter Conn31c726a2017-08-17 11:07:348580 media_web_contents_observer_->GetFullscreenVideoMediaPlayerId();
Jan Wilken Dörrie531be7ca2019-06-07 10:05:578581 if (id && base::Contains(cached_video_sizes_, id.value()))
Peter Conn31c726a2017-08-17 11:07:348582 return base::Optional<gfx::Size>(cached_video_sizes_[id.value()]);
Lei Zhang6410ec1a2019-01-31 21:38:588583 return base::nullopt;
peconn257951522017-06-09 18:24:598584}
8585
billorr21c005d2016-11-17 03:57:048586int WebContentsImpl::GetCurrentlyPlayingVideoCount() {
8587 return currently_playing_video_count_;
dalecurtis88c240072015-12-09 02:11:188588}
8589
Raymond Toye413650c2018-08-31 00:12:478590void WebContentsImpl::AudioContextPlaybackStarted(RenderFrameHost* host,
8591 int context_id) {
Alexander Timin5fdeff22020-09-08 09:20:378592 OPTIONAL_TRACE_EVENT1(
8593 "content", "WebContentsImpl::AudioContextPlaybackStarted",
8594 "render_frame_host", base::trace_event::ToTracedValue(host));
Raymond Toye413650c2018-08-31 00:12:478595 WebContentsObserver::AudioContextId audio_context_id(host, context_id);
Alexander Timin90c20c32020-08-12 15:28:328596 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8597 observer->AudioContextPlaybackStarted(audio_context_id);
8598 });
Raymond Toye413650c2018-08-31 00:12:478599}
8600
8601void WebContentsImpl::AudioContextPlaybackStopped(RenderFrameHost* host,
8602 int context_id) {
Alexander Timin5fdeff22020-09-08 09:20:378603 OPTIONAL_TRACE_EVENT1(
8604 "content", "WebContentsImpl::AudioContextPlaybackStopped",
8605 "render_frame_host", base::trace_event::ToTracedValue(host));
Raymond Toye413650c2018-08-31 00:12:478606 WebContentsObserver::AudioContextId audio_context_id(host, context_id);
Alexander Timin90c20c32020-08-12 15:28:328607 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8608 observer->AudioContextPlaybackStopped(audio_context_id);
8609 });
Raymond Toye413650c2018-08-31 00:12:478610}
8611
Chris Hamilton16ca64a2020-05-14 23:13:178612void WebContentsImpl::OnFrameAudioStateChanged(RenderFrameHost* host,
8613 bool is_audible) {
Alexander Timin5fdeff22020-09-08 09:20:378614 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnFrameAudioStateChanged",
8615 "render_frame_host",
8616 base::trace_event::ToTracedValue(host), "is_audible",
8617 is_audible);
Alexander Timin90c20c32020-08-12 15:28:328618 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8619 observer->OnFrameAudioStateChanged(host, is_audible);
8620 });
Chris Hamilton16ca64a2020-05-14 23:13:178621}
8622
evliu7f736f02019-11-07 17:43:508623media::MediaMetricsProvider::RecordAggregateWatchTimeCallback
8624WebContentsImpl::GetRecordAggregateWatchTimeCallback() {
Alexander Timin5fdeff22020-09-08 09:20:378625 OPTIONAL_TRACE_EVENT0("content",
8626 "WebContentsImpl::RecordAggregateWatchTimeCallback");
Becca Hughes53652442020-03-17 15:35:428627 if (!delegate_ || !delegate_->GetDelegateWeakPtr())
8628 return base::DoNothing();
8629
evliu7f736f02019-11-07 17:43:508630 return base::BindRepeating(
Becca Hughes53652442020-03-17 15:35:428631 [](base::WeakPtr<WebContentsDelegate> delegate, GURL last_committed_url,
8632 base::TimeDelta total_watch_time, base::TimeDelta time_stamp,
8633 bool has_video, bool has_audio) {
evliua283c9e2019-11-08 22:57:228634 content::MediaPlayerWatchTime watch_time(
8635 last_committed_url, last_committed_url.GetOrigin(),
8636 total_watch_time, time_stamp, has_video, has_audio);
evliu7f736f02019-11-07 17:43:508637
8638 // Save the watch time if the delegate is still alive.
8639 if (delegate)
8640 delegate->MediaWatchTimeChanged(watch_time);
8641 },
Becca Hughes53652442020-03-17 15:35:428642 delegate_->GetDelegateWeakPtr(), GetMainFrameLastCommittedURL());
evliu7f736f02019-11-07 17:43:508643}
8644
Ehsan Karamad1c631762019-05-13 23:04:018645RenderFrameHostImpl* WebContentsImpl::GetMainFrameForInnerDelegate(
8646 FrameTreeNode* frame_tree_node) {
8647 if (auto* web_contents = node_.GetInnerWebContentsInFrame(frame_tree_node))
8648 return web_contents->GetMainFrame();
8649 return nullptr;
8650}
8651
John Budorickee1c9512019-10-17 15:32:198652bool WebContentsImpl::IsFrameLowPriority(
8653 const RenderFrameHost* render_frame_host) {
8654 if (!delegate_)
8655 return false;
8656 return delegate_->IsFrameLowPriority(this, render_frame_host);
8657}
8658
Roger Tawa03ffdbd2020-01-16 18:12:548659void WebContentsImpl::IsClipboardPasteAllowed(
8660 const GURL& url,
8661 const ui::ClipboardFormatType& data_type,
8662 const std::string& data,
8663 IsClipboardPasteAllowedCallback callback) {
Dominique Fauteux-Chapleau99244382020-07-08 20:37:008664 ++suppress_unresponsive_renderer_count_;
Roger Tawa03ffdbd2020-01-16 18:12:548665 GetContentClient()->browser()->IsClipboardPasteAllowed(
Dominique Fauteux-Chapleau99244382020-07-08 20:37:008666 this, url, data_type, data,
8667 base::BindOnce(&WebContentsImpl::IsClipboardPasteAllowedWrapperCallback,
8668 weak_factory_.GetWeakPtr(), std::move(callback)));
8669}
8670
8671void WebContentsImpl::IsClipboardPasteAllowedWrapperCallback(
8672 IsClipboardPasteAllowedCallback callback,
8673 ClipboardPasteAllowed allowed) {
8674 std::move(callback).Run(allowed);
8675 --suppress_unresponsive_renderer_count_;
Roger Tawa03ffdbd2020-01-16 18:12:548676}
8677
Lan Weif81c6e7c2020-02-12 16:46:098678bool WebContentsImpl::HasSeenRecentScreenOrientationChange() {
8679 static constexpr base::TimeDelta kMaxInterval =
8680 base::TimeDelta::FromSeconds(1);
8681 base::TimeDelta delta =
8682 ui::EventTimeForNow() - last_screen_orientation_change_time_;
8683 // Return whether there is a screen orientation change happened in the recent
8684 // 1 second.
8685 return delta <= kMaxInterval;
8686}
8687
8688void WebContentsImpl::DidChangeScreenOrientation() {
8689 last_screen_orientation_change_time_ = ui::EventTimeForNow();
8690}
8691
Miyoung Shin8f2e1832020-04-27 09:00:028692bool WebContentsImpl::ShowPopupMenu(
Miyoung Shin4d947d22020-04-24 04:48:338693 RenderFrameHostImpl* render_frame_host,
Miyoung Shin8f2e1832020-04-27 09:00:028694 mojo::PendingRemote<blink::mojom::PopupMenuClient>* popup_client,
Miyoung Shin4d947d22020-04-24 04:48:338695 const gfx::Rect& bounds,
8696 int32_t item_height,
8697 double font_size,
8698 int32_t selected_item,
8699 std::vector<blink::mojom::MenuItemPtr>* menu_items,
8700 bool right_aligned,
8701 bool allow_multiple_selection) {
Alexander Timin5fdeff22020-09-08 09:20:378702 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ShowPopupMenu",
8703 "render_frame_host",
8704 base::trace_event::ToTracedValue(render_frame_host));
Alexander Timin90c20c32020-08-12 15:28:328705 for (auto& observer : observers_.observer_list()) {
Miyoung Shin8f2e1832020-04-27 09:00:028706 if (observer.ShowPopupMenu(render_frame_host, popup_client, bounds,
8707 item_height, font_size, selected_item,
8708 menu_items, right_aligned,
8709 allow_multiple_selection)) {
Miyoung Shin4d947d22020-04-24 04:48:338710 return true;
8711 }
8712 }
8713 return false;
8714}
8715
Francois Doraye6161152018-03-27 22:05:378716void WebContentsImpl::UpdateWebContentsVisibility(Visibility visibility) {
Alexander Timin5fdeff22020-09-08 09:20:378717 OPTIONAL_TRACE_EVENT1("content",
8718 "WebContentsImpl::UpdateWebContentsVisibility",
8719 "visibility", visibility);
Francois Doray3f2afbd2018-04-06 19:18:188720 // Occlusion is disabled when |features::kWebContentsOcclusion| is disabled
8721 // (for power and speed impact assessment) or when
8722 // |switches::kDisableBackgroundingOccludedWindowsForTesting| is specified on
8723 // the command line (to avoid flakiness in browser tests).
8724 const bool occlusion_is_disabled =
8725 !base::FeatureList::IsEnabled(features::kWebContentsOcclusion) ||
Francois Doraye6161152018-03-27 22:05:378726 base::CommandLine::ForCurrentProcess()->HasSwitch(
8727 switches::kDisableBackgroundingOccludedWindowsForTesting);
8728 if (occlusion_is_disabled && visibility == Visibility::OCCLUDED)
8729 visibility = Visibility::VISIBLE;
8730
tapted65ff2ea72016-03-01 23:39:008731 if (!did_first_set_visible_) {
Francois Doraye6161152018-03-27 22:05:378732 if (visibility == Visibility::VISIBLE) {
8733 // A WebContents created with CreateParams::initially_hidden = false
8734 // starts with GetVisibility() == Visibility::VISIBLE even though it is
8735 // not really visible. Call WasShown() when it becomes visible for real as
8736 // the page load mechanism and some WebContentsObserver rely on that.
tapted65ff2ea72016-03-01 23:39:008737 WasShown();
Francois Dorayfe4a1772018-02-17 04:17:098738 did_first_set_visible_ = true;
tapted65ff2ea72016-03-01 23:39:008739 }
Francois Doraye6161152018-03-27 22:05:378740
8741 // Trust the initial visibility of the WebContents and do not switch it to
8742 // HIDDEN or OCCLUDED before it becomes VISIBLE for real. Doing so would
8743 // result in destroying resources that would immediately be recreated (e.g.
8744 // UpdateWebContents(HIDDEN) can be called when a WebContents is added to a
8745 // hidden window that is about to be shown).
8746
tapted65ff2ea72016-03-01 23:39:008747 return;
8748 }
Francois Doraye6161152018-03-27 22:05:378749
8750 if (visibility == visibility_)
tapted65ff2ea72016-03-01 23:39:008751 return;
8752
Collin Baker989e0882019-11-01 01:27:178753 UpdateVisibilityAndNotifyPageAndView(visibility);
tapted65ff2ea72016-03-01 23:39:008754}
8755
aelias5252baa2016-04-10 01:18:028756void WebContentsImpl::UpdateOverridingUserAgent() {
Alexander Timin5fdeff22020-09-08 09:20:378757 OPTIONAL_TRACE_EVENT0("content",
8758 "WebContentsImpl::UpdateOverridingUserAgent");
mlamouri5cd9ae82017-02-18 11:05:098759 NotifyPreferencesChanged();
aelias5252baa2016-04-10 01:18:028760}
8761
avid53461d2016-02-25 17:15:048762void WebContentsImpl::SetJavaScriptDialogManagerForTesting(
8763 JavaScriptDialogManager* dialog_manager) {
Alexander Timin5fdeff22020-09-08 09:20:378764 OPTIONAL_TRACE_EVENT0(
8765 "content", "WebContentsImpl::SetJavaScriptDialogManagerForTesting");
avid53461d2016-02-25 17:15:048766 dialog_manager_ = dialog_manager;
8767}
8768
Julie Jeongeun Kim7d0986172019-12-04 03:17:258769void WebContentsImpl::RemoveReceiverSet(const std::string& interface_name) {
Alexander Timin5fdeff22020-09-08 09:20:378770 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RemoveReceiverSet",
8771 "interface_name", interface_name);
Julie Jeongeun Kim7d0986172019-12-04 03:17:258772 auto it = receiver_sets_.find(interface_name);
8773 if (it != receiver_sets_.end())
8774 receiver_sets_.erase(it);
rockotf62002a2016-09-15 00:08:598775}
8776
nzolghadrd87a308d2016-12-07 15:45:568777bool WebContentsImpl::AddDomainInfoToRapporSample(rappor::Sample* sample) {
Alexander Timin5fdeff22020-09-08 09:20:378778 OPTIONAL_TRACE_EVENT0("content",
8779 "WebContentsImpl::AddDomainInfoToRapporSample");
nzolghadrbbffc6c2017-05-25 17:56:398780 // Here we associate this metric to the main frame URL regardless of what
8781 // caused it.
nzolghadrd87a308d2016-12-07 15:45:568782 sample->SetStringField("Domain", ::rappor::GetDomainAndRegistrySampleFromGURL(
8783 GetLastCommittedURL()));
nzolghadrd87a308d2016-12-07 15:45:568784 return true;
8785}
8786
falken52a56e32016-12-08 05:02:408787void WebContentsImpl::ShowInsecureLocalhostWarningIfNeeded() {
Alexander Timin5fdeff22020-09-08 09:20:378788 OPTIONAL_TRACE_EVENT0(
8789 "content", "WebContentsImpl::ShowInsecureLocalhostWarningIfNeeded");
falken52a56e32016-12-08 05:02:408790 bool allow_localhost = base::CommandLine::ForCurrentProcess()->HasSwitch(
8791 switches::kAllowInsecureLocalhost);
8792 if (!allow_localhost)
8793 return;
8794
8795 content::NavigationEntry* entry = GetController().GetLastCommittedEntry();
Rob Wuf79b3ba2018-01-14 01:54:318796 if (!entry || !net::IsLocalhost(entry->GetURL()))
falken52a56e32016-12-08 05:02:408797 return;
8798
8799 content::SSLStatus ssl_status = entry->GetSSL();
Matt Mueller936511442019-09-03 18:15:128800 if (!net::IsCertStatusError(ssl_status.cert_status))
falken52a56e32016-12-08 05:02:408801 return;
8802
8803 GetMainFrame()->AddMessageToConsole(
Abhijeet Kandalkara5928a0a2019-03-13 05:04:428804 blink::mojom::ConsoleMessageLevel::kWarning,
falken52a56e32016-12-08 05:02:408805 base::StringPrintf("This site does not have a valid SSL "
8806 "certificate! Without SSL, your site's and "
8807 "visitors' data is vulnerable to theft and "
8808 "tampering. Get a valid SSL certificate before"
8809 " releasing your website to the public."));
8810}
8811
ekaramadf6750aa2017-06-06 18:29:428812bool WebContentsImpl::IsShowingContextMenuOnPage() const {
8813 return showing_context_menu_;
8814}
8815
Min Qina904f3302018-02-13 23:33:348816download::DownloadUrlParameters::RequestHeadersType
8817WebContentsImpl::ParseDownloadHeaders(const std::string& headers) {
Alexander Timin5fdeff22020-09-08 09:20:378818 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ParseDownloadHeaders",
8819 "headers", headers);
Min Qina904f3302018-02-13 23:33:348820 download::DownloadUrlParameters::RequestHeadersType request_headers;
Megan Jablonski2f6a4c52017-07-10 23:01:258821 for (const base::StringPiece& key_value : base::SplitStringPiece(
8822 headers, "\r\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) {
8823 std::vector<std::string> pair = base::SplitString(
8824 key_value, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
8825 if (2ul == pair.size())
8826 request_headers.push_back(make_pair(pair[0], pair[1]));
8827 }
8828 return request_headers;
8829}
8830
lukasza6f8ac622017-06-06 03:10:208831void WebContentsImpl::SetOpenerForNewContents(FrameTreeNode* opener,
8832 bool opener_suppressed) {
Alexander Timin5fdeff22020-09-08 09:20:378833 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetOpenerForNewContents");
lukasza6f8ac622017-06-06 03:10:208834 if (opener) {
8835 FrameTreeNode* new_root = GetFrameTree()->root();
8836
8837 // For the "original opener", track the opener's main frame instead, because
8838 // if the opener is a subframe, the opener tracking could be easily bypassed
8839 // by spawning from a subframe and deleting the subframe.
8840 // https://crbug.com/705316
8841 new_root->SetOriginalOpener(opener->frame_tree()->root());
8842
8843 if (!opener_suppressed) {
8844 new_root->SetOpener(opener);
8845 created_with_opener_ = true;
8846 }
8847 }
8848}
8849
Mounir Lamouri0f5bdf52019-04-04 16:32:358850void WebContentsImpl::MediaMutedStatusChanged(const MediaPlayerId& id,
8851 bool muted) {
Alexander Timin5fdeff22020-09-08 09:20:378852 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::MediaMutedStatusChanged",
8853 "muted", muted);
Alexander Timin90c20c32020-08-12 15:28:328854 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8855 observer->MediaMutedStatusChanged(id, muted);
8856 });
Becca Hughes9f6fd4b82017-06-15 10:01:408857}
8858
EhsanK2075c7e2017-08-21 02:42:398859void WebContentsImpl::SetVisibilityForChildViews(bool visible) {
Alexander Timin5fdeff22020-09-08 09:20:378860 OPTIONAL_TRACE_EVENT1("content",
8861 "WebContentsImpl::SetVisibilityForChildViews",
8862 "visible", visible);
EhsanK2075c7e2017-08-21 02:42:398863 GetMainFrame()->SetVisibilityForChildViews(visible);
8864}
8865
Alison Maher7f366dc62020-03-03 19:46:008866void WebContentsImpl::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) {
Alexander Timin5fdeff22020-09-08 09:20:378867 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnNativeThemeUpdated");
Alison Maher7f366dc62020-03-03 19:46:008868 DCHECK(native_theme_observer_.IsObserving(observed_theme));
8869
8870 bool using_dark_colors = observed_theme->ShouldUseDarkColors();
8871 ui::NativeTheme::PreferredColorScheme preferred_color_scheme =
8872 observed_theme->GetPreferredColorScheme();
8873 bool preferences_changed = false;
8874
8875 if (using_dark_colors_ != using_dark_colors) {
8876 using_dark_colors_ = using_dark_colors;
8877 preferences_changed = true;
8878 }
8879 if (preferred_color_scheme_ != preferred_color_scheme) {
8880 preferred_color_scheme_ = preferred_color_scheme;
8881 preferences_changed = true;
8882 }
8883
8884 if (preferences_changed)
8885 NotifyPreferencesChanged();
8886}
8887
Dave Tapuska58a099e2020-06-08 21:48:408888blink::mojom::FrameWidgetInputHandler*
8889WebContentsImpl::GetFocusedFrameWidgetInputHandler() {
8890 auto* focused_render_widget_host =
8891 GetFocusedRenderWidgetHost(GetMainFrame()->GetRenderWidgetHost());
8892 if (!focused_render_widget_host)
Dave Tapuskae782bea2019-07-09 16:21:518893 return nullptr;
Dave Tapuska58a099e2020-06-08 21:48:408894 return focused_render_widget_host->GetFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:518895}
8896
Alexander Timine3ec4192020-04-20 16:39:408897ukm::SourceId WebContentsImpl::GetCurrentPageUkmSourceId() {
8898 return GetMainFrame()->GetPageUkmSourceId();
8899}
8900
Yuzu Saijo232076f2020-05-29 07:14:028901std::set<RenderViewHostImpl*>
8902WebContentsImpl::GetRenderViewHostsIncludingBackForwardCached() {
8903 std::set<RenderViewHostImpl*> render_view_hosts;
8904
8905 // Add RenderViewHostImpls outside of BackForwardCache.
8906 for (auto& render_view_host : frame_tree_.render_view_hosts()) {
8907 render_view_hosts.insert(render_view_host.second);
8908 }
8909
8910 // Add RenderViewHostImpls in BackForwardCache.
8911 const auto& entries = GetController().GetBackForwardCache().GetEntries();
8912 for (const auto& entry : entries) {
8913 std::set<RenderViewHostImpl*> bfcached_hosts = entry->render_view_hosts;
8914 render_view_hosts.insert(bfcached_hosts.begin(), bfcached_hosts.end());
8915 }
8916
8917 return render_view_hosts;
8918}
8919
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:508920void WebContentsImpl::RenderFrameHostStateChanged(
8921 RenderFrameHost* render_frame_host,
8922 LifecycleState old_state,
8923 LifecycleState new_state) {
Alexander Timin5fdeff22020-09-08 09:20:378924 OPTIONAL_TRACE_EVENT2(
8925 "content", "WebContentsImpl::RenderFrameHostStateChanged",
8926 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host),
8927 "states",
8928 base::trace_event::TracedValue::Build(
8929 {{"old", base::trace_event::ValueToString(old_state)},
8930 {"new", base::trace_event::ValueToString(new_state)}}));
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:508931 if (render_frame_host->GetParent())
8932 return;
8933
8934 if (old_state == LifecycleState::kActive &&
8935 new_state != LifecycleState::kActive) {
8936 // TODO(sreejakshetty): Remove this reset when ColorChooser becomes
8937 // per-frame.
8938 // Close the color chooser popup when RenderFrameHost changes state from
8939 // kActive.
8940 color_chooser_.reset();
8941 }
8942}
8943
danakjc5ce67602020-09-23 20:06:578944void WebContentsImpl::GetFrameSequenceNumbersForDebugging(
8945 RenderFrameHostImpl* render_frame_host,
8946 int64_t& item_sequence_number,
8947 int64_t& document_sequence_number) {
8948 NavigationEntryImpl* entry =
8949 controller_.GetEntryWithUniqueID(render_frame_host->nav_entry_id());
8950 if (!entry)
8951 return;
8952
8953 FrameNavigationEntry* frame_entry =
8954 entry->GetFrameEntry(render_frame_host->frame_tree_node());
8955 if (frame_entry) {
8956 item_sequence_number = frame_entry->item_sequence_number();
8957 document_sequence_number = frame_entry->document_sequence_number();
8958 }
8959}
8960
[email protected]8ff00d72012-10-23 19:12:218961} // namespace content