electron_api_web_contents.h 35 KB

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