electron_api_web_contents.h 36 KB

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