electron_api_web_contents.h 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  1. // Copyright (c) 2014 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_
  5. #define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_
  6. #include <map>
  7. #include <memory>
  8. #include <optional>
  9. #include <string>
  10. #include <vector>
  11. #include "base/functional/callback_forward.h"
  12. #include "base/memory/raw_ptr.h"
  13. #include "base/memory/raw_ptr_exclusion.h"
  14. #include "base/memory/weak_ptr.h"
  15. #include "base/observer_list.h"
  16. #include "base/task/thread_pool.h"
  17. #include "chrome/browser/devtools/devtools_file_system_indexer.h"
  18. #include "chrome/browser/ui/exclusive_access/exclusive_access_context.h" // nogncheck
  19. #include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h"
  20. #include "content/common/frame.mojom-forward.h"
  21. #include "content/public/browser/browser_thread.h"
  22. #include "content/public/browser/devtools_agent_host.h"
  23. #include "content/public/browser/frame_tree_node_id.h"
  24. #include "content/public/browser/javascript_dialog_manager.h"
  25. #include "content/public/browser/render_widget_host.h"
  26. #include "content/public/browser/web_contents_delegate.h"
  27. #include "content/public/browser/web_contents_observer.h"
  28. #include "electron/buildflags/buildflags.h"
  29. #include "gin/handle.h"
  30. #include "gin/wrappable.h"
  31. #include "printing/buildflags/buildflags.h"
  32. #include "shell/browser/api/save_page_handler.h"
  33. #include "shell/browser/background_throttling_source.h"
  34. #include "shell/browser/event_emitter_mixin.h"
  35. #include "shell/browser/extended_web_contents_observer.h"
  36. #include "shell/browser/osr/osr_paint_event.h"
  37. #include "shell/browser/preload_script.h"
  38. #include "shell/browser/ui/inspectable_web_contents_delegate.h"
  39. #include "shell/browser/ui/inspectable_web_contents_view_delegate.h"
  40. #include "shell/common/api/api.mojom.h"
  41. #include "shell/common/gin_helper/cleaned_up_at_exit.h"
  42. #include "shell/common/gin_helper/constructible.h"
  43. #include "shell/common/gin_helper/pinnable.h"
  44. #include "shell/common/web_contents_utility.mojom.h"
  45. #include "ui/base/models/image_model.h"
  46. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  47. #include "extensions/common/mojom/view_type.mojom-forward.h"
  48. namespace extensions {
  49. class ScriptExecutor;
  50. }
  51. #endif
  52. namespace blink {
  53. struct DeviceEmulationParams;
  54. // enum class PermissionType;
  55. } // namespace blink
  56. namespace content {
  57. enum class KeyboardEventProcessingResult;
  58. class WebContents;
  59. } // namespace content
  60. namespace gin {
  61. class Arguments;
  62. }
  63. namespace gin_helper {
  64. class Dictionary;
  65. class ErrorThrower;
  66. template <typename T>
  67. class Promise;
  68. } // namespace gin_helper
  69. namespace network {
  70. class ResourceRequestBody;
  71. }
  72. namespace print_to_pdf {
  73. enum class PdfPrintResult;
  74. } // namespace print_to_pdf
  75. namespace ui {
  76. class Cursor;
  77. }
  78. class DevToolsEyeDropper;
  79. class SkRegion;
  80. namespace electron {
  81. class ElectronBrowserContext;
  82. class InspectableWebContents;
  83. class WebContentsZoomController;
  84. class WebViewGuestDelegate;
  85. class WebDialogHelper;
  86. class NativeWindow;
  87. class OffScreenRenderWidgetHostView;
  88. class OffScreenWebContentsView;
  89. namespace api {
  90. class BaseWindow;
  91. class FrameSubscriber;
  92. // Wrapper around the content::WebContents.
  93. class WebContents final : public ExclusiveAccessContext,
  94. public gin::Wrappable<WebContents>,
  95. public gin_helper::EventEmitterMixin<WebContents>,
  96. public gin_helper::Constructible<WebContents>,
  97. public gin_helper::Pinnable<WebContents>,
  98. public gin_helper::CleanedUpAtExit,
  99. public content::WebContentsObserver,
  100. public content::WebContentsDelegate,
  101. private content::RenderWidgetHost::InputEventObserver,
  102. public content::JavaScriptDialogManager,
  103. public InspectableWebContentsDelegate,
  104. public InspectableWebContentsViewDelegate,
  105. public BackgroundThrottlingSource {
  106. public:
  107. enum class Type {
  108. kBackgroundPage, // An extension background page.
  109. kBrowserWindow, // Used by BrowserWindow.
  110. kBrowserView, // Used by the JS implementation of BrowserView for
  111. // backwards compatibility. Otherwise identical to
  112. // kBrowserWindow.
  113. kRemote, // Thin wrap around an existing WebContents.
  114. kWebView, // Used by <webview>.
  115. kOffScreen, // Used for offscreen rendering
  116. };
  117. // Create a new WebContents and return the V8 wrapper of it.
  118. static gin::Handle<WebContents> New(v8::Isolate* isolate,
  119. const gin_helper::Dictionary& options);
  120. // Create a new V8 wrapper for an existing |web_content|.
  121. //
  122. // The lifetime of |web_contents| will be managed by this class.
  123. static gin::Handle<WebContents> CreateAndTake(
  124. v8::Isolate* isolate,
  125. std::unique_ptr<content::WebContents> web_contents,
  126. Type type);
  127. // Get the api::WebContents associated with |web_contents|. Returns nullptr
  128. // if there is no associated wrapper.
  129. static WebContents* From(content::WebContents* web_contents);
  130. static WebContents* FromID(int32_t id);
  131. static std::list<WebContents*> GetWebContentsList();
  132. // Whether to disable draggable regions globally. This can be used to allow
  133. // events to skip client region hit tests.
  134. static void SetDisableDraggableRegions(bool disable);
  135. // Get the V8 wrapper of the |web_contents|, or create one if not existed.
  136. //
  137. // The lifetime of |web_contents| is NOT managed by this class, and the type
  138. // of this wrapper is always REMOTE.
  139. static gin::Handle<WebContents> FromOrCreate(
  140. v8::Isolate* isolate,
  141. content::WebContents* web_contents);
  142. static gin::Handle<WebContents> CreateFromWebPreferences(
  143. v8::Isolate* isolate,
  144. const gin_helper::Dictionary& web_preferences);
  145. // gin_helper::Constructible
  146. static void FillObjectTemplate(v8::Isolate*, v8::Local<v8::ObjectTemplate>);
  147. static const char* GetClassName() { return "WebContents"; }
  148. // gin::Wrappable
  149. static gin::WrapperInfo kWrapperInfo;
  150. const char* GetTypeName() override;
  151. // gin_helper::CleanedUpAtExit
  152. void WillBeDestroyed() override;
  153. void Destroy();
  154. void Close(std::optional<gin_helper::Dictionary> options);
  155. base::WeakPtr<WebContents> GetWeakPtr() { return weak_factory_.GetWeakPtr(); }
  156. // BackgroundThrottlingSource
  157. bool GetBackgroundThrottling() const override;
  158. void SetBackgroundThrottling(bool allowed);
  159. int32_t GetProcessID() const;
  160. base::ProcessId GetOSProcessID() const;
  161. [[nodiscard]] Type type() const { return type_; }
  162. bool Equal(const WebContents* web_contents) const;
  163. void LoadURL(const GURL& url, const gin_helper::Dictionary& options);
  164. void Reload();
  165. void ReloadIgnoringCache();
  166. void DownloadURL(const GURL& url, gin::Arguments* args);
  167. GURL GetURL() const;
  168. std::u16string GetTitle() const;
  169. bool IsLoading() const;
  170. bool IsLoadingMainFrame() const;
  171. bool IsWaitingForResponse() const;
  172. void Stop();
  173. bool CanGoBack() const;
  174. void GoBack();
  175. bool CanGoForward() const;
  176. void GoForward();
  177. bool CanGoToOffset(int offset) const;
  178. void GoToOffset(int offset);
  179. bool CanGoToIndex(int index) const;
  180. void GoToIndex(int index);
  181. int GetActiveIndex() const;
  182. content::NavigationEntry* GetNavigationEntryAtIndex(int index) const;
  183. bool RemoveNavigationEntryAtIndex(int index);
  184. std::vector<content::NavigationEntry*> GetHistory() const;
  185. void ClearHistory();
  186. void RestoreHistory(v8::Isolate* isolate,
  187. gin_helper::ErrorThrower thrower,
  188. int index,
  189. const std::vector<v8::Local<v8::Value>>& entries);
  190. int GetHistoryLength() const;
  191. const std::string GetWebRTCIPHandlingPolicy() const;
  192. void SetWebRTCIPHandlingPolicy(const std::string& webrtc_ip_handling_policy);
  193. v8::Local<v8::Value> GetWebRTCUDPPortRange(v8::Isolate* isolate) const;
  194. void SetWebRTCUDPPortRange(gin::Arguments* args);
  195. std::string GetMediaSourceID(content::WebContents* request_web_contents);
  196. bool IsCrashed() const;
  197. void ForcefullyCrashRenderer();
  198. void SetUserAgent(const std::string& user_agent);
  199. std::string GetUserAgent();
  200. void InsertCSS(const std::string& css);
  201. v8::Local<v8::Promise> SavePage(const base::FilePath& full_file_path,
  202. const content::SavePageType& save_type);
  203. void OpenDevTools(gin::Arguments* args);
  204. void CloseDevTools();
  205. bool IsDevToolsOpened();
  206. bool IsDevToolsFocused();
  207. std::u16string GetDevToolsTitle();
  208. void SetDevToolsTitle(const std::u16string& title);
  209. void ToggleDevTools();
  210. void EnableDeviceEmulation(const blink::DeviceEmulationParams& params);
  211. void DisableDeviceEmulation();
  212. void InspectElement(int x, int y);
  213. void InspectSharedWorker();
  214. void InspectSharedWorkerById(const std::string& workerId);
  215. std::vector<scoped_refptr<content::DevToolsAgentHost>> GetAllSharedWorkers();
  216. void InspectServiceWorker();
  217. void SetIgnoreMenuShortcuts(bool ignore);
  218. void SetAudioMuted(bool muted);
  219. bool IsAudioMuted();
  220. bool IsCurrentlyAudible();
  221. void SetEmbedder(const WebContents* embedder);
  222. void SetDevToolsWebContents(const WebContents* devtools);
  223. v8::Local<v8::Value> GetNativeView(v8::Isolate* isolate) const;
  224. bool IsBeingCaptured();
  225. void HandleNewRenderFrame(content::RenderFrameHost* render_frame_host);
  226. #if BUILDFLAG(ENABLE_PRINTING)
  227. void Print(gin::Arguments* args);
  228. // Print current page as PDF.
  229. v8::Local<v8::Promise> PrintToPDF(const base::Value& settings);
  230. #endif
  231. void SetNextChildWebPreferences(const gin_helper::Dictionary);
  232. // DevTools workspace api.
  233. void AddWorkSpace(gin::Arguments* args, const base::FilePath& path);
  234. void RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path);
  235. // Editing commands.
  236. void Undo();
  237. void Redo();
  238. void Cut();
  239. void Copy();
  240. void CenterSelection();
  241. void Paste();
  242. void PasteAndMatchStyle();
  243. void Delete();
  244. void SelectAll();
  245. void Unselect();
  246. void ScrollToTopOfDocument();
  247. void ScrollToBottomOfDocument();
  248. void AdjustSelectionByCharacterOffset(gin::Arguments* args);
  249. void Replace(const std::u16string& word);
  250. void ReplaceMisspelling(const std::u16string& word);
  251. uint32_t FindInPage(gin::Arguments* args);
  252. void StopFindInPage(content::StopFindAction action);
  253. void ShowDefinitionForSelection();
  254. void CopyImageAt(int x, int y);
  255. // Focus.
  256. void Focus();
  257. bool IsFocused() const;
  258. // Send WebInputEvent to the page.
  259. void SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event);
  260. // Subscribe to the frame updates.
  261. void BeginFrameSubscription(gin::Arguments* args);
  262. void EndFrameSubscription();
  263. // Dragging native items.
  264. void StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args);
  265. // Captures the page with |rect|, |callback| would be called when capturing is
  266. // done.
  267. v8::Local<v8::Promise> CapturePage(gin::Arguments* args);
  268. // Methods for creating <webview>.
  269. [[nodiscard]] bool is_guest() const { return type_ == Type::kWebView; }
  270. void AttachToIframe(content::WebContents* embedder_web_contents,
  271. int embedder_frame_id);
  272. void DetachFromOuterFrame();
  273. // Methods for offscreen rendering
  274. bool IsOffScreen() const;
  275. void OnPaint(const gfx::Rect& dirty_rect,
  276. const SkBitmap& bitmap,
  277. const OffscreenSharedTexture& info);
  278. void StartPainting();
  279. void StopPainting();
  280. bool IsPainting() const;
  281. void SetFrameRate(int frame_rate);
  282. int GetFrameRate() const;
  283. void Invalidate();
  284. gfx::Size GetSizeForNewRenderView(content::WebContents*) override;
  285. // Methods for zoom handling.
  286. void SetZoomLevel(double level);
  287. double GetZoomLevel() const;
  288. void SetZoomFactor(gin_helper::ErrorThrower thrower, double factor);
  289. double GetZoomFactor() const;
  290. // Callback triggered on permission response.
  291. void OnEnterFullscreenModeForTab(
  292. content::RenderFrameHost* requesting_frame,
  293. const blink::mojom::FullscreenOptions& options,
  294. bool allowed);
  295. // Create window with the given disposition.
  296. void OnCreateWindow(const GURL& target_url,
  297. const content::Referrer& referrer,
  298. const std::string& frame_name,
  299. WindowOpenDisposition disposition,
  300. const std::string& features,
  301. const scoped_refptr<network::ResourceRequestBody>& body);
  302. // Returns the preload script of current WebContents.
  303. std::optional<PreloadScript> GetPreloadScript() const;
  304. // Returns the web preferences of current WebContents.
  305. v8::Local<v8::Value> GetLastWebPreferences(v8::Isolate* isolate) const;
  306. // Returns the owner window.
  307. v8::Local<v8::Value> GetOwnerBrowserWindow(v8::Isolate* isolate) const;
  308. // Notifies the web page that there is user interaction.
  309. void NotifyUserActivation();
  310. v8::Local<v8::Promise> TakeHeapSnapshot(v8::Isolate* isolate,
  311. const base::FilePath& file_path);
  312. v8::Local<v8::Promise> GetProcessMemoryInfo(v8::Isolate* isolate);
  313. // content::WebContentsDelegate:
  314. bool HandleContextMenu(content::RenderFrameHost& render_frame_host,
  315. const content::ContextMenuParams& params) override;
  316. // Properties.
  317. int32_t ID() const { return id_; }
  318. v8::Local<v8::Value> Session(v8::Isolate* isolate);
  319. content::WebContents* HostWebContents() const;
  320. v8::Local<v8::Value> DevToolsWebContents(v8::Isolate* isolate);
  321. v8::Local<v8::Value> Debugger(v8::Isolate* isolate);
  322. content::RenderFrameHost* MainFrame();
  323. content::RenderFrameHost* Opener();
  324. content::RenderFrameHost* FocusedFrame();
  325. WebContentsZoomController* GetZoomController() { return zoom_controller_; }
  326. void AddObserver(ExtendedWebContentsObserver* obs) {
  327. observers_.AddObserver(obs);
  328. }
  329. void RemoveObserver(ExtendedWebContentsObserver* obs) {
  330. // Trying to remove from an empty collection leads to an access violation
  331. if (!observers_.empty())
  332. observers_.RemoveObserver(obs);
  333. }
  334. bool EmitNavigationEvent(const std::string& event,
  335. content::NavigationHandle* navigation_handle);
  336. WebContents* embedder() { return embedder_; }
  337. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  338. extensions::ScriptExecutor* script_executor() {
  339. return script_executor_.get();
  340. }
  341. #endif
  342. // Set the window as owner window.
  343. void SetOwnerWindow(NativeWindow* owner_window);
  344. void SetOwnerWindow(content::WebContents* web_contents,
  345. NativeWindow* owner_window);
  346. void SetOwnerBaseWindow(std::optional<BaseWindow*> owner_window);
  347. // Returns the WebContents managed by this delegate.
  348. content::WebContents* GetWebContents() const;
  349. // Returns the WebContents of devtools.
  350. content::WebContents* GetDevToolsWebContents() const;
  351. InspectableWebContents* inspectable_web_contents() const {
  352. return inspectable_web_contents_.get();
  353. }
  354. NativeWindow* owner_window() const { return owner_window_.get(); }
  355. bool is_html_fullscreen() const { return html_fullscreen_; }
  356. void set_fullscreen_frame(content::RenderFrameHost* rfh) {
  357. fullscreen_frame_ = rfh;
  358. }
  359. // mojom::ElectronWebContentsUtility
  360. void OnFirstNonEmptyLayout(content::RenderFrameHost* render_frame_host);
  361. void SetTemporaryZoomLevel(double level);
  362. void SetImageAnimationPolicy(const std::string& new_policy);
  363. // content::RenderWidgetHost::InputEventObserver:
  364. void OnInputEvent(const content::RenderWidgetHost& rfh,
  365. const blink::WebInputEvent& event) override;
  366. // content::JavaScriptDialogManager:
  367. void RunJavaScriptDialog(content::WebContents* web_contents,
  368. content::RenderFrameHost* rfh,
  369. content::JavaScriptDialogType dialog_type,
  370. const std::u16string& message_text,
  371. const std::u16string& default_prompt_text,
  372. DialogClosedCallback callback,
  373. bool* did_suppress_message) override;
  374. void RunBeforeUnloadDialog(content::WebContents* web_contents,
  375. content::RenderFrameHost* rfh,
  376. bool is_reload,
  377. DialogClosedCallback callback) override;
  378. void CancelDialogs(content::WebContents* web_contents,
  379. bool reset_state) override;
  380. void SetBackgroundColor(std::optional<SkColor> color);
  381. void PDFReadyToPrint();
  382. SkRegion* draggable_region();
  383. // disable copy
  384. WebContents(const WebContents&) = delete;
  385. WebContents& operator=(const WebContents&) = delete;
  386. private:
  387. // Does not manage lifetime of |web_contents|.
  388. WebContents(v8::Isolate* isolate, content::WebContents* web_contents);
  389. // Takes over ownership of |web_contents|.
  390. WebContents(v8::Isolate* isolate,
  391. std::unique_ptr<content::WebContents> web_contents,
  392. Type type);
  393. // Creates a new content::WebContents.
  394. WebContents(v8::Isolate* isolate, const gin_helper::Dictionary& options);
  395. ~WebContents() override;
  396. // Delete this if garbage collection has not started.
  397. void DeleteThisIfAlive();
  398. // Creates a InspectableWebContents object and takes ownership of
  399. // |web_contents|.
  400. void InitWithWebContents(std::unique_ptr<content::WebContents> web_contents,
  401. ElectronBrowserContext* browser_context,
  402. bool is_guest);
  403. void InitWithSessionAndOptions(
  404. v8::Isolate* isolate,
  405. std::unique_ptr<content::WebContents> web_contents,
  406. gin::Handle<class Session> session,
  407. const gin_helper::Dictionary& options);
  408. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  409. void InitWithExtensionView(v8::Isolate* isolate,
  410. content::WebContents* web_contents,
  411. extensions::mojom::ViewType view_type);
  412. #endif
  413. // content::WebContentsDelegate:
  414. bool IsWebContentsCreationOverridden(
  415. content::SiteInstance* source_site_instance,
  416. content::mojom::WindowContainerType window_container_type,
  417. const GURL& opener_url,
  418. const content::mojom::CreateNewWindowParams& params) override;
  419. content::WebContents* CreateCustomWebContents(
  420. content::RenderFrameHost* opener,
  421. content::SiteInstance* source_site_instance,
  422. bool is_new_browsing_instance,
  423. const GURL& opener_url,
  424. const std::string& frame_name,
  425. const GURL& target_url,
  426. const content::StoragePartitionConfig& partition_config,
  427. content::SessionStorageNamespace* session_storage_namespace) override;
  428. void WebContentsCreatedWithFullParams(
  429. content::WebContents* source_contents,
  430. int opener_render_process_id,
  431. int opener_render_frame_id,
  432. const content::mojom::CreateNewWindowParams& params,
  433. content::WebContents* new_contents) override;
  434. content::WebContents* AddNewContents(
  435. content::WebContents* source,
  436. std::unique_ptr<content::WebContents> new_contents,
  437. const GURL& target_url,
  438. WindowOpenDisposition disposition,
  439. const blink::mojom::WindowFeatures& window_features,
  440. bool user_gesture,
  441. bool* was_blocked) override;
  442. content::WebContents* OpenURLFromTab(
  443. content::WebContents* source,
  444. const content::OpenURLParams& params,
  445. base::OnceCallback<void(content::NavigationHandle&)>
  446. navigation_handle_callback) override;
  447. void BeforeUnloadFired(content::WebContents* tab,
  448. bool proceed,
  449. bool* proceed_to_fire_unload) override;
  450. void SetContentsBounds(content::WebContents* source,
  451. const gfx::Rect& pos) override;
  452. void CloseContents(content::WebContents* source) override;
  453. void ActivateContents(content::WebContents* contents) override;
  454. void UpdateTargetURL(content::WebContents* source, const GURL& url) override;
  455. bool HandleKeyboardEvent(content::WebContents* source,
  456. const input::NativeWebKeyboardEvent& event) override;
  457. bool PlatformHandleKeyboardEvent(content::WebContents* source,
  458. const input::NativeWebKeyboardEvent& event);
  459. content::KeyboardEventProcessingResult PreHandleKeyboardEvent(
  460. content::WebContents* source,
  461. const input::NativeWebKeyboardEvent& event) override;
  462. void ContentsZoomChange(bool zoom_in) override;
  463. void EnterFullscreenModeForTab(
  464. content::RenderFrameHost* requesting_frame,
  465. const blink::mojom::FullscreenOptions& options) override;
  466. void ExitFullscreenModeForTab(content::WebContents* source) override;
  467. void RendererUnresponsive(
  468. content::WebContents* source,
  469. content::RenderWidgetHost* render_widget_host,
  470. base::RepeatingClosure hang_monitor_restarter) override;
  471. void RendererResponsive(
  472. content::WebContents* source,
  473. content::RenderWidgetHost* render_widget_host) override;
  474. void FindReply(content::WebContents* web_contents,
  475. int request_id,
  476. int number_of_matches,
  477. const gfx::Rect& selection_rect,
  478. int active_match_ordinal,
  479. bool final_update) override;
  480. void OnRequestPointerLock(content::WebContents* web_contents,
  481. bool user_gesture,
  482. bool last_unlocked_by_target,
  483. bool allowed);
  484. void RequestPointerLock(content::WebContents* web_contents,
  485. bool user_gesture,
  486. bool last_unlocked_by_target) override;
  487. void LostPointerLock() override;
  488. bool IsWaitingForPointerLockPrompt(
  489. content::WebContents* web_contents) override;
  490. void OnRequestKeyboardLock(content::WebContents* web_contents,
  491. bool esc_key_locked,
  492. bool allowed);
  493. void RequestKeyboardLock(content::WebContents* web_contents,
  494. bool esc_key_locked) override;
  495. void CancelKeyboardLockRequest(content::WebContents* web_contents) override;
  496. bool CheckMediaAccessPermission(content::RenderFrameHost* render_frame_host,
  497. const url::Origin& security_origin,
  498. blink::mojom::MediaStreamType type) override;
  499. void RequestMediaAccessPermission(
  500. content::WebContents* web_contents,
  501. const content::MediaStreamRequest& request,
  502. content::MediaResponseCallback callback) override;
  503. content::JavaScriptDialogManager* GetJavaScriptDialogManager(
  504. content::WebContents* source) override;
  505. void OnAudioStateChanged(bool audible) override;
  506. void UpdatePreferredSize(content::WebContents* web_contents,
  507. const gfx::Size& pref_size) override;
  508. void DraggableRegionsChanged(
  509. const std::vector<blink::mojom::DraggableRegionPtr>& regions,
  510. content::WebContents* contents) override;
  511. void PrintCrossProcessSubframe(
  512. content::WebContents* web_contents,
  513. const gfx::Rect& rect,
  514. int document_cookie,
  515. content::RenderFrameHost* subframe_host) const override;
  516. // content::WebContentsObserver:
  517. void BeforeUnloadFired(bool proceed) override;
  518. void OnBackgroundColorChanged() override;
  519. void RenderFrameCreated(content::RenderFrameHost* render_frame_host) override;
  520. void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override;
  521. void RenderFrameHostChanged(content::RenderFrameHost* old_host,
  522. content::RenderFrameHost* new_host) override;
  523. void FrameDeleted(content::FrameTreeNodeId frame_tree_node_id) override;
  524. void RenderViewDeleted(content::RenderViewHost*) override;
  525. void PrimaryMainFrameRenderProcessGone(
  526. base::TerminationStatus status) override;
  527. void DOMContentLoaded(content::RenderFrameHost* render_frame_host) override;
  528. void DidFinishLoad(content::RenderFrameHost* render_frame_host,
  529. const GURL& validated_url) override;
  530. void DidFailLoad(content::RenderFrameHost* render_frame_host,
  531. const GURL& validated_url,
  532. int error_code) override;
  533. void DidStartLoading() override;
  534. void DidStopLoading() override;
  535. void DidStartNavigation(
  536. content::NavigationHandle* navigation_handle) override;
  537. void DidRedirectNavigation(
  538. content::NavigationHandle* navigation_handle) override;
  539. void ReadyToCommitNavigation(
  540. content::NavigationHandle* navigation_handle) override;
  541. void DidFinishNavigation(
  542. content::NavigationHandle* navigation_handle) override;
  543. void WebContentsDestroyed() override;
  544. void NavigationEntryCommitted(
  545. const content::LoadCommittedDetails& load_details) override;
  546. void TitleWasSet(content::NavigationEntry* entry) override;
  547. void DidUpdateFaviconURL(
  548. content::RenderFrameHost* render_frame_host,
  549. const std::vector<blink::mojom::FaviconURLPtr>& urls) override;
  550. void PluginCrashed(const base::FilePath& plugin_path,
  551. base::ProcessId plugin_pid) override;
  552. void MediaStartedPlaying(const MediaPlayerInfo& video_type,
  553. const content::MediaPlayerId& id) override;
  554. void MediaStoppedPlaying(
  555. const MediaPlayerInfo& video_type,
  556. const content::MediaPlayerId& id,
  557. content::WebContentsObserver::MediaStoppedReason reason) override;
  558. void DidChangeThemeColor() override;
  559. void OnCursorChanged(const ui::Cursor& cursor) override;
  560. void DidAcquireFullscreen(content::RenderFrameHost* rfh) override;
  561. void OnWebContentsFocused(
  562. content::RenderWidgetHost* render_widget_host) override;
  563. void OnWebContentsLostFocus(
  564. content::RenderWidgetHost* render_widget_host) override;
  565. void OnDidAddMessageToConsole(
  566. content::RenderFrameHost* source_frame,
  567. blink::mojom::ConsoleMessageLevel level,
  568. const std::u16string& message,
  569. int32_t line_no,
  570. const std::u16string& source_id,
  571. const std::optional<std::u16string>& untrusted_stack_trace) override;
  572. // InspectableWebContentsDelegate:
  573. void DevToolsReloadPage() override;
  574. // InspectableWebContentsViewDelegate:
  575. void DevToolsFocused() override;
  576. void DevToolsOpened() override;
  577. void DevToolsClosed() override;
  578. void DevToolsResized() override;
  579. ElectronBrowserContext* GetBrowserContext() const;
  580. void OnElectronBrowserConnectionError();
  581. OffScreenWebContentsView* GetOffScreenWebContentsView() const;
  582. OffScreenRenderWidgetHostView* GetOffScreenRenderWidgetHostView() const;
  583. // Called when received a synchronous message from renderer to
  584. // get the zoom level.
  585. void OnGetZoomLevel(content::RenderFrameHost* frame_host,
  586. IPC::Message* reply_msg);
  587. void InitZoomController(content::WebContents* web_contents,
  588. const gin_helper::Dictionary& options);
  589. // content::WebContentsDelegate:
  590. bool CanOverscrollContent() override;
  591. std::unique_ptr<content::EyeDropper> OpenEyeDropper(
  592. content::RenderFrameHost* frame,
  593. content::EyeDropperListener* listener) override;
  594. void RunFileChooser(content::RenderFrameHost* render_frame_host,
  595. scoped_refptr<content::FileSelectListener> listener,
  596. const blink::mojom::FileChooserParams& params) override;
  597. void EnumerateDirectory(content::WebContents* web_contents,
  598. scoped_refptr<content::FileSelectListener> listener,
  599. const base::FilePath& path) override;
  600. // ExclusiveAccessContext:
  601. Profile* GetProfile() override;
  602. bool IsFullscreen() const override;
  603. void EnterFullscreen(const url::Origin& origin,
  604. ExclusiveAccessBubbleType bubble_type,
  605. const int64_t display_id) override;
  606. void ExitFullscreen() override {}
  607. void UpdateExclusiveAccessBubble(
  608. const ExclusiveAccessBubbleParams& params,
  609. ExclusiveAccessBubbleHideCallback bubble_first_hide_callback) override {}
  610. void OnExclusiveAccessUserInput() override {}
  611. content::WebContents* GetWebContentsForExclusiveAccess() override;
  612. bool CanUserEnterFullscreen() const override;
  613. bool CanUserExitFullscreen() const override;
  614. bool IsExclusiveAccessBubbleDisplayed() const override;
  615. // content::WebContentsDelegate
  616. bool IsFullscreenForTabOrPending(const content::WebContents* source) override;
  617. content::FullscreenState GetFullscreenState(
  618. const content::WebContents* web_contents) const override;
  619. bool TakeFocus(content::WebContents* source, bool reverse) override;
  620. content::PictureInPictureResult EnterPictureInPicture(
  621. content::WebContents* web_contents) override;
  622. void ExitPictureInPicture() override;
  623. // InspectableWebContentsDelegate:
  624. void DevToolsSaveToFile(const std::string& url,
  625. const std::string& content,
  626. bool save_as,
  627. bool is_base64) override;
  628. void DevToolsAppendToFile(const std::string& url,
  629. const std::string& content) override;
  630. void DevToolsRequestFileSystems() override;
  631. void DevToolsAddFileSystem(const std::string& type,
  632. const base::FilePath& file_system_path) override;
  633. void DevToolsRemoveFileSystem(
  634. const base::FilePath& file_system_path) override;
  635. void DevToolsIndexPath(int request_id,
  636. const std::string& file_system_path,
  637. const std::string& excluded_folders_message) override;
  638. void DevToolsOpenInNewTab(const std::string& url) override;
  639. void DevToolsOpenSearchResultsInNewTab(const std::string& query) override;
  640. void DevToolsStopIndexing(int request_id) override;
  641. void DevToolsSearchInPath(int request_id,
  642. const std::string& file_system_path,
  643. const std::string& query) override;
  644. void DevToolsSetEyeDropperActive(bool active) override;
  645. // InspectableWebContentsViewDelegate:
  646. #if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC)
  647. ui::ImageModel GetDevToolsWindowIcon() override;
  648. #endif
  649. #if BUILDFLAG(IS_LINUX)
  650. void GetDevToolsWindowWMClass(std::string* name,
  651. std::string* class_name) override;
  652. #endif
  653. void ColorPickedInEyeDropper(int r, int g, int b, int a);
  654. // DevTools index event callbacks.
  655. void OnDevToolsIndexingWorkCalculated(int request_id,
  656. const std::string& file_system_path,
  657. int total_work);
  658. void OnDevToolsIndexingWorked(int request_id,
  659. const std::string& file_system_path,
  660. int worked);
  661. void OnDevToolsIndexingDone(int request_id,
  662. const std::string& file_system_path);
  663. void OnDevToolsSearchCompleted(int request_id,
  664. const std::string& file_system_path,
  665. const std::vector<std::string>& file_paths);
  666. // Set fullscreen mode triggered by html api.
  667. void SetHtmlApiFullscreen(bool enter_fullscreen);
  668. // Update the html fullscreen flag in both browser and renderer.
  669. void UpdateHtmlApiFullscreen(bool fullscreen);
  670. v8::Global<v8::Value> session_;
  671. v8::Global<v8::Value> devtools_web_contents_;
  672. v8::Global<v8::Value> debugger_;
  673. std::unique_ptr<WebViewGuestDelegate> guest_delegate_;
  674. std::unique_ptr<FrameSubscriber> frame_subscriber_;
  675. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  676. std::unique_ptr<extensions::ScriptExecutor> script_executor_;
  677. #endif
  678. // The host webcontents that may contain this webcontents.
  679. RAW_PTR_EXCLUSION WebContents* embedder_ = nullptr;
  680. // Whether the guest view has been attached.
  681. bool attached_ = false;
  682. // The type of current WebContents.
  683. Type type_ = Type::kBrowserWindow;
  684. // Weather the guest view should be transparent
  685. bool guest_transparent_ = true;
  686. int32_t id_;
  687. // Request id used for findInPage request.
  688. uint32_t find_in_page_request_id_ = 0;
  689. // Whether background throttling is disabled.
  690. bool background_throttling_ = true;
  691. // Whether to enable devtools.
  692. bool enable_devtools_ = true;
  693. // Observers of this WebContents.
  694. base::ObserverList<ExtendedWebContentsObserver> observers_;
  695. v8::Global<v8::Value> pending_child_web_preferences_;
  696. // The window that this WebContents belongs to.
  697. base::WeakPtr<NativeWindow> owner_window_;
  698. bool offscreen_ = false;
  699. // Whether offscreen rendering use gpu shared texture
  700. bool offscreen_use_shared_texture_ = false;
  701. // Whether window is fullscreened by HTML5 api.
  702. bool html_fullscreen_ = false;
  703. // Whether window is fullscreened by window api.
  704. bool native_fullscreen_ = false;
  705. const scoped_refptr<DevToolsFileSystemIndexer> devtools_file_system_indexer_ =
  706. base::MakeRefCounted<DevToolsFileSystemIndexer>();
  707. ExclusiveAccessManager exclusive_access_manager_{this};
  708. std::unique_ptr<DevToolsEyeDropper> eye_dropper_;
  709. raw_ptr<ElectronBrowserContext> browser_context_;
  710. // The stored InspectableWebContents object.
  711. // Notice that inspectable_web_contents_ must be placed after
  712. // dialog_manager_, so we can make sure inspectable_web_contents_ is
  713. // destroyed before dialog_manager_, otherwise a crash would happen.
  714. std::unique_ptr<InspectableWebContents> inspectable_web_contents_;
  715. // The zoom controller for this webContents.
  716. // Note: owned by inspectable_web_contents_, so declare this *after*
  717. // that field to ensure the dtor destroys them in the right order.
  718. raw_ptr<WebContentsZoomController> zoom_controller_ = nullptr;
  719. // Maps url to file path, used by the file requests sent from devtools.
  720. typedef std::map<std::string, base::FilePath> PathsMap;
  721. PathsMap saved_files_;
  722. // Map id to index job, used for file system indexing requests from devtools.
  723. typedef std::
  724. map<int, scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>>
  725. DevToolsIndexingJobsMap;
  726. DevToolsIndexingJobsMap devtools_indexing_jobs_;
  727. const scoped_refptr<base::SequencedTaskRunner> file_task_runner_ =
  728. base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()});
  729. #if BUILDFLAG(ENABLE_PRINTING)
  730. const scoped_refptr<base::TaskRunner> print_task_runner_;
  731. #endif
  732. // Stores the frame that's currently in fullscreen, nullptr if there is none.
  733. raw_ptr<content::RenderFrameHost> fullscreen_frame_ = nullptr;
  734. std::unique_ptr<SkRegion> draggable_region_;
  735. base::WeakPtrFactory<WebContents> weak_factory_{this};
  736. };
  737. } // namespace api
  738. } // namespace electron
  739. #endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_