extension_host.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. // Copyright 2014 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef EXTENSIONS_BROWSER_EXTENSION_HOST_H_
  5. #define EXTENSIONS_BROWSER_EXTENSION_HOST_H_
  6. #include <stdint.h>
  7. #include <memory>
  8. #include <string>
  9. #include <unordered_map>
  10. #include "base/callback.h"
  11. #include "base/memory/raw_ptr.h"
  12. #include "base/memory/weak_ptr.h"
  13. #include "base/observer_list.h"
  14. #include "base/timer/elapsed_timer.h"
  15. #include "content/public/browser/media_stream_request.h"
  16. #include "content/public/browser/web_contents_delegate.h"
  17. #include "content/public/browser/web_contents_observer.h"
  18. #include "extensions/browser/deferred_start_render_host.h"
  19. #include "extensions/browser/extension_function_dispatcher.h"
  20. #include "extensions/browser/extension_registry_observer.h"
  21. #include "extensions/common/mojom/view_type.mojom.h"
  22. #include "extensions/common/stack_frame.h"
  23. namespace content {
  24. class BrowserContext;
  25. class RenderProcessHost;
  26. class SiteInstance;
  27. }
  28. namespace extensions {
  29. class Extension;
  30. class ExtensionHostDelegate;
  31. class ExtensionHostObserver;
  32. class ExtensionHostQueue;
  33. // This class is the browser component of an extension component's page.
  34. // It handles setting up the renderer process, if needed, with special
  35. // privileges available to extensions. It may have a view to be shown in the
  36. // browser UI, or it may be hidden.
  37. //
  38. // If you are adding code that only affects visible extension views (and not
  39. // invisible background pages) you should add it to ExtensionViewHost.
  40. class ExtensionHost : public DeferredStartRenderHost,
  41. public content::WebContentsDelegate,
  42. public content::WebContentsObserver,
  43. public ExtensionFunctionDispatcher::Delegate,
  44. public ExtensionRegistryObserver {
  45. public:
  46. using CloseHandler = base::OnceCallback<void(ExtensionHost*)>;
  47. ExtensionHost(const Extension* extension,
  48. content::SiteInstance* site_instance,
  49. const GURL& url,
  50. mojom::ViewType host_type);
  51. ExtensionHost(const ExtensionHost&) = delete;
  52. ExtensionHost& operator=(const ExtensionHost&) = delete;
  53. ~ExtensionHost() override;
  54. // This may be null if the extension has been or is being unloaded.
  55. const Extension* extension() const { return extension_; }
  56. const std::string& extension_id() const { return extension_id_; }
  57. content::WebContents* host_contents() const { return host_contents_.get(); }
  58. content::RenderFrameHost* main_frame_host() const { return main_frame_host_; }
  59. content::RenderProcessHost* render_process_host() const;
  60. bool has_loaded_once() const { return has_loaded_once_; }
  61. const GURL& initial_url() const { return initial_url_; }
  62. bool document_element_available() const {
  63. return document_element_available_;
  64. }
  65. content::BrowserContext* browser_context() { return browser_context_; }
  66. mojom::ViewType extension_host_type() const { return extension_host_type_; }
  67. // Sets the callback responsible for closing the ExtensionHost in response to
  68. // a WebContents::CloseContents() call (which is triggered from e.g.
  69. // calling `window.close()`). This is done separately from the constructor as
  70. // some callsites create an ExtensionHost prior to the object that is
  71. // responsible for later closing it, but must be done before `CloseContents()`
  72. // can be called.
  73. void SetCloseHandler(CloseHandler close_handler);
  74. // Returns the last committed URL of the associated WebContents.
  75. const GURL& GetLastCommittedURL() const;
  76. // Returns true if the renderer main frame exists.
  77. bool IsRendererLive() const;
  78. // Prepares to initializes our RenderFrameHost by creating the main frame and
  79. // navigating `host_contents_` to the initial url. This happens delayed to
  80. // avoid locking the UI.
  81. void CreateRendererSoon();
  82. // Closes this host (results in [possibly asynchronous] deletion).
  83. void Close();
  84. // Typical observer interface.
  85. void AddObserver(ExtensionHostObserver* observer);
  86. void RemoveObserver(ExtensionHostObserver* observer);
  87. // Called when an event is dispatched to the event page associated with this
  88. // ExtensionHost.
  89. void OnBackgroundEventDispatched(const std::string& event_name, int event_id);
  90. // Called by the ProcessManager when a network request is started by the
  91. // extension corresponding to this ExtensionHost.
  92. void OnNetworkRequestStarted(uint64_t request_id);
  93. // Called by the ProcessManager when a previously started network request is
  94. // finished.
  95. void OnNetworkRequestDone(uint64_t request_id);
  96. // Returns true if the ExtensionHost is allowed to be navigated.
  97. bool ShouldAllowNavigations() const;
  98. // content::WebContentsObserver:
  99. bool OnMessageReceived(const IPC::Message& message,
  100. content::RenderFrameHost* host) override;
  101. void RenderFrameCreated(content::RenderFrameHost* frame_host) override;
  102. void RenderFrameHostChanged(content::RenderFrameHost* old_host,
  103. content::RenderFrameHost* new_host) override;
  104. void PrimaryMainFrameRenderProcessGone(
  105. base::TerminationStatus status) override;
  106. void PrimaryMainDocumentElementAvailable() override;
  107. void DidStopLoading() override;
  108. // content::WebContentsDelegate:
  109. content::JavaScriptDialogManager* GetJavaScriptDialogManager(
  110. content::WebContents* source) override;
  111. void AddNewContents(content::WebContents* source,
  112. std::unique_ptr<content::WebContents> new_contents,
  113. const GURL& target_url,
  114. WindowOpenDisposition disposition,
  115. const gfx::Rect& initial_rect,
  116. bool user_gesture,
  117. bool* was_blocked) override;
  118. void CloseContents(content::WebContents* contents) override;
  119. void RequestMediaAccessPermission(
  120. content::WebContents* web_contents,
  121. const content::MediaStreamRequest& request,
  122. content::MediaResponseCallback callback) override;
  123. bool CheckMediaAccessPermission(content::RenderFrameHost* render_frame_host,
  124. const GURL& security_origin,
  125. blink::mojom::MediaStreamType type) override;
  126. bool IsNeverComposited(content::WebContents* web_contents) override;
  127. content::PictureInPictureResult EnterPictureInPicture(
  128. content::WebContents* web_contents) override;
  129. void ExitPictureInPicture() override;
  130. std::string GetTitleForMediaControls(
  131. content::WebContents* web_contents) override;
  132. // ExtensionRegistryObserver:
  133. void OnExtensionReady(content::BrowserContext* browser_context,
  134. const Extension* extension) override;
  135. void OnExtensionUnloaded(content::BrowserContext* browser_context,
  136. const Extension* extension,
  137. UnloadedExtensionReason reason) override;
  138. protected:
  139. // Called each time this ExtensionHost completes a load finishes loading,
  140. // before any stop-loading notifications or observer methods are called.
  141. virtual void OnDidStopFirstLoad();
  142. // Navigates to the initial page.
  143. virtual void LoadInitialURL();
  144. // Returns true if we're hosting a background page.
  145. virtual bool IsBackgroundPage() const;
  146. private:
  147. // DeferredStartRenderHost:
  148. void CreateRendererNow() override;
  149. // Message handlers.
  150. void OnEventAck(int event_id);
  151. void OnIncrementLazyKeepaliveCount();
  152. void OnDecrementLazyKeepaliveCount();
  153. void MaybeNotifyRenderProcessReady();
  154. void NotifyRenderProcessReady();
  155. // Records UMA for load events.
  156. void RecordStopLoadingUMA();
  157. // Delegate for functionality that cannot exist in the extensions module.
  158. std::unique_ptr<ExtensionHostDelegate> delegate_;
  159. // The extension that we're hosting in this view.
  160. raw_ptr<const Extension> extension_;
  161. // Id of extension that we're hosting in this view.
  162. const std::string extension_id_;
  163. // The browser context that this host is tied to.
  164. raw_ptr<content::BrowserContext> browser_context_;
  165. // The host for our HTML content.
  166. std::unique_ptr<content::WebContents> host_contents_;
  167. // A pointer to the current or speculative main frame in `host_contents_`. We
  168. // can't access this frame through the `host_contents_` directly as it does
  169. // not expose the speculative main frame. While navigating to a still-loading
  170. // speculative main frame, we want to send messages to it rather than the
  171. // current frame.
  172. raw_ptr<content::RenderFrameHost> main_frame_host_;
  173. // Whether CreateRendererNow was called before the extension was ready.
  174. bool is_renderer_creation_pending_ = false;
  175. // Whether ExtensionHostCreated() event has been fired, since
  176. // RenderFrameCreated is triggered by every main frame that is created,
  177. // including during a cross-site navigation which uses a new main frame.
  178. bool has_creation_notification_already_fired_ = false;
  179. // Whether the ExtensionHost has finished loading some content at least once.
  180. // There may be subsequent loads - such as reloads and navigations - and this
  181. // will not affect its value (it will remain true).
  182. bool has_loaded_once_ = false;
  183. // True if the main frame has finished parsing.
  184. bool document_element_available_ = false;
  185. // The original URL of the page being hosted.
  186. GURL initial_url_;
  187. // Messages sent out to the renderer that have not been acknowledged yet.
  188. // Maps event ID to event name.
  189. std::unordered_map<int, std::string> unacked_messages_;
  190. // The type of view being hosted.
  191. mojom::ViewType extension_host_type_;
  192. // Measures how long since the ExtensionHost object was created. This can be
  193. // used to measure the responsiveness of UI. For example, it's important to
  194. // keep this as low as possible for popups. Contrast this to |load_start_|,
  195. // for which a low value does not necessarily mean a responsive UI, as
  196. // ExtensionHosts may sit in an ExtensionHostQueue for a long time.
  197. base::ElapsedTimer create_start_;
  198. // Measures how long since the initial URL started loading. This timer is
  199. // started only once the ExtensionHost has exited the ExtensionHostQueue.
  200. std::unique_ptr<base::ElapsedTimer> load_start_;
  201. CloseHandler close_handler_;
  202. // Whether the close handler has been previously invoked.
  203. bool called_close_handler_ = false;
  204. base::ObserverList<ExtensionHostObserver>::Unchecked observer_list_;
  205. base::WeakPtrFactory<ExtensionHost> weak_ptr_factory_{this};
  206. };
  207. } // namespace extensions
  208. #endif // EXTENSIONS_BROWSER_EXTENSION_HOST_H_