electron_api_web_contents.h 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  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 blink::WebInputEvent& event) override;
  400. // content::JavaScriptDialogManager:
  401. void RunJavaScriptDialog(content::WebContents* web_contents,
  402. content::RenderFrameHost* rfh,
  403. content::JavaScriptDialogType dialog_type,
  404. const std::u16string& message_text,
  405. const std::u16string& default_prompt_text,
  406. DialogClosedCallback callback,
  407. bool* did_suppress_message) override;
  408. void RunBeforeUnloadDialog(content::WebContents* web_contents,
  409. content::RenderFrameHost* rfh,
  410. bool is_reload,
  411. DialogClosedCallback callback) override;
  412. void CancelDialogs(content::WebContents* web_contents,
  413. bool reset_state) override;
  414. void SetBackgroundColor(std::optional<SkColor> color);
  415. void PDFReadyToPrint();
  416. SkRegion* draggable_region() {
  417. return force_non_draggable_ ? nullptr : draggable_region_.get();
  418. }
  419. void SetForceNonDraggable(bool force_non_draggable) {
  420. force_non_draggable_ = force_non_draggable;
  421. }
  422. // disable copy
  423. WebContents(const WebContents&) = delete;
  424. WebContents& operator=(const WebContents&) = delete;
  425. private:
  426. // Does not manage lifetime of |web_contents|.
  427. WebContents(v8::Isolate* isolate, content::WebContents* web_contents);
  428. // Takes over ownership of |web_contents|.
  429. WebContents(v8::Isolate* isolate,
  430. std::unique_ptr<content::WebContents> web_contents,
  431. Type type);
  432. // Creates a new content::WebContents.
  433. WebContents(v8::Isolate* isolate, const gin_helper::Dictionary& options);
  434. ~WebContents() override;
  435. // Delete this if garbage collection has not started.
  436. void DeleteThisIfAlive();
  437. // Creates a InspectableWebContents object and takes ownership of
  438. // |web_contents|.
  439. void InitWithWebContents(std::unique_ptr<content::WebContents> web_contents,
  440. ElectronBrowserContext* browser_context,
  441. bool is_guest);
  442. void InitWithSessionAndOptions(
  443. v8::Isolate* isolate,
  444. std::unique_ptr<content::WebContents> web_contents,
  445. gin::Handle<class Session> session,
  446. const gin_helper::Dictionary& options);
  447. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  448. void InitWithExtensionView(v8::Isolate* isolate,
  449. content::WebContents* web_contents,
  450. extensions::mojom::ViewType view_type);
  451. #endif
  452. // content::WebContentsDelegate:
  453. bool IsWebContentsCreationOverridden(
  454. content::SiteInstance* source_site_instance,
  455. content::mojom::WindowContainerType window_container_type,
  456. const GURL& opener_url,
  457. const content::mojom::CreateNewWindowParams& params) override;
  458. content::WebContents* CreateCustomWebContents(
  459. content::RenderFrameHost* opener,
  460. content::SiteInstance* source_site_instance,
  461. bool is_new_browsing_instance,
  462. const GURL& opener_url,
  463. const std::string& frame_name,
  464. const GURL& target_url,
  465. const content::StoragePartitionConfig& partition_config,
  466. content::SessionStorageNamespace* session_storage_namespace) override;
  467. void WebContentsCreatedWithFullParams(
  468. content::WebContents* source_contents,
  469. int opener_render_process_id,
  470. int opener_render_frame_id,
  471. const content::mojom::CreateNewWindowParams& params,
  472. content::WebContents* new_contents) override;
  473. content::WebContents* AddNewContents(
  474. content::WebContents* source,
  475. std::unique_ptr<content::WebContents> new_contents,
  476. const GURL& target_url,
  477. WindowOpenDisposition disposition,
  478. const blink::mojom::WindowFeatures& window_features,
  479. bool user_gesture,
  480. bool* was_blocked) override;
  481. content::WebContents* OpenURLFromTab(
  482. content::WebContents* source,
  483. const content::OpenURLParams& params,
  484. base::OnceCallback<void(content::NavigationHandle&)>
  485. navigation_handle_callback) override;
  486. void BeforeUnloadFired(content::WebContents* tab,
  487. bool proceed,
  488. bool* proceed_to_fire_unload) override;
  489. void SetContentsBounds(content::WebContents* source,
  490. const gfx::Rect& pos) override;
  491. void CloseContents(content::WebContents* source) override;
  492. void ActivateContents(content::WebContents* contents) override;
  493. void UpdateTargetURL(content::WebContents* source, const GURL& url) override;
  494. bool HandleKeyboardEvent(content::WebContents* source,
  495. const input::NativeWebKeyboardEvent& event) override;
  496. bool PlatformHandleKeyboardEvent(content::WebContents* source,
  497. const input::NativeWebKeyboardEvent& event);
  498. content::KeyboardEventProcessingResult PreHandleKeyboardEvent(
  499. content::WebContents* source,
  500. const input::NativeWebKeyboardEvent& event) override;
  501. void ContentsZoomChange(bool zoom_in) override;
  502. void EnterFullscreenModeForTab(
  503. content::RenderFrameHost* requesting_frame,
  504. const blink::mojom::FullscreenOptions& options) override;
  505. void ExitFullscreenModeForTab(content::WebContents* source) override;
  506. void RendererUnresponsive(
  507. content::WebContents* source,
  508. content::RenderWidgetHost* render_widget_host,
  509. base::RepeatingClosure hang_monitor_restarter) override;
  510. void RendererResponsive(
  511. content::WebContents* source,
  512. content::RenderWidgetHost* render_widget_host) override;
  513. void FindReply(content::WebContents* web_contents,
  514. int request_id,
  515. int number_of_matches,
  516. const gfx::Rect& selection_rect,
  517. int active_match_ordinal,
  518. bool final_update) override;
  519. void OnRequestPointerLock(content::WebContents* web_contents,
  520. bool user_gesture,
  521. bool last_unlocked_by_target,
  522. bool allowed);
  523. void RequestPointerLock(content::WebContents* web_contents,
  524. bool user_gesture,
  525. bool last_unlocked_by_target) override;
  526. void LostPointerLock() override;
  527. void OnRequestKeyboardLock(content::WebContents* web_contents,
  528. bool esc_key_locked,
  529. bool allowed);
  530. void RequestKeyboardLock(content::WebContents* web_contents,
  531. bool esc_key_locked) override;
  532. void CancelKeyboardLockRequest(content::WebContents* web_contents) override;
  533. bool CheckMediaAccessPermission(content::RenderFrameHost* render_frame_host,
  534. const url::Origin& security_origin,
  535. blink::mojom::MediaStreamType type) override;
  536. void RequestMediaAccessPermission(
  537. content::WebContents* web_contents,
  538. const content::MediaStreamRequest& request,
  539. content::MediaResponseCallback callback) override;
  540. content::JavaScriptDialogManager* GetJavaScriptDialogManager(
  541. content::WebContents* source) override;
  542. void OnAudioStateChanged(bool audible) override;
  543. void UpdatePreferredSize(content::WebContents* web_contents,
  544. const gfx::Size& pref_size) override;
  545. void DraggableRegionsChanged(
  546. const std::vector<blink::mojom::DraggableRegionPtr>& regions,
  547. content::WebContents* contents) override;
  548. // content::WebContentsObserver:
  549. void BeforeUnloadFired(bool proceed) override;
  550. void OnBackgroundColorChanged() override;
  551. void RenderFrameCreated(content::RenderFrameHost* render_frame_host) override;
  552. void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override;
  553. void RenderFrameHostChanged(content::RenderFrameHost* old_host,
  554. content::RenderFrameHost* new_host) override;
  555. void FrameDeleted(content::FrameTreeNodeId frame_tree_node_id) override;
  556. void RenderViewDeleted(content::RenderViewHost*) override;
  557. void PrimaryMainFrameRenderProcessGone(
  558. base::TerminationStatus status) override;
  559. void DOMContentLoaded(content::RenderFrameHost* render_frame_host) override;
  560. void DidFinishLoad(content::RenderFrameHost* render_frame_host,
  561. const GURL& validated_url) override;
  562. void DidFailLoad(content::RenderFrameHost* render_frame_host,
  563. const GURL& validated_url,
  564. int error_code) override;
  565. void DidStartLoading() override;
  566. void DidStopLoading() override;
  567. void DidStartNavigation(
  568. content::NavigationHandle* navigation_handle) override;
  569. void DidRedirectNavigation(
  570. content::NavigationHandle* navigation_handle) override;
  571. void ReadyToCommitNavigation(
  572. content::NavigationHandle* navigation_handle) override;
  573. void DidFinishNavigation(
  574. content::NavigationHandle* navigation_handle) override;
  575. void WebContentsDestroyed() override;
  576. void NavigationEntryCommitted(
  577. const content::LoadCommittedDetails& load_details) override;
  578. void TitleWasSet(content::NavigationEntry* entry) override;
  579. void DidUpdateFaviconURL(
  580. content::RenderFrameHost* render_frame_host,
  581. const std::vector<blink::mojom::FaviconURLPtr>& urls) override;
  582. void PluginCrashed(const base::FilePath& plugin_path,
  583. base::ProcessId plugin_pid) override;
  584. void MediaStartedPlaying(const MediaPlayerInfo& video_type,
  585. const content::MediaPlayerId& id) override;
  586. void MediaStoppedPlaying(
  587. const MediaPlayerInfo& video_type,
  588. const content::MediaPlayerId& id,
  589. content::WebContentsObserver::MediaStoppedReason reason) override;
  590. void DidChangeThemeColor() override;
  591. void OnCursorChanged(const ui::Cursor& cursor) override;
  592. void DidAcquireFullscreen(content::RenderFrameHost* rfh) override;
  593. void OnWebContentsFocused(
  594. content::RenderWidgetHost* render_widget_host) override;
  595. void OnWebContentsLostFocus(
  596. content::RenderWidgetHost* render_widget_host) override;
  597. void OnDidAddMessageToConsole(
  598. content::RenderFrameHost* source_frame,
  599. blink::mojom::ConsoleMessageLevel level,
  600. const std::u16string& message,
  601. int32_t line_no,
  602. const std::u16string& source_id,
  603. const std::optional<std::u16string>& untrusted_stack_trace) override;
  604. // InspectableWebContentsDelegate:
  605. void DevToolsReloadPage() override;
  606. // InspectableWebContentsViewDelegate:
  607. void DevToolsFocused() override;
  608. void DevToolsOpened() override;
  609. void DevToolsClosed() override;
  610. void DevToolsResized() override;
  611. ElectronBrowserContext* GetBrowserContext() const;
  612. void OnElectronBrowserConnectionError();
  613. OffScreenWebContentsView* GetOffScreenWebContentsView() const;
  614. OffScreenRenderWidgetHostView* GetOffScreenRenderWidgetHostView() const;
  615. // Called when received a synchronous message from renderer to
  616. // get the zoom level.
  617. void OnGetZoomLevel(content::RenderFrameHost* frame_host,
  618. IPC::Message* reply_msg);
  619. void InitZoomController(content::WebContents* web_contents,
  620. const gin_helper::Dictionary& options);
  621. // content::WebContentsDelegate:
  622. bool CanOverscrollContent() override;
  623. std::unique_ptr<content::EyeDropper> OpenEyeDropper(
  624. content::RenderFrameHost* frame,
  625. content::EyeDropperListener* listener) override;
  626. void RunFileChooser(content::RenderFrameHost* render_frame_host,
  627. scoped_refptr<content::FileSelectListener> listener,
  628. const blink::mojom::FileChooserParams& params) override;
  629. void EnumerateDirectory(content::WebContents* web_contents,
  630. scoped_refptr<content::FileSelectListener> listener,
  631. const base::FilePath& path) override;
  632. // ExclusiveAccessContext:
  633. Profile* GetProfile() override;
  634. bool IsFullscreen() const override;
  635. void EnterFullscreen(const GURL& url,
  636. ExclusiveAccessBubbleType bubble_type,
  637. const int64_t display_id) override;
  638. void ExitFullscreen() override {}
  639. void UpdateExclusiveAccessBubble(
  640. const ExclusiveAccessBubbleParams& params,
  641. ExclusiveAccessBubbleHideCallback bubble_first_hide_callback) override {}
  642. void OnExclusiveAccessUserInput() override {}
  643. content::WebContents* GetWebContentsForExclusiveAccess() override;
  644. bool CanUserExitFullscreen() const override;
  645. bool IsExclusiveAccessBubbleDisplayed() const override;
  646. // content::WebContentsDelegate
  647. bool IsFullscreenForTabOrPending(const content::WebContents* source) override;
  648. content::FullscreenState GetFullscreenState(
  649. const content::WebContents* web_contents) const override;
  650. bool TakeFocus(content::WebContents* source, bool reverse) override;
  651. content::PictureInPictureResult EnterPictureInPicture(
  652. content::WebContents* web_contents) override;
  653. void ExitPictureInPicture() override;
  654. // InspectableWebContentsDelegate:
  655. void DevToolsSaveToFile(const std::string& url,
  656. const std::string& content,
  657. bool save_as,
  658. bool is_base64) override;
  659. void DevToolsAppendToFile(const std::string& url,
  660. const std::string& content) override;
  661. void DevToolsRequestFileSystems() override;
  662. void DevToolsAddFileSystem(const std::string& type,
  663. const base::FilePath& file_system_path) override;
  664. void DevToolsRemoveFileSystem(
  665. const base::FilePath& file_system_path) override;
  666. void DevToolsIndexPath(int request_id,
  667. const std::string& file_system_path,
  668. const std::string& excluded_folders_message) override;
  669. void DevToolsOpenInNewTab(const std::string& url) override;
  670. void DevToolsOpenSearchResultsInNewTab(const std::string& query) override;
  671. void DevToolsStopIndexing(int request_id) override;
  672. void DevToolsSearchInPath(int request_id,
  673. const std::string& file_system_path,
  674. const std::string& query) override;
  675. void DevToolsSetEyeDropperActive(bool active) override;
  676. // InspectableWebContentsViewDelegate:
  677. #if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC)
  678. ui::ImageModel GetDevToolsWindowIcon() override;
  679. #endif
  680. #if BUILDFLAG(IS_LINUX)
  681. void GetDevToolsWindowWMClass(std::string* name,
  682. std::string* class_name) override;
  683. #endif
  684. void ColorPickedInEyeDropper(int r, int g, int b, int a);
  685. // DevTools index event callbacks.
  686. void OnDevToolsIndexingWorkCalculated(int request_id,
  687. const std::string& file_system_path,
  688. int total_work);
  689. void OnDevToolsIndexingWorked(int request_id,
  690. const std::string& file_system_path,
  691. int worked);
  692. void OnDevToolsIndexingDone(int request_id,
  693. const std::string& file_system_path);
  694. void OnDevToolsSearchCompleted(int request_id,
  695. const std::string& file_system_path,
  696. const std::vector<std::string>& file_paths);
  697. // Set fullscreen mode triggered by html api.
  698. void SetHtmlApiFullscreen(bool enter_fullscreen);
  699. // Update the html fullscreen flag in both browser and renderer.
  700. void UpdateHtmlApiFullscreen(bool fullscreen);
  701. v8::Global<v8::Value> session_;
  702. v8::Global<v8::Value> devtools_web_contents_;
  703. v8::Global<v8::Value> debugger_;
  704. std::unique_ptr<WebViewGuestDelegate> guest_delegate_;
  705. std::unique_ptr<FrameSubscriber> frame_subscriber_;
  706. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  707. std::unique_ptr<extensions::ScriptExecutor> script_executor_;
  708. #endif
  709. // The host webcontents that may contain this webcontents.
  710. RAW_PTR_EXCLUSION WebContents* embedder_ = nullptr;
  711. // Whether the guest view has been attached.
  712. bool attached_ = false;
  713. // The type of current WebContents.
  714. Type type_ = Type::kBrowserWindow;
  715. // Weather the guest view should be transparent
  716. bool guest_transparent_ = true;
  717. int32_t id_;
  718. // Request id used for findInPage request.
  719. uint32_t find_in_page_request_id_ = 0;
  720. // Whether background throttling is disabled.
  721. bool background_throttling_ = true;
  722. // Whether to enable devtools.
  723. bool enable_devtools_ = true;
  724. // Observers of this WebContents.
  725. base::ObserverList<ExtendedWebContentsObserver> observers_;
  726. v8::Global<v8::Value> pending_child_web_preferences_;
  727. // The window that this WebContents belongs to.
  728. base::WeakPtr<NativeWindow> owner_window_;
  729. bool offscreen_ = false;
  730. // Whether offscreen rendering use gpu shared texture
  731. bool offscreen_use_shared_texture_ = false;
  732. // Whether window is fullscreened by HTML5 api.
  733. bool html_fullscreen_ = false;
  734. // Whether window is fullscreened by window api.
  735. bool native_fullscreen_ = false;
  736. const scoped_refptr<DevToolsFileSystemIndexer> devtools_file_system_indexer_ =
  737. base::MakeRefCounted<DevToolsFileSystemIndexer>();
  738. ExclusiveAccessManager exclusive_access_manager_{this};
  739. std::unique_ptr<DevToolsEyeDropper> eye_dropper_;
  740. raw_ptr<ElectronBrowserContext> browser_context_;
  741. // The stored InspectableWebContents object.
  742. // Notice that inspectable_web_contents_ must be placed after
  743. // dialog_manager_, so we can make sure inspectable_web_contents_ is
  744. // destroyed before dialog_manager_, otherwise a crash would happen.
  745. std::unique_ptr<InspectableWebContents> inspectable_web_contents_;
  746. // The zoom controller for this webContents.
  747. // Note: owned by inspectable_web_contents_, so declare this *after*
  748. // that field to ensure the dtor destroys them in the right order.
  749. raw_ptr<WebContentsZoomController> zoom_controller_ = nullptr;
  750. // Maps url to file path, used by the file requests sent from devtools.
  751. typedef std::map<std::string, base::FilePath> PathsMap;
  752. PathsMap saved_files_;
  753. // Map id to index job, used for file system indexing requests from devtools.
  754. typedef std::
  755. map<int, scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>>
  756. DevToolsIndexingJobsMap;
  757. DevToolsIndexingJobsMap devtools_indexing_jobs_;
  758. const scoped_refptr<base::SequencedTaskRunner> file_task_runner_ =
  759. base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()});
  760. #if BUILDFLAG(ENABLE_PRINTING)
  761. const scoped_refptr<base::TaskRunner> print_task_runner_;
  762. #endif
  763. // Stores the frame thats currently in fullscreen, nullptr if there is none.
  764. raw_ptr<content::RenderFrameHost> fullscreen_frame_ = nullptr;
  765. std::unique_ptr<SkRegion> draggable_region_;
  766. bool force_non_draggable_ = false;
  767. base::WeakPtrFactory<WebContents> weak_factory_{this};
  768. };
  769. } // namespace api
  770. } // namespace electron
  771. #endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_WEB_CONTENTS_H_