electron_api_web_contents.h 35 KB

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