electron_api_web_contents.h 35 KB

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