web_state.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. // Copyright 2013 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 IOS_WEB_PUBLIC_WEB_STATE_H_
  5. #define IOS_WEB_PUBLIC_WEB_STATE_H_
  6. #import <Foundation/Foundation.h>
  7. #include <stdint.h>
  8. #include <map>
  9. #include <memory>
  10. #include <string>
  11. #include <utility>
  12. #include <vector>
  13. #include "base/callback_forward.h"
  14. #include "base/callback_list.h"
  15. #include "base/memory/weak_ptr.h"
  16. #include "base/strings/string_piece.h"
  17. #include "base/supports_user_data.h"
  18. #include "base/time/time.h"
  19. #include "ios/web/public/deprecated/url_verification_constants.h"
  20. #include "ios/web/public/navigation/referrer.h"
  21. #include "mojo/public/cpp/bindings/generic_pending_receiver.h"
  22. #include "mojo/public/cpp/system/message_pipe.h"
  23. #include "ui/base/page_transition_types.h"
  24. #include "ui/base/window_open_disposition.h"
  25. #include "url/gurl.h"
  26. class GURL;
  27. @class CRWJSInjectionReceiver;
  28. @class CRWSessionStorage;
  29. @protocol CRWScrollableContent;
  30. @protocol CRWWebViewProxy;
  31. typedef id<CRWWebViewProxy> CRWWebViewProxyType;
  32. @class UIView;
  33. typedef UIView<CRWScrollableContent> CRWContentView;
  34. namespace base {
  35. class Value;
  36. }
  37. namespace gfx {
  38. class Image;
  39. class RectF;
  40. }
  41. namespace web {
  42. class BrowserState;
  43. struct FaviconStatus;
  44. class NavigationManager;
  45. enum Permission : NSUInteger;
  46. enum PermissionState : NSUInteger;
  47. class SessionCertificatePolicyCache;
  48. class WebFrame;
  49. class WebFramesManager;
  50. class WebStateDelegate;
  51. class WebStateObserver;
  52. class WebStatePolicyDecider;
  53. // Normally it would be a bug for multiple WebStates to be realized in quick
  54. // succession. However, there are some specific use cases where this is
  55. // expected. In these scenarios call IgnoreOverRealizationCheck() before
  56. // each expected -ForceRealized.
  57. void IgnoreOverRealizationCheck();
  58. // Core interface for interaction with the web.
  59. class WebState : public base::SupportsUserData {
  60. public:
  61. // Parameters for the Create() method.
  62. struct CreateParams {
  63. explicit CreateParams(web::BrowserState* browser_state);
  64. ~CreateParams();
  65. // The corresponding BrowserState for the new WebState.
  66. web::BrowserState* browser_state;
  67. // Whether the WebState is created as the result of a window.open or by
  68. // clicking a link with a blank target. Used to determine whether the
  69. // WebState is allowed to be closed via window.close().
  70. bool created_with_opener;
  71. // Value used to set the last time the WebState was made active; this
  72. // is the value that will be returned by GetLastActiveTime(). If this
  73. // is left default initialized, then the value will not be passed on
  74. // to the WebState and GetLastActiveTime() will return the WebState's
  75. // creation time.
  76. base::Time last_active_time;
  77. };
  78. // Parameters for the OpenURL() method.
  79. struct OpenURLParams {
  80. OpenURLParams(const GURL& url,
  81. const GURL& virtual_url,
  82. const Referrer& referrer,
  83. WindowOpenDisposition disposition,
  84. ui::PageTransition transition,
  85. bool is_renderer_initiated);
  86. OpenURLParams(const GURL& url,
  87. const Referrer& referrer,
  88. WindowOpenDisposition disposition,
  89. ui::PageTransition transition,
  90. bool is_renderer_initiated);
  91. OpenURLParams(const OpenURLParams& params);
  92. OpenURLParams& operator=(const OpenURLParams& params);
  93. OpenURLParams(OpenURLParams&& params);
  94. OpenURLParams& operator=(OpenURLParams&& params);
  95. ~OpenURLParams();
  96. // The URL/virtualURL/referrer to be opened.
  97. GURL url;
  98. GURL virtual_url;
  99. Referrer referrer;
  100. // The disposition requested by the navigation source.
  101. WindowOpenDisposition disposition;
  102. // The transition type of navigation.
  103. ui::PageTransition transition;
  104. // Whether this navigation is initiated by the renderer process.
  105. bool is_renderer_initiated;
  106. };
  107. // InterfaceBinder can be instantiated by subclasses of WebState and returned
  108. // by GetInterfaceBinderForMainFrame().
  109. class InterfaceBinder {
  110. public:
  111. explicit InterfaceBinder(WebState* web_state);
  112. InterfaceBinder(const InterfaceBinder&) = delete;
  113. InterfaceBinder& operator=(const InterfaceBinder&) = delete;
  114. ~InterfaceBinder();
  115. template <typename Interface>
  116. void AddInterface(
  117. base::RepeatingCallback<void(mojo::PendingReceiver<Interface>)>
  118. callback) {
  119. AddInterface(
  120. Interface::Name_,
  121. base::BindRepeating(&WrapCallback<Interface>, std::move(callback)));
  122. }
  123. // Adds a callback to bind an interface receiver pipe carried by a
  124. // GenericPendingReceiver.
  125. using Callback =
  126. base::RepeatingCallback<void(mojo::GenericPendingReceiver*)>;
  127. void AddInterface(base::StringPiece interface_name, Callback callback);
  128. // Attempts to bind |receiver| by matching its interface name against the
  129. // callbacks registered on this InterfaceBinder.
  130. void BindInterface(mojo::GenericPendingReceiver receiver);
  131. private:
  132. template <typename Interface>
  133. static void WrapCallback(
  134. base::RepeatingCallback<void(mojo::PendingReceiver<Interface>)>
  135. callback,
  136. mojo::GenericPendingReceiver* receiver) {
  137. if (auto typed_receiver = receiver->As<Interface>())
  138. callback.Run(std::move(typed_receiver));
  139. }
  140. WebState* const web_state_;
  141. std::map<std::string, Callback> callbacks_;
  142. };
  143. // Creates a new WebState.
  144. static std::unique_ptr<WebState> Create(const CreateParams& params);
  145. // Creates a new WebState from a serialized representation of the session.
  146. // |session_storage| must not be nil.
  147. static std::unique_ptr<WebState> CreateWithStorageSession(
  148. const CreateParams& params,
  149. CRWSessionStorage* session_storage);
  150. WebState(const WebState&) = delete;
  151. WebState& operator=(const WebState&) = delete;
  152. ~WebState() override {}
  153. // Gets/Sets the delegate.
  154. virtual WebStateDelegate* GetDelegate() = 0;
  155. virtual void SetDelegate(WebStateDelegate* delegate) = 0;
  156. // Returns whether the WebState is realized.
  157. //
  158. // What does "realized" mean? When creating a WebState from session storage
  159. // with |CreateWithStorageSession()|, it may not yet have been fully created.
  160. // Instead, it has all information to fully instantiate it and its history
  161. // available, but the underlying objects (WKWebView, NavigationManager, ...)
  162. // have not been created.
  163. //
  164. // This is an optimisation to reduce the amount of memory consumed by tabs
  165. // that have been restored after the browser has been shutdown. If the user
  166. // has many tabs, but only consult a subset of them, then there is no point
  167. // in creating them eagerly at startup. Instead, the creation is delayed
  168. // until the tabs are activated by the user.
  169. //
  170. // When the WebState becomes realized, the WebStateRealized() event will be
  171. // sent to all its WebStateObservers. They can listen to that event if they
  172. // need to support this optimisation (by delaying the creation of their own
  173. // state until the WebState is really used).
  174. //
  175. // See //docs/ios/unrealized_web_state.md for more information.
  176. virtual bool IsRealized() const = 0;
  177. // Forcefully bring the WebState in "realized" state. This method can safely
  178. // be called multiple time on a WebState, though it should not be necessary
  179. // to call it as the WebState will lazily switch to "realized" state when
  180. // needed.
  181. //
  182. // Returns `this` so that the method can be chained such as:
  183. //
  184. // WebState* web_state = ...;
  185. // web_state->ForceRealized()->SetDelegate(this);
  186. virtual WebState* ForceRealized() = 0;
  187. // Whether or not a web view is allowed to exist in this WebState. Defaults
  188. // to false; this should be enabled before attempting to access the view.
  189. virtual bool IsWebUsageEnabled() const = 0;
  190. virtual void SetWebUsageEnabled(bool enabled) = 0;
  191. // The view containing the contents of the current web page. If the view has
  192. // been purged due to low memory, this will recreate it. It is up to the
  193. // caller to size the view.
  194. virtual UIView* GetView() = 0;
  195. // Notifies the WebState that the WebContent is covered. Triggers
  196. // visibilitychange event.
  197. virtual void DidCoverWebContent() = 0;
  198. // Notifies the WebState that the WebContent is no longer covered. Triggers
  199. // visibilitychange event.
  200. virtual void DidRevealWebContent() = 0;
  201. // Get the last time that the WebState was made active (either when it was
  202. // created or shown with WasShown()).
  203. virtual base::Time GetLastActiveTime() const = 0;
  204. // Must be called when the WebState becomes shown/hidden.
  205. virtual void WasShown() = 0;
  206. virtual void WasHidden() = 0;
  207. // When |true|, attempt to prevent the WebProcess from suspending. Embedder
  208. // must override WebClient::GetWindowedContainer to maintain this
  209. // functionality.
  210. virtual void SetKeepRenderProcessAlive(bool keep_alive) = 0;
  211. // Gets the BrowserState associated with this WebState. Can never return null.
  212. virtual BrowserState* GetBrowserState() const = 0;
  213. // Returns a weak pointer.
  214. virtual base::WeakPtr<WebState> GetWeakPtr() = 0;
  215. // Opens a URL with the given disposition. The transition specifies how this
  216. // navigation should be recorded in the history system (for example, typed).
  217. virtual void OpenURL(const OpenURLParams& params) = 0;
  218. // Loads the web content from the HTML you provide as if the HTML were the
  219. // response to the request.
  220. virtual void LoadSimulatedRequest(const GURL& url,
  221. NSString* response_html_string)
  222. API_AVAILABLE(ios(15.0)) = 0;
  223. // Loads the web content from the data you provide as if the data were the
  224. // response to the request.
  225. virtual void LoadSimulatedRequest(const GURL& url,
  226. NSData* response_data,
  227. NSString* mime_type)
  228. API_AVAILABLE(ios(15.0)) = 0;
  229. // Stops any pending navigation.
  230. virtual void Stop() = 0;
  231. // Gets the NavigationManager associated with this WebState. Can never return
  232. // null.
  233. virtual const NavigationManager* GetNavigationManager() const = 0;
  234. virtual NavigationManager* GetNavigationManager() = 0;
  235. // Gets the WebFramesManager associated with this WebState. Can never return
  236. // null.
  237. virtual const WebFramesManager* GetWebFramesManager() const = 0;
  238. virtual WebFramesManager* GetWebFramesManager() = 0;
  239. // Gets the SessionCertificatePolicyCache for this WebState. Can never return
  240. // null.
  241. virtual const SessionCertificatePolicyCache*
  242. GetSessionCertificatePolicyCache() const = 0;
  243. virtual SessionCertificatePolicyCache* GetSessionCertificatePolicyCache() = 0;
  244. // Creates a serializable representation of the session. The returned value
  245. // is autoreleased.
  246. virtual CRWSessionStorage* BuildSessionStorage() = 0;
  247. // Gets the CRWJSInjectionReceiver associated with this WebState.
  248. virtual CRWJSInjectionReceiver* GetJSInjectionReceiver() const = 0;
  249. // Loads |data| of type |mime_type| and replaces last committed URL with the
  250. // given |url|.
  251. virtual void LoadData(NSData* data, NSString* mime_type, const GURL& url) = 0;
  252. // DISCOURAGED. Prefer using |WebFrame CallJavaScriptFunction| instead because
  253. // it restricts JavaScript execution to functions within __gCrWeb and can also
  254. // call those functions on any frame in the page. ExecuteJavaScript here can
  255. // execute arbitrary JavaScript code, which is not as safe and is restricted
  256. // to executing only on the main frame.
  257. // Runs JavaScript in the main frame's context. If a callback is provided, it
  258. // will be used to return the result, when the result is available or script
  259. // execution has failed due to an error.
  260. // NOTE: Integer values will be returned as Type::DOUBLE because of underlying
  261. // library limitation.
  262. typedef base::OnceCallback<void(const base::Value*)> JavaScriptResultCallback;
  263. virtual void ExecuteJavaScript(const std::u16string& javascript) = 0;
  264. virtual void ExecuteJavaScript(const std::u16string& javascript,
  265. JavaScriptResultCallback callback) = 0;
  266. // Asynchronously executes |javaScript| in the main frame's context,
  267. // registering user interaction.
  268. virtual void ExecuteUserJavaScript(NSString* javaScript) = 0;
  269. // Returns a unique identifier for this WebState that is stable across
  270. // restart of the application (and across "undo" after a tab is closed).
  271. // It is local to the device and not synchronized. This can be used as a key
  272. // to identify locally this WebState (e.g. can be used as part of the name
  273. // of the file that is used to store a snapshot of the WebState, or it can
  274. // be used as a key in an NSDictionary).
  275. virtual NSString* GetStableIdentifier() const = 0;
  276. // Gets the contents MIME type.
  277. virtual const std::string& GetContentsMimeType() const = 0;
  278. // Returns true if the current page is a web view with HTML.
  279. virtual bool ContentIsHTML() const = 0;
  280. // Returns the current navigation title. This could be the title of the page
  281. // if it is available or the URL.
  282. virtual const std::u16string& GetTitle() const = 0;
  283. // Returns true if the current page is loading.
  284. virtual bool IsLoading() const = 0;
  285. // The fraction of the page load that has completed as a number between 0.0
  286. // (nothing loaded) and 1.0 (fully loaded).
  287. virtual double GetLoadingProgress() const = 0;
  288. // Whether the WebState is visible. Returns true after WasShown() call and
  289. // false after WasHidden() call.
  290. virtual bool IsVisible() const = 0;
  291. // Returns true if the web process backing this WebState is believed to
  292. // currently be crashed.
  293. virtual bool IsCrashed() const = 0;
  294. // Returns true if the web process backing this WebState is believed to
  295. // currently be crashed or was evicted (by calling SetWebUsageEnabled
  296. // with false).
  297. // TODO(crbug.com/619971): Remove once all code has been ported to use
  298. // IsCrashed() instead of IsEvicted().
  299. virtual bool IsEvicted() const = 0;
  300. // Whether this instance is in the process of being destroyed.
  301. virtual bool IsBeingDestroyed() const = 0;
  302. // Gets/Sets the favicon for the current page displayed by this WebState.
  303. virtual const FaviconStatus& GetFaviconStatus() const = 0;
  304. virtual void SetFaviconStatus(const FaviconStatus& favicon_status) = 0;
  305. // Returns the number of items in the NavigationManager, excluding
  306. // pending entries.
  307. // TODO(crbug.com/533848): Update to return size_t.
  308. virtual int GetNavigationItemCount() const = 0;
  309. // Gets the URL currently being displayed in the URL bar, if there is one.
  310. // This URL might be a pending navigation that hasn't committed yet, so it is
  311. // not guaranteed to match the current page in this WebState. A typical
  312. // example of this is interstitials, which show the URL of the new/loading
  313. // page (active) but the security context is of the old page (last committed).
  314. virtual const GURL& GetVisibleURL() const = 0;
  315. // Gets the last committed URL. It represents the current page that is
  316. // displayed in this WebState. It represents the current security context.
  317. virtual const GURL& GetLastCommittedURL() const = 0;
  318. // Returns the WebState view of the current URL. Moreover, this method
  319. // will set the trustLevel enum to the appropriate level from a security point
  320. // of view. The caller has to handle the case where |trust_level| is not
  321. // appropriate. Passing |null| will skip the trust check.
  322. // TODO(crbug.com/457679): Figure out a clean API for this.
  323. virtual GURL GetCurrentURL(URLVerificationTrustLevel* trust_level) const = 0;
  324. // Callback used to handle script commands. |message| is the JS message sent
  325. // from the |sender_frame| in the page, |page_url| is the URL of page's main
  326. // frame, |user_is_interacting| indicates if the user is interacting with the
  327. // page.
  328. // TODO(crbug.com/881813): remove |page_url|.
  329. using ScriptCommandCallbackSignature = void(const base::Value& message,
  330. const GURL& page_url,
  331. bool user_is_interacting,
  332. web::WebFrame* sender_frame);
  333. using ScriptCommandCallback =
  334. base::RepeatingCallback<ScriptCommandCallbackSignature>;
  335. // Registers |callback| for JS message whose 'command' matches
  336. // |command_prefix|. The returned subscription should be stored by the caller.
  337. // When the description object is destroyed, it will unregister |callback| if
  338. // this WebState is still alive, and do nothing if this WebState is already
  339. // destroyed. Therefore if the caller want to stop receiving JS messages it
  340. // can just destroy the subscription.
  341. [[nodiscard]] virtual base::CallbackListSubscription AddScriptCommandCallback(
  342. const ScriptCommandCallback& callback,
  343. const std::string& command_prefix) = 0;
  344. // Returns the current CRWWebViewProxy object.
  345. virtual CRWWebViewProxyType GetWebViewProxy() const = 0;
  346. // Typically an embedder will:
  347. // - Implement this method to receive notification of changes to the page's
  348. // |VisibleSecurityState|, updating security UI (e.g. a lock icon) to
  349. // reflect the current security state of the page.
  350. // ...and optionally:
  351. // - Invoke this method upon detection of an event that will change
  352. // the security state (e.g. a non-secure form element is edited).
  353. virtual void DidChangeVisibleSecurityState() = 0;
  354. virtual InterfaceBinder* GetInterfaceBinderForMainFrame();
  355. // Whether this WebState was created with an opener.
  356. // See CreateParams::created_with_opener for more details.
  357. virtual bool HasOpener() const = 0;
  358. virtual void SetHasOpener(bool has_opener) = 0;
  359. // Callback used to handle snapshots. The parameter is the snapshot image.
  360. typedef base::RepeatingCallback<void(const gfx::Image&)> SnapshotCallback;
  361. // Returns whether TakeSnapshot() can be executed. The API may be disabled if
  362. // the WKWebView IPC mechanism is blocked due to an outstanding JavaScript
  363. // dialog.
  364. virtual bool CanTakeSnapshot() const = 0;
  365. // Takes a snapshot of this WebState with |rect|. |rect| should be specified
  366. // in the coordinate system of the view returned by GetView(). |callback| is
  367. // asynchronously invoked after performing the snapshot. Prior to iOS 11, the
  368. // callback is invoked with a nil snapshot.
  369. virtual void TakeSnapshot(const gfx::RectF& rect,
  370. SnapshotCallback callback) = 0;
  371. // Creates PDF representation of the web page and invokes the |callback| with
  372. // the NSData of the PDF or nil if a PDF couldn't be generated.
  373. virtual void CreateFullPagePdf(
  374. base::OnceCallback<void(NSData*)> callback) = 0;
  375. // Tries to dismiss the presented states of the media (fullscreen or Picture
  376. // in Picture).
  377. virtual void CloseMediaPresentations() = 0;
  378. // Adds and removes observers for page navigation notifications. The order in
  379. // which notifications are sent to observers is undefined. Clients must be
  380. // sure to remove the observer before they go away.
  381. virtual void AddObserver(WebStateObserver* observer) = 0;
  382. virtual void RemoveObserver(WebStateObserver* observer) = 0;
  383. // Instructs the delegate to close this web state. Called when the page calls
  384. // wants to close self by calling window.close() JavaScript API.
  385. virtual void CloseWebState() = 0;
  386. // Injects an opaque NSData block into a WKWebView to restore or serialize.
  387. // Returns true if this operation succeeds, and false otherwise.
  388. virtual bool SetSessionStateData(NSData* data) = 0;
  389. virtual NSData* SessionStateData() = 0;
  390. // Gets or sets the web state's permission for a specific type, for example
  391. // camera or microphone, on the device.
  392. virtual PermissionState GetStateForPermission(Permission permission) const
  393. API_AVAILABLE(ios(15.0)) = 0;
  394. virtual void SetStateForPermission(PermissionState state,
  395. Permission permission)
  396. API_AVAILABLE(ios(15.0)) = 0;
  397. // Gets a mapping of all available permissions and their states.
  398. // Note that both key and value are in NSNumber format, and should be
  399. // translated to NSUInteger and casted to web::Permission or
  400. // web::PermissionState before use.
  401. virtual NSDictionary<NSNumber*, NSNumber*>* GetStatesForAllPermissions() const
  402. API_AVAILABLE(ios(15.0)) = 0;
  403. protected:
  404. friend class WebStatePolicyDecider;
  405. // Adds and removes policy deciders for navigation actions. The order in which
  406. // deciders are called is undefined, and will stop on the first decider that
  407. // refuses a navigation. Clients must be sure to remove the deciders before
  408. // they go away.
  409. virtual void AddPolicyDecider(WebStatePolicyDecider* decider) = 0;
  410. virtual void RemovePolicyDecider(WebStatePolicyDecider* decider) = 0;
  411. WebState() {}
  412. };
  413. } // namespace web
  414. #endif // IOS_WEB_PUBLIC_WEB_STATE_H_