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.
5 #ifndef IOS_WEB_WEB_STATE_UI_CRW_WEB_CONTROLLER_PROTECTED_H_
6 #define IOS_WEB_WEB_STATE_UI_CRW_WEB_CONTROLLER_PROTECTED_H_
8 #import "ios/web/web_state/ui/crw_web_controller.h"
10 #include "base/mac/scoped_nsobject.h"
11 #include "ios/web/public/referrer.h"
12 #include "ios/web/public/web_state/page_display_state.h"
14 @
class CRWSessionController
;
21 // Separator between window href and name.
22 extern const char* kWindowNameSeparator
;
23 // Key for user interaction data in JavaScript message context.
24 extern NSString
* const kUserIsInteractingKey
;
25 // Key for origin URL data in JavaScript message context.
26 extern NSString
* const kOriginURLKey
;
28 // Values of the UMA |Web.URLVerificationFailure| histogram.
29 enum WebViewDocumentType
{
30 // Generic contents (e.g. PDF documents).
31 WEB_VIEW_DOCUMENT_TYPE_GENERIC
= 0,
33 WEB_VIEW_DOCUMENT_TYPE_HTML
,
35 WEB_VIEW_DOCUMENT_TYPE_UNKNOWN
,
36 WEB_VIEW_DOCUMENT_TYPE_COUNT
,
39 // A guess for how likely a page change is to happen very soon.
40 // TODO(stuartmorgan): Eliminate this, or at least move to the UIWebView
42 enum PageChangeProbability
{
43 // No expectation that the page will be changing.
44 PAGE_CHANGE_PROBABILITY_LOW
,
45 // Reasonably high expectation that the page will be changing (e.g., the
46 // user just tapped a link).
47 PAGE_CHANGE_PROBABILITY_HIGH
,
48 // Very high expectation that the page will be changing (e.g., window.unload
50 PAGE_CHANGE_PROBABILITY_VERY_HIGH
,
53 struct NewWindowInfo
{
55 base::scoped_nsobject
<NSString
> window_name
;
56 web::ReferrerPolicy referrer_policy
;
57 bool user_is_interacting
;
58 NewWindowInfo(GURL url
,
59 NSString
* window_name
,
60 web::ReferrerPolicy referrer_policy
,
61 bool user_is_interacting
);
66 // Category for methods used or implemented by implementation subclasses of
68 @interface
CRWWebController (ProtectedMethods
)
70 #pragma mark Methods implemented by subclasses
71 // Everything in this section must be implemented by subclasses.
73 // If |contentView_| contains a web view, this is the web view it contains.
75 @
property(nonatomic
, readonly
) UIView
* webView
;
77 // The scroll view of |webView|.
78 @
property(nonatomic
, readonly
) UIScrollView
* webScrollView
;
80 // Whether or not to ignore URL verification failures. This may return YES in
81 // very limited situations where the URL can't be verified but there is no
82 // security impact to ignoring the failure (i.e., it's safe not to show the
84 @
property(nonatomic
, readonly
) BOOL ignoreURLVerificationFailures
;
86 // The title of the page.
87 @
property(nonatomic
, readonly
) NSString
* title
;
89 // Referrer for the current page; does not include the fragment.
90 @
property(nonatomic
, readonly
) NSString
* currentReferrerString
;
92 // This public property should be implemented by subclasses.
93 // TODO(stuartmorgan): See if we can get rid of this (it looks like it may only
94 // be fallback code for autocomplete that's necessarily used). If not, file a
95 // Radar since WKWebView doesn't appear to have this property.
96 // @property(nonatomic, assign) BOOL keyboardDisplayRequiresUserAction;
98 // Designated initializer.
99 - (instancetype
)initWithWebState
:(scoped_ptr
<web::WebStateImpl
>)webState
;
101 // Creates a web view if it's not yet created.
102 - (void)ensureWebViewCreated
;
104 // Destroys the web view by setting webView property to nil.
105 - (void)resetWebView
;
107 // Returns the current URL of the web view, and sets |trustLevel| accordingly
108 // based on the confidence in the verification.
109 - (GURL
)webURLWithTrustLevel
:(web::URLVerificationTrustLevel
*)trustLevel
;
111 // Registers the current user agent with the web view.
112 - (void)registerUserAgent
;
114 // Returns the type of document object loaded in the web view.
115 - (web::WebViewDocumentType
)webViewDocumentType
;
117 // Loads the given HTML in the web view.
118 - (void)loadWebHTMLString
:(NSString
*)html forURL
:(const GURL
&)URL
;
120 // These public methods should be implemented by subclasses.
121 //- (void)evaluateJavaScript:(NSString*)script
122 // stringResultHandler:(web::JavaScriptCompletion)handler;
123 //- (BOOL)scriptHasBeenInjectedForClass:(Class)jsInjectionManagerClass
124 // presenceBeacon:(NSString*)beacon;
125 //- (void)loadRequest:(NSMutableURLRequest*)request;
126 // Subclasses must call super's implementation.
127 //- (void)injectScript:(NSString*)script
128 // forClass:(Class)jsInjectionManagerClass;
129 //- (web::WebViewType)webViewType;
130 //- (void)evaluateUserJavaScript:(NSString*)script;
132 // Called before loading current URL in WebView.
133 - (void)willLoadCurrentURLInWebView
;
135 // Loads request for the URL of the current navigation item. Subclasses may
136 // choose to build a new NSURLRequest and call |loadRequest| on the underlying
137 // web view, or use native web view navigation where possible (for example,
138 // going back and forward through the history stack).
139 - (void)loadRequestForCurrentNavigationItem
;
141 // Indicates whether or not there's an indication that the page is probably
142 // about to change. This is called as a hint to the UIWebView-based subclass to
143 // change polling behavior.
144 // TODO(stuartmorgan): Remove once the hook points are driven from the subclass.
145 - (void)setPageChangeProbability
:(web::PageChangeProbability
)probability
;
147 // Cancels any load in progress in the web view.
148 - (void)abortWebLoad
;
150 // Called whenever any in-progress-load state should be reset.
151 // TODO(stuartmorgan): Remove this; it should be tracked internally to each
152 // subclass, since the existing logic is somewhat UIWebView-guesswork-based.
153 - (void)resetLoadState
;
155 // Evaluates given JavaScript to suppress the dialogs. Subclasses should prefer
156 // synchronous execution.
157 - (void)setSuppressDialogsWithHelperScript
:(NSString
*)script
;
159 // Called when CRWWebController believes that web page title has been changed.
160 - (void)titleDidChange
;
162 // Returns selector to handle JavaScript message with command property
163 // |command|. Subclasses may override to handle class-specific messages.
164 - (SEL
)selectorToHandleJavaScriptCommand
:(const std::string
&)command
;
166 // Sets zoom scale value for webview scroll view from |zoomState|.
167 - (void)applyWebViewScrollZoomScaleFromZoomState
:
168 (const web::PageZoomState
&)zoomState
;
170 // Handles cancelled load in WKWebView (error with NSURLErrorCancelled code).
171 - (void)handleCancelledError
:(NSError
*)error
;
173 #pragma mark - Optional methods for subclasses
174 // Subclasses may overwrite methods in this section.
176 // Checks if the URL has changed unexpectedly, and handles such changes.
177 // Returns true if the URL has changed.
178 // TODO(stuartmorgan): Remove once the hook points are driven from the subclass.
179 - (BOOL
)checkForUnexpectedURLChange
;
181 // Handles 'window.history.willChangeState' message.
182 - (BOOL
)handleWindowHistoryWillChangeStateMessage
:
183 (base::DictionaryValue
*)message
184 context
:(NSDictionary
*)context
;
185 // Handles 'window.history.didPushState' message.
186 - (BOOL
)handleWindowHistoryDidPushStateMessage
:(base::DictionaryValue
*)message
187 context
:(NSDictionary
*)context
;
189 // Handles 'window.history.didReplaceState' message.
190 - (BOOL
)handleWindowHistoryDidReplaceStateMessage
:
191 (base::DictionaryValue
*)message
192 context
:(NSDictionary
*)context
;
194 // Sets up WebUI for URL.
195 - (void)createWebUIForURL
:(const GURL
&)URL
;
197 // Clears WebUI, if one exists.
200 // Returns a NSMutableURLRequest that represents the current NavigationItem.
201 - (NSMutableURLRequest
*)requestForCurrentNavigationItem
;
203 // Compares the two URLs being navigated between during a history navigation to
204 // determine if a # needs to be appended to the URL of |toItem| to trigger a
205 // hashchange event. If so, also saves the modified URL into |toItem|.
206 - (GURL
)URLForHistoryNavigationFromItem
:(web::NavigationItem
*)fromItem
207 toItem
:(web::NavigationItem
*)toItem
;
209 #pragma mark - Internal methods for use by subclasses
211 // The web view's view of the current URL. During page transitions
212 // this may not be the same as the session history's view of the current URL.
213 // This method can change the state of the CRWWebController, as it will display
214 // an error if the returned URL is not reliable from a security point of view.
215 // Note that this method is expensive, so it should always be cached locally if
216 // it's needed multiple times in a method.
217 @
property(nonatomic
, readonly
) GURL currentURL
;
219 // The default URL for a newly created web view.
220 @
property(nonatomic
, readonly
) const GURL
& defaultURL
;
222 // Last URL change reported to webDidStartLoadingURL. Used to detect page
223 // location changes in practice.
224 @
property(nonatomic
, readonly
) GURL URLOnStartLoading
;
226 // Last URL change registered for load request.
227 @
property(nonatomic
, readonly
) GURL lastRegisteredRequestURL
;
229 // Returns YES if the object is being deallocated.
230 @
property(nonatomic
, readonly
) BOOL isBeingDestroyed
;
232 // Return YES if network activity is being halted. Halting happens prior to
234 @
property(nonatomic
, readonly
) BOOL isHalted
;
236 // Returns whether the user is interacting with the page.
237 @
property(nonatomic
, readonly
) BOOL userIsInteracting
;
239 // YES if a user interaction has been registered at any time once the page has
241 @
property(nonatomic
, readonly
) BOOL userInteractionRegistered
;
243 // Returns the current window id.
244 @
property(nonatomic
, readonly
) NSString
* windowId
;
246 // Returns windowID that is saved when a page changes. Used to detect refreshes.
247 @
property(nonatomic
, readonly
) NSString
* lastSeenWindowID
;
249 // Returns NavigationManager's session controller.
250 @
property(nonatomic
, readonly
) CRWSessionController
* sessionController
;
252 // Returns a new script which wraps |script| with windowID check so |script| is
253 // not evaluated on windowID mismatch.
254 - (NSString
*)scriptByAddingWindowIDCheckForScript
:(NSString
*)script
;
256 // Removes webView, optionally tracking the URL of the evicted
257 // page for later cache-based reconstruction.
258 - (void)removeWebViewAllowingCachedReconstruction
:(BOOL
)allowCache
;
260 // Subclasses must call this method every time when web view has been created
261 // or recreated. This method should not be called if a web view property has
262 // changed (e.g. view's background color). Web controller adds |webView| to its
264 - (void)webViewDidChange
;
266 // Updates the internal state and informs the delegate that any outstanding load
267 // operations are cancelled.
268 - (void)loadCancelled
;
270 // Aborts any load for both the web view and web controller.
273 // Returns the URL that the navigation system believes should be currently
275 // TODO(stuartmorgan):Remove this in favor of more specific getters.
276 - (const GURL
&)currentNavigationURL
;
278 // Called when the web page has changed document and/or URL, and so the page
279 // navigation should be reported to the delegate, and internal state updated to
280 // reflect the fact that the navigation has occurred.
281 // TODO(stuartmorgan): The code conflates URL changes and document object
282 // changes; the two need to be separated and handled differently.
283 - (void)webPageChanged
;
285 // Injects all scripts registered for early injection, as well as the window ID,
286 // if necssary. If they are already injected, this is a no-op.
287 - (void)injectEarlyInjectionScripts
;
289 // Inject windowID if not yet injected.
290 - (void)injectWindowID
;
292 // Called when a page (native or web) has actually started loading (i.e., for
293 // a web page the document has actually changed), or after the load request has
294 // been registered for a non-document-changing URL change. Updates internal
295 // state not specific to web pages, and informs the delegate.
296 - (void)didStartLoadingURL
:(const GURL
&)URL updateHistory
:(BOOL
)updateHistory
;
298 // Should be called with YES if a user interaction has been registered at any
299 // time once the page has loaded.
300 - (void)setUserInteractionRegistered
:(BOOL
)flag
;
302 // Returns YES if the user interacted with the page recently.
303 - (BOOL
)userClickedRecently
;
305 // Returns whether the desktop user agent should be used when setting the user
307 - (BOOL
)useDesktopUserAgent
;
309 // Called when SSL status has been updated for the current navigation item.
310 - (void)didUpdateSSLStatusForCurrentNavigationItem
;
312 // Processes the given web invocation; urlSchemeIsWebInvoke: must return YES
313 // for the given URL. |request| should be the request associated with that load.
314 - (void)handleWebInvokeURL
:(const GURL
&)url request
:(NSURLRequest
*)request
;
316 // Returns YES if the given load request should be allowed to continue. If this
317 // returns NO, the load should be cancelled. |targetFrame| contains information
318 // about the frame to which navigation is targeted, can be null.
319 // |isLinkClick| should indicate whether the navigation is the
320 // result of a link click (either directly, or via JS triggered by a link).
321 - (BOOL
)shouldAllowLoadWithRequest
:(NSURLRequest
*)request
322 targetFrame
:(const web::FrameInfo
*)targetFrame
323 isLinkClick
:(BOOL
)isLinkClick
;
325 // Prepares web controller and delegates for anticipated page change.
326 // Allows several methods to invoke webWill/DidAddPendingURL on anticipated page
327 // change, using the same cached request and calculated transition types.
328 - (void)registerLoadRequest
:(const GURL
&)URL
329 referrer
:(const web::Referrer
&)referrer
330 transition
:(ui::PageTransition
)transition
;
332 // Called when a load ends in an error.
333 // TODO(stuartmorgan): Figure out if there's actually enough shared logic that
334 // this makes sense. At the very least remove inMainFrame since that only makes
335 // sense for UIWebView.
336 - (void)handleLoadError
:(NSError
*)error inMainFrame
:(BOOL
)inMainFrame
;
338 // Update the appropriate parts of the model and broadcast to the embedder. This
339 // may be called multiple times and thus must be idempotent.
340 - (void)loadCompleteWithSuccess
:(BOOL
)loadSuccess
;
342 // Creates a new opened by DOM window and returns its autoreleased web
344 - (CRWWebController
*)createChildWebControllerWithReferrerURL
:
345 (const GURL
&)referrerURL
;
347 // Called following navigation completion to generate final navigation lifecycle
348 // events. Navigation is considered complete when the document has finished
349 // loading, or when other page load mechanics are completed on a
350 // non-document-changing URL change.
351 - (void)didFinishNavigation
;
353 // Returns the referrer policy for the given referrer policy string (as reported
355 - (web::ReferrerPolicy
)referrerPolicyFromString
:(const std::string
&)policy
;
357 // Returns YES if the popup should be blocked, NO otherwise.
358 - (BOOL
)shouldBlockPopupWithURL
:(const GURL
&)popupURL
359 sourceURL
:(const GURL
&)sourceURL
;
361 // Call to stop web controller activity, in particular to stop all network
362 // requests. Called as part of the close sequence if it hasn't already been
363 // halted; should also be called from the web delegate as part of any shutdown
364 // sequence which doesn't call -close.
365 - (void)terminateNetworkActivity
;
367 // Acts on a single message from the JS object, parsed from JSON into a
368 // DictionaryValue. Returns NO if the format for the message was invalid.
369 - (BOOL
)respondToMessage
:(base::DictionaryValue
*)crwMessage
370 userIsInteracting
:(BOOL
)userIsInteracting
371 originURL
:(const GURL
&)originURL
;
373 // Asynchronously determines window size of the web page. |handler| cannot
375 - (void)fetchWebPageSizeWithCompletionHandler
:(void (^)(CGSize
))handler
;
377 // Tries to open a popup with the given new window information.
378 - (void)openPopupWithInfo
:(const web::NewWindowInfo
&)windowInfo
;
380 // Returns the current entry from the underlying session controller.
381 // TODO(stuartmorgan): Audit all calls to these methods; these are just wrappers
382 // around the same logic as GetActiveEntry, so should probably not be used for
383 // the same reason that GetActiveEntry is deprecated. (E.g., page operations
384 // should generally be dealing with the last commited entry, not a pending
386 - (CRWSessionEntry
*)currentSessionEntry
;
387 // Returns the navigation item for the current page.
388 - (web::NavigationItem
*)currentNavItem
;
390 // The HTTP headers associated with the current navigation item. These are nil
391 // unless the request was a POST.
392 - (NSDictionary
*)currentHTTPHeaders
;
394 // Returns the referrer for the current page.
395 - (web::Referrer
)currentReferrer
;
397 // Returns the referrer for current navigation item. May be empty.
398 - (web::Referrer
)currentSessionEntryReferrer
;
400 // Returns the current transition type.
401 - (ui::PageTransition
)currentTransition
;
403 // Returns the current entry from the underlying session controller.
404 - (CRWSessionEntry
*)currentSessionEntry
;
406 // Resets pending external request information.
407 - (void)resetExternalRequest
;
411 #endif // IOS_WEB_WEB_STATE_UI_CRW_WEB_CONTROLLER_PROTECTED_H_