blob: a538c9418eeda9f5eb9b83c1d182226bc7953e32 [file] [log] [blame]
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "ios/web/web_state/ui/crw_web_controller.h"
#import <WebKit/WebKit.h>
#import <objc/runtime.h>
#include <stddef.h>
#include <cmath>
#include <limits>
#include <memory>
#include <utility>
#include <vector>
#include "base/base64.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/containers/mru_cache.h"
#include "base/feature_list.h"
#include "base/i18n/i18n_constants.h"
#import "base/ios/block_types.h"
#include "base/ios/ios_util.h"
#import "base/ios/ns_error_util.h"
#include "base/json/string_escape.h"
#include "base/logging.h"
#include "base/mac/bundle_locations.h"
#include "base/mac/foundation_util.h"
#include "base/mac/scoped_cftyperef.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/user_metrics.h"
#include "base/metrics/user_metrics_action.h"
#include "base/strings/string_util.h"
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "base/values.h"
#include "crypto/symmetric_key.h"
#import "ios/net/http_response_headers_util.h"
#import "ios/web/find_in_page/find_in_page_manager_impl.h"
#include "ios/web/history_state_util.h"
#import "ios/web/interstitials/web_interstitial_impl.h"
#import "ios/web/navigation/crw_navigation_item_holder.h"
#include "ios/web/navigation/error_retry_state_machine.h"
#import "ios/web/navigation/navigation_item_impl.h"
#import "ios/web/navigation/navigation_manager_impl.h"
#include "ios/web/navigation/navigation_manager_util.h"
#import "ios/web/navigation/wk_navigation_util.h"
#include "ios/web/net/cert_host_pair.h"
#import "ios/web/net/crw_cert_verification_controller.h"
#import "ios/web/net/crw_ssl_status_updater.h"
#include "ios/web/public/browser_state.h"
#import "ios/web/public/download/download_controller.h"
#include "ios/web/public/favicon_url.h"
#include "ios/web/public/features.h"
#import "ios/web/public/java_script_dialog_presenter.h"
#import "ios/web/public/navigation_item.h"
#import "ios/web/public/navigation_manager.h"
#include "ios/web/public/referrer.h"
#include "ios/web/public/referrer_util.h"
#include "ios/web/public/ssl_status.h"
#import "ios/web/public/url_scheme_util.h"
#include "ios/web/public/url_util.h"
#import "ios/web/public/web_client.h"
#import "ios/web/public/web_state/context_menu_params.h"
#import "ios/web/public/web_state/js/crw_js_injection_manager.h"
#import "ios/web/public/web_state/js/crw_js_injection_receiver.h"
#import "ios/web/public/web_state/page_display_state.h"
#import "ios/web/public/web_state/ui/crw_content_view.h"
#import "ios/web/public/web_state/ui/crw_context_menu_delegate.h"
#import "ios/web/public/web_state/ui/crw_native_content.h"
#import "ios/web/public/web_state/ui/crw_native_content_provider.h"
#import "ios/web/public/web_state/ui/crw_web_view_content_view.h"
#import "ios/web/public/web_state/ui/crw_web_view_scroll_view_proxy.h"
#include "ios/web/public/web_state/url_verification_constants.h"
#include "ios/web/public/web_state/web_frame.h"
#include "ios/web/public/web_state/web_frame_util.h"
#import "ios/web/public/web_state/web_state.h"
#include "ios/web/public/web_state/web_state_interface_provider.h"
#import "ios/web/public/web_state/web_state_policy_decider.h"
#include "ios/web/public/webui/web_ui_ios.h"
#import "ios/web/web_state/error_translation_util.h"
#import "ios/web/web_state/js/crw_js_post_request_loader.h"
#import "ios/web/web_state/js/crw_js_window_id_manager.h"
#import "ios/web/web_state/navigation_context_impl.h"
#import "ios/web/web_state/page_viewport_state.h"
#import "ios/web/web_state/session_certificate_policy_cache_impl.h"
#import "ios/web/web_state/ui/crw_context_menu_controller.h"
#import "ios/web/web_state/ui/crw_swipe_recognizer_provider.h"
#import "ios/web/web_state/ui/crw_web_controller.h"
#import "ios/web/web_state/ui/crw_web_controller_container_view.h"
#import "ios/web/web_state/ui/crw_web_view_navigation_proxy.h"
#import "ios/web/web_state/ui/crw_web_view_proxy_impl.h"
#import "ios/web/web_state/ui/crw_wk_navigation_states.h"
#import "ios/web/web_state/ui/crw_wk_script_message_router.h"
#import "ios/web/web_state/ui/favicon_util.h"
#include "ios/web/web_state/ui/web_kit_constants.h"
#import "ios/web/web_state/ui/wk_back_forward_list_item_holder.h"
#import "ios/web/web_state/ui/wk_navigation_action_policy_util.h"
#import "ios/web/web_state/ui/wk_navigation_action_util.h"
#import "ios/web/web_state/ui/wk_security_origin_util.h"
#import "ios/web/web_state/ui/wk_web_view_configuration_provider.h"
#import "ios/web/web_state/web_frame_impl.h"
#import "ios/web/web_state/web_frames_manager_impl.h"
#import "ios/web/web_state/web_state_impl.h"
#import "ios/web/web_state/web_view_internal_creation_util.h"
#import "ios/web/web_state/wk_web_view_security_util.h"
#import "ios/web/webui/crw_web_ui_manager.h"
#import "ios/web/webui/mojo_facade.h"
#import "net/base/mac/url_conversions.h"
#include "net/base/net_errors.h"
#include "net/cert/x509_util_ios.h"
#include "net/ssl/ssl_info.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "ui/base/page_transition_types.h"
#include "url/gurl.h"
#include "url/url_constants.h"
#if !defined(__has_feature) || !__has_feature(objc_arc)
#error "This file requires ARC support."
#endif
using web::NavigationManager;
using web::NavigationManagerImpl;
using web::WebState;
using web::WebStateImpl;
namespace {
using web::wk_navigation_util::IsPlaceholderUrl;
using web::wk_navigation_util::CreatePlaceholderUrlForUrl;
using web::wk_navigation_util::ExtractUrlFromPlaceholderUrl;
using web::wk_navigation_util::IsRestoreSessionUrl;
using web::wk_navigation_util::IsWKInternalUrl;
// Struct to capture data about a user interaction. Records the time of the
// interaction and the main document URL at that time.
struct UserInteractionEvent {
UserInteractionEvent(GURL url)
: main_document_url(url), time(CFAbsoluteTimeGetCurrent()) {}
// Main document URL at the time the interaction occurred.
GURL main_document_url;
// Time that the interaction occurred, measured in seconds since Jan 1 2001.
CFAbsoluteTime time;
};
// Keys for JavaScript command handlers context.
NSString* const kUserIsInteractingKey = @"userIsInteracting";
NSString* const kOriginURLKey = @"originURL";
NSString* const kIsMainFrame = @"isMainFrame";
// URL scheme for messages sent from javascript for asynchronous processing.
NSString* const kScriptMessageName = @"crwebinvoke";
// Message command sent when a frame becomes available.
NSString* const kFrameBecameAvailableMessageName = @"FrameBecameAvailable";
// Message command sent when a frame is unloading.
NSString* const kFrameBecameUnavailableMessageName = @"FrameBecameUnavailable";
// Values for the histogram that counts slow/fast back/forward navigations.
enum class BackForwardNavigationType {
// Fast back navigation through WKWebView back-forward list.
FAST_BACK = 0,
// Slow back navigation when back-forward list navigation is not possible.
SLOW_BACK = 1,
// Fast forward navigation through WKWebView back-forward list.
FAST_FORWARD = 2,
// Slow forward navigation when back-forward list navigation is not possible.
SLOW_FORWARD = 3,
BACK_FORWARD_NAVIGATION_TYPE_COUNT
};
// Represents cert verification error, which happened inside
// |webView:didReceiveAuthenticationChallenge:completionHandler:| and should
// be checked inside |webView:didFailProvisionalNavigation:withError:|.
struct CertVerificationError {
CertVerificationError(BOOL is_recoverable, net::CertStatus status)
: is_recoverable(is_recoverable), status(status) {}
BOOL is_recoverable;
net::CertStatus status;
};
// Type of Cache object for storing cert verification errors.
typedef base::MRUCache<web::CertHostPair, CertVerificationError>
CertVerificationErrorsCacheType;
// Maximum number of errors to store in cert verification errors cache.
// Cache holds errors only for pending navigations, so the actual number of
// stored errors is not expected to be high.
const CertVerificationErrorsCacheType::size_type kMaxCertErrorsCount = 100;
} // namespace
#pragma mark -
// A container object for any navigation information that is only available
// during pre-commit delegate callbacks, and thus must be held until the
// navigation commits and the informatino can be used.
@interface CRWWebControllerPendingNavigationInfo : NSObject {
}
// The referrer for the page.
@property(nonatomic, copy) NSString* referrer;
// The MIME type for the page.
@property(nonatomic, copy) NSString* MIMEType;
// The navigation type for the load.
@property(nonatomic, assign) WKNavigationType navigationType;
// HTTP request method for the load.
@property(nonatomic, copy) NSString* HTTPMethod;
// Whether the pending navigation has been directly cancelled before the
// navigation is committed.
// Cancelled navigations should be simply discarded without handling any
// specific error.
@property(nonatomic, assign) BOOL cancelled;
// Whether the navigation was initiated by a user gesture.
@property(nonatomic, assign) BOOL hasUserGesture;
@end
@implementation CRWWebControllerPendingNavigationInfo
- (instancetype)init {
if ((self = [super init])) {
_navigationType = WKNavigationTypeOther;
}
return self;
}
@end
@interface CRWWebController ()<CRWContextMenuDelegate,
CRWNativeContentDelegate,
CRWSSLStatusUpdaterDataSource,
CRWSSLStatusUpdaterDelegate,
CRWWebControllerContainerViewDelegate,
CRWWebViewScrollViewProxyObserver,
WKNavigationDelegate,
WKUIDelegate> {
// The view used to display content. Must outlive |_webViewProxy|. The
// container view should be accessed through this property rather than
// |self.view| from within this class, as |self.view| triggers creation while
// |self.containerView| will return nil if the view hasn't been instantiated.
CRWWebControllerContainerView* _containerView;
// YES if the current URL load was triggered in Web Controller. NO by default
// and after web usage was disabled. Used by |-loadCurrentURLIfNecessary| to
// prevent extra loads.
BOOL _currentURLLoadWasTrigerred;
BOOL _isHalted; // YES if halted. Halting happens prior to destruction.
BOOL _isBeingDestroyed; // YES if in the process of closing.
// YES if the user has interacted with the content area since the last URL
// change.
BOOL _interactionRegisteredSinceLastURLChange;
// The actual URL of the document object (i.e., the last committed URL).
// TODO(crbug.com/549616): Remove this in favor of just updating the
// navigation manager and treating that as authoritative.
GURL _documentURL;
// Page loading phase.
web::LoadPhase _loadPhase;
// The web::PageDisplayState recorded when the page starts loading.
web::PageDisplayState _displayStateOnStartLoading;
// Whether or not the page has zoomed since the current navigation has been
// committed, either by user interaction or via |-restoreStateFromHistory|.
BOOL _pageHasZoomed;
// Whether a PageDisplayState is currently being applied.
BOOL _applyingPageState;
// Actions to execute once the page load is complete.
NSMutableArray* _pendingLoadCompleteActions;
// UIGestureRecognizers to add to the web view.
NSMutableArray* _gestureRecognizers;
// Flag to say if browsing is enabled.
BOOL _webUsageEnabled;
// The controller that tracks long press and check context menu trigger.
CRWContextMenuController* _contextMenuController;
// Whether a click is in progress.
BOOL _clickInProgress;
// Data on the recorded last user interaction.
std::unique_ptr<UserInteractionEvent> _lastUserInteraction;
// YES if there has been user interaction with views owned by this controller.
BOOL _userInteractedWithWebController;
// The time of the last page transfer start, measured in seconds since Jan 1
// 2001.
CFAbsoluteTime _lastTransferTimeInSeconds;
// Default URL (about:blank).
GURL _defaultURL;
// Whether the web page is currently performing window.history.pushState or
// window.history.replaceState
// Set to YES on window.history.willChangeState message. To NO on
// window.history.didPushState or window.history.didReplaceState.
BOOL _changingHistoryState;
// Set to YES when a hashchange event is manually dispatched for same-document
// history navigations.
BOOL _dispatchingSameDocumentHashChangeEvent;
// Object for loading POST requests with body.
CRWJSPOSTRequestLoader* _POSTRequestLoader;
// A set of script managers whose scripts have been injected into the current
// page.
// TODO(stuartmorgan): Revisit this approach; it's intended only as a stopgap
// measure to make all the existing script managers work. Longer term, there
// should probably be a couple of points where managers can register to have
// things happen automatically based on page lifecycle, and if they don't want
// to use one of those fixed points, they should make their scripts internally
// idempotent.
NSMutableSet* _injectedScriptManagers;
// Script manager for setting the windowID.
CRWJSWindowIDManager* _windowIDJSManager;
// Backs up property with the same name.
std::unique_ptr<web::MojoFacade> _mojoFacade;
// Referrer for the current page; does not include the fragment.
NSString* _currentReferrerString;
// Pending information for an in-progress page navigation. The lifetime of
// this object starts at |decidePolicyForNavigationAction| where the info is
// extracted from the request, and ends at either |didCommitNavigation| or
// |didFailProvisionalNavigation|.
CRWWebControllerPendingNavigationInfo* _pendingNavigationInfo;
// Holds all WKNavigation objects and their states which are currently in
// flight.
CRWWKNavigationStates* _navigationStates;
// The WKNavigation captured when |stopLoading| was called. Used for reporting
// WebController.EmptyNavigationManagerCausedByStopLoading UMA metric which
// helps with diagnosing a navigation related crash (crbug.com/565457).
__weak WKNavigation* _stoppedWKNavigation;
// Used to poll for a SafeBrowsing warning being displayed. This is created in
// |decidePolicyForNavigationAction| and destroyed once any of the following
// happens: 1) a SafeBrowsing warning is detected; 2) any WKNavigationDelegate
// method is called; 3) |abortLoad| is called.
base::RepeatingTimer _safeBrowsingWarningDetectionTimer;
// CRWWebUIManager object for loading WebUI pages.
CRWWebUIManager* _webUIManager;
// Updates SSLStatus for current navigation item.
CRWSSLStatusUpdater* _SSLStatusUpdater;
// Controller used for certs verification to help with blocking requests with
// bad SSL cert, presenting SSL interstitials and determining SSL status for
// Navigation Items.
CRWCertVerificationController* _certVerificationController;
// CertVerification errors which happened inside
// |webView:didReceiveAuthenticationChallenge:completionHandler:|.
// Key is leaf-cert/host pair. This storage is used to carry calculated
// cert status from |didReceiveAuthenticationChallenge:| to
// |didFailProvisionalNavigation:| delegate method.
std::unique_ptr<CertVerificationErrorsCacheType> _certVerificationErrors;
}
// If |contentView_| contains a web view, this is the web view it contains.
// If not, it's nil. When setting the property, it performs basic setup.
@property(weak, nonatomic) WKWebView* webView;
// The scroll view of |webView|.
@property(weak, nonatomic, readonly) UIScrollView* webScrollView;
// The current page state of the web view. Writing to this property
// asynchronously applies the passed value to the current web view.
@property(nonatomic, readwrite) web::PageDisplayState pageDisplayState;
// The currently displayed native controller, if any.
@property(weak, nonatomic, readwrite) id<CRWNativeContent> nativeController;
// Dictionary where keys are the names of WKWebView properties and values are
// selector names which should be called when a corresponding property has
// changed. e.g. @{ @"URL" : @"webViewURLDidChange" } means that
// -[self webViewURLDidChange] must be called every time when WKWebView.URL is
// changed.
@property(weak, nonatomic, readonly) NSDictionary* WKWebViewObservers;
// The web view's view of the current URL. During page transitions
// this may not be the same as the session history's view of the current URL.
// This method can change the state of the CRWWebController, as it will display
// an error if the returned URL is not reliable from a security point of view.
// Note that this method is expensive, so it should always be cached locally if
// it's needed multiple times in a method.
@property(nonatomic, readonly) GURL currentURL;
// Returns the referrer for the current page.
@property(nonatomic, readonly) web::Referrer currentReferrer;
// Returns YES if the user interacted with the page recently.
@property(nonatomic, readonly) BOOL userClickedRecently;
// User agent type of the transient item if any, the pending item if a
// navigation is in progress or the last committed item otherwise.
// Returns MOBILE, the default type, if navigation manager is nullptr or empty.
@property(nonatomic, readonly) web::UserAgentType userAgentType;
// Facade for Mojo API.
@property(nonatomic, readonly) web::MojoFacade* mojoFacade;
// YES if a user interaction has been registered at any time since the page has
// loaded.
@property(nonatomic, readwrite) BOOL userInteractionRegistered;
@property(nonatomic, readonly) web::WebState* webState;
// WebStateImpl instance associated with this CRWWebController, web controller
// does not own this pointer.
@property(nonatomic, readonly) web::WebStateImpl* webStateImpl;
// Returns the x, y offset the content has been scrolled.
@property(nonatomic, readonly) CGPoint scrollPosition;
// The touch tracking recognizer allowing us to decide if a navigation has user
// gesture. Lazily created.
@property(nonatomic, strong, readonly)
CRWTouchTrackingRecognizer* touchTrackingRecognizer;
// Session Information
// -------------------
// Returns NavigationManager's session controller.
@property(weak, nonatomic, readonly) CRWSessionController* sessionController;
// The associated NavigationManagerImpl.
@property(nonatomic, readonly) NavigationManagerImpl* navigationManagerImpl;
// Whether the associated WebState has an opener.
@property(nonatomic, readonly) BOOL hasOpener;
// TODO(crbug.com/692871): Remove these functions and replace with more
// appropriate NavigationItem getters.
// Returns the navigation item for the current page.
@property(nonatomic, readonly) web::NavigationItemImpl* currentNavItem;
// Returns the current transition type.
@property(nonatomic, readonly) ui::PageTransition currentTransition;
// Returns the referrer for current navigation item. May be empty.
@property(nonatomic, readonly) web::Referrer currentNavItemReferrer;
// The HTTP headers associated with the current navigation item. These are nil
// unless the request was a POST.
@property(weak, nonatomic, readonly) NSDictionary* currentHTTPHeaders;
// Extracts "Referer" [sic] value from WKNavigationAction request header.
- (NSString*)referrerFromNavigationAction:(WKNavigationAction*)action;
// Returns the current URL of the web view, and sets |trustLevel| accordingly
// based on the confidence in the verification.
- (GURL)webURLWithTrustLevel:(web::URLVerificationTrustLevel*)trustLevel;
// Loads POST request with body in |_wkWebView| by constructing an HTML page
// that executes the request through JavaScript and replaces document with the
// result.
// Note that this approach includes multiple body encodings and decodings, plus
// the data is passed to |_wkWebView| on main thread.
// This is necessary because WKWebView ignores POST request body.
// Workaround for https://bugs.webkit.org/show_bug.cgi?id=145410
// TODO(crbug.com/740987): Remove |loadPOSTRequest:| workaround once iOS 10 is
// dropped.
- (WKNavigation*)loadPOSTRequest:(NSMutableURLRequest*)request;
// Extracts navigation info from WKNavigationAction and sets it as a pending.
// Some pieces of navigation information are only known in
// |decidePolicyForNavigationAction|, but must be in a pending state until
// |didgo/Navigation| where it becames current.
- (void)updatePendingNavigationInfoFromNavigationAction:
(WKNavigationAction*)action;
// Extracts navigation info from WKNavigationResponse and sets it as a pending.
// Some pieces of navigation information are only known in
// |decidePolicyForNavigationResponse|, but must be in a pending state until
// |didCommitNavigation| where it becames current.
- (void)updatePendingNavigationInfoFromNavigationResponse:
(WKNavigationResponse*)response;
// Updates current state with any pending information. Should be called when a
// navigation is committed.
- (void)commitPendingNavigationInfo;
// Returns a NSMutableURLRequest that represents the current NavigationItem.
- (NSMutableURLRequest*)requestForCurrentNavigationItem;
// Returns the WKBackForwardListItemHolder for the current navigation item.
- (web::WKBackForwardListItemHolder*)currentBackForwardListItemHolder;
// Updates the WKBackForwardListItemHolder navigation item.
- (void)updateCurrentBackForwardListItemHolder;
// Loads a blank page directly into WKWebView as a placeholder for a Native View
// or WebUI URL. This page has the URL about:blank?for=<encoded original URL>.
// If |originalContext| is provided, reuse it for the placeholder navigation
// instead of creating a new one. See "Handling App-specific URLs"
// section of go/bling-navigation-experiment for details.
- (web::NavigationContextImpl*)
loadPlaceholderInWebViewForURL:(const GURL&)originalURL
rendererInitiated:(BOOL)rendererInitiated
forContext:(std::unique_ptr<web::NavigationContextImpl>)
originalContext;
// Executes the command specified by the ErrorRetryStateMachine.
- (void)handleErrorRetryCommand:(web::ErrorRetryCommand)command
navigationItem:(web::NavigationItemImpl*)item
navigationContext:(web::NavigationContextImpl*)context
originalNavigation:(WKNavigation*)originalNavigation;
// Loads the error page.
- (void)loadErrorPageForNavigationItem:(web::NavigationItemImpl*)item
navigationContext:(web::NavigationContextImpl*)context;
// Aborts any load for both the web view and web controller.
- (void)abortLoad;
// Updates the internal state and informs the delegate that any outstanding load
// operations are cancelled.
- (void)loadCancelled;
// If YES, the page should be closed if it successfully redirects to a native
// application, for example if a new tab redirects to the App Store.
- (BOOL)shouldClosePageOnNativeApplicationLoad;
// Updates URL for navigation context and navigation item.
- (void)didReceiveRedirectForNavigation:(web::NavigationContextImpl*)context
withURL:(const GURL&)URL;
// Called following navigation completion to generate final navigation lifecycle
// events. Navigation is considered complete when the document has finished
// loading, or when other page load mechanics are completed on a
// non-document-changing URL change.
- (void)didFinishNavigation:(web::NavigationContextImpl*)context;
// Update the appropriate parts of the model and broadcast to the embedder. This
// may be called multiple times and thus must be idempotent.
- (void)loadCompleteWithSuccess:(BOOL)loadSuccess
forContext:(web::NavigationContextImpl*)context;
// Called after URL is finished loading and _loadPhase is set to PAGE_LOADED.
// |context| contains information about the navigation associated with the URL.
// It is nil if currentURL is invalid.
- (void)didFinishWithURL:(const GURL&)currentURL
loadSuccess:(BOOL)loadSuccess
context:(nullable const web::NavigationContextImpl*)context;
// Acts on a single message from the JS object, parsed from JSON into a
// DictionaryValue. Returns NO if the format for the message was invalid.
- (BOOL)respondToMessage:(base::DictionaryValue*)crwMessage
userIsInteracting:(BOOL)userIsInteracting
originURL:(const GURL&)originURL
isMainFrame:(BOOL)isMainFrame
senderFrame:(web::WebFrame*)senderFrame;
// Called when web controller receives a new message from the web page.
- (void)didReceiveScriptMessage:(WKScriptMessage*)message;
// Returns a new script which wraps |script| with windowID check so |script| is
// not evaluated on windowID mismatch.
- (NSString*)scriptByAddingWindowIDCheckForScript:(NSString*)script;
// Attempts to handle a script message. Returns YES on success, NO otherwise.
- (BOOL)respondToWKScriptMessage:(WKScriptMessage*)scriptMessage;
// Handles frame became available message.
- (void)frameBecameAvailableWithMessage:(WKScriptMessage*)message;
// Handles frame became unavailable message.
- (void)frameBecameUnavailableWithMessage:(WKScriptMessage*)message;
// Clears the frames list.
- (void)removeAllWebFrames;
// Registers load request with empty referrer and link or client redirect
// transition based on user interaction state. Returns navigation context for
// this request.
- (std::unique_ptr<web::NavigationContextImpl>)
registerLoadRequestForURL:(const GURL&)URL
sameDocumentNavigation:(BOOL)sameDocumentNavigation
hasUserGesture:(BOOL)hasUserGesture
rendererInitiated:(BOOL)rendererInitiated
placeholderNavigation:(BOOL)placeholderNavigation;
// Prepares web controller and delegates for anticipated page change.
// Allows several methods to invoke webWill/DidAddPendingURL on anticipated page
// change, using the same cached request and calculated transition types.
// Returns navigation context for this request.
- (std::unique_ptr<web::NavigationContextImpl>)
registerLoadRequestForURL:(const GURL&)URL
referrer:(const web::Referrer&)referrer
transition:(ui::PageTransition)transition
sameDocumentNavigation:(BOOL)sameDocumentNavigation
hasUserGesture:(BOOL)hasUserGesture
rendererInitiated:(BOOL)rendererInitiated
placeholderNavigation:(BOOL)placeholderNavigation;
// Maps WKNavigationType to ui::PageTransition.
- (ui::PageTransition)pageTransitionFromNavigationType:
(WKNavigationType)navigationType;
// Returns YES if the current live view is a web view with an image MIME type.
- (BOOL)contentIsImage;
// Restores the state for this page from session history.
- (void)restoreStateFromHistory;
// Extracts the current page's viewport tag information and calls |completion|.
// If the page has changed before the viewport tag is successfully extracted,
// |completion| is called with nullptr.
typedef void (^ViewportStateCompletion)(const web::PageViewportState*);
- (void)extractViewportTagWithCompletion:(ViewportStateCompletion)completion;
// Called by NSNotificationCenter upon orientation changes.
- (void)orientationDidChange;
// Queries the web view for the user-scalable meta tag and calls
// |-applyPageDisplayState:userScalable:| with the result.
- (void)applyPageDisplayState:(const web::PageDisplayState&)displayState;
// Restores state of the web view's scroll view from |scrollState|.
// |isUserScalable| represents the value of user-scalable meta tag.
- (void)applyPageDisplayState:(const web::PageDisplayState&)displayState
userScalable:(BOOL)isUserScalable;
// Calls the zoom-preparation UIScrollViewDelegate callbacks on the web view.
// This is called before |-applyWebViewScrollZoomScaleFromScrollState:|.
- (void)prepareToApplyWebViewScrollZoomScale;
// Calls the zoom-completion UIScrollViewDelegate callbacks on the web view.
// This is called after |-applyWebViewScrollZoomScaleFromScrollState:|.
- (void)finishApplyingWebViewScrollZoomScale;
// Sets zoom scale value for webview scroll view from |zoomState|.
- (void)applyWebViewScrollZoomScaleFromZoomState:
(const web::PageZoomState&)zoomState;
// Sets scroll offset value for webview scroll view from |scrollState|.
- (void)applyWebViewScrollOffsetFromScrollState:
(const web::PageScrollState&)scrollState;
// Sets _documentURL to newURL, and updates any relevant state information.
- (void)setDocumentURL:(const GURL&)newURL
context:(web::NavigationContextImpl*)context;
// Sets last committed NavigationItem's title to the given |title|, which can
// not be nil.
- (void)setNavigationItemTitle:(NSString*)title;
// Returns YES if the current navigation item corresponds to a web page
// loaded by a POST request.
- (BOOL)isCurrentNavigationItemPOST;
// Returns YES if current navigation item is WKNavigationTypeBackForward.
- (BOOL)isCurrentNavigationBackForward;
// Returns YES if the given WKBackForwardListItem is valid to use for
// navigation.
- (BOOL)isBackForwardListItemValid:(WKBackForwardListItem*)item;
// Finds all the scrollviews in the view hierarchy and makes sure they do not
// interfere with scroll to top when tapping the statusbar.
- (void)optOutScrollsToTopForSubviews;
// Returns YES if the navigation action is associated with a main frame request.
- (BOOL)isMainFrameNavigationAction:(WKNavigationAction*)action;
// Updates SSL status for the current navigation item based on the information
// provided by web view.
- (void)updateSSLStatusForCurrentNavigationItem;
// Called when a load ends in an SSL error and certificate chain.
- (void)handleSSLCertError:(NSError*)error
forNavigation:(WKNavigation*)navigation;
// Used in webView:didReceiveAuthenticationChallenge:completionHandler: to
// reply with NSURLSessionAuthChallengeDisposition and credentials.
- (void)processAuthChallenge:(NSURLAuthenticationChallenge*)challenge
forCertAcceptPolicy:(web::CertAcceptPolicy)policy
certStatus:(net::CertStatus)certStatus
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition,
NSURLCredential*))completionHandler;
// Used in webView:didReceiveAuthenticationChallenge:completionHandler: to reply
// with NSURLSessionAuthChallengeDisposition and credentials.
- (void)handleHTTPAuthForChallenge:(NSURLAuthenticationChallenge*)challenge
completionHandler:
(void (^)(NSURLSessionAuthChallengeDisposition,
NSURLCredential*))completionHandler;
// Used in webView:didReceiveAuthenticationChallenge:completionHandler: to reply
// with NSURLSessionAuthChallengeDisposition and credentials.
+ (void)processHTTPAuthForUser:(NSString*)user
password:(NSString*)password
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition,
NSURLCredential*))completionHandler;
// Returns YES if a SafeBrowsing warning is currently displayed within
// WKWebView.
- (BOOL)isSafeBrowsingWarningDisplayedInWebView;
// Returns context for pending navigation that has |URL|. null if there is no
// matching pending navigation.
- (web::NavigationContextImpl*)contextForPendingMainFrameNavigationWithURL:
(const GURL&)URL;
// Loads request for the URL of the current navigation item. Subclasses may
// choose to build a new NSURLRequest and call |loadRequest| on the underlying
// web view, or use native web view navigation where possible (for example,
// going back and forward through the history stack).
- (void)loadRequestForCurrentNavigationItem;
// Reports Navigation.IOSWKWebViewSlowFastBackForward UMA. No-op if pending
// navigation is not back forward navigation.
- (void)reportBackForwardNavigationTypeForFastNavigation:(BOOL)isFast;
// Sets up WebUI for URL.
- (void)createWebUIForURL:(const GURL&)URL;
// Clears WebUI, if one exists.
- (void)clearWebUI;
@end
namespace {
NSString* const kReferrerHeaderName = @"Referer"; // [sic]
// The duration of the period following a screen touch during which the user is
// still considered to be interacting with the page.
const NSTimeInterval kMaximumDelayForUserInteractionInSeconds = 2;
// URLs that are fed into UIWebView as history push/replace get escaped,
// potentially changing their format. Code that attempts to determine whether a
// URL hasn't changed can be confused by those differences though, so method
// will round-trip a URL through the escaping process so that it can be adjusted
// pre-storing, to allow later comparisons to work as expected.
GURL URLEscapedForHistory(const GURL& url) {
// TODO(stuartmorgan): This is a very large hammer; see if limited unicode
// escaping would be sufficient.
return net::GURLWithNSURL(net::NSURLWithGURL(url));
}
} // namespace
@implementation CRWWebController
// Synthesize as it is readonly.
@synthesize touchTrackingRecognizer = _touchTrackingRecognizer;
#pragma mark - Object lifecycle
- (instancetype)initWithWebState:(WebStateImpl*)webState {
self = [super init];
if (self) {
_webStateImpl = webState;
_webUsageEnabled = YES;
if (web::GetWebClient()->IsSlimNavigationManagerEnabled())
_allowsBackForwardNavigationGestures = YES;
DCHECK(_webStateImpl);
// Load phase when no WebView present is 'loaded' because this represents
// the idle state.
_loadPhase = web::PAGE_LOADED;
// Content area is lazily instantiated.
_defaultURL = GURL(url::kAboutBlankURL);
_jsInjectionReceiver =
[[CRWJSInjectionReceiver alloc] initWithEvaluator:self];
_webViewProxy = [[CRWWebViewProxyImpl alloc] initWithWebController:self];
[[_webViewProxy scrollViewProxy] addObserver:self];
_gestureRecognizers = [[NSMutableArray alloc] init];
_pendingLoadCompleteActions = [[NSMutableArray alloc] init];
web::BrowserState* browserState = _webStateImpl->GetBrowserState();
_certVerificationController = [[CRWCertVerificationController alloc]
initWithBrowserState:browserState];
_certVerificationErrors =
std::make_unique<CertVerificationErrorsCacheType>(kMaxCertErrorsCount);
_navigationStates = [[CRWWKNavigationStates alloc] init];
web::WebFramesManagerImpl::CreateForWebState(_webStateImpl);
web::FindInPageManagerImpl::CreateForWebState(_webStateImpl);
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(orientationDidChange)
name:UIApplicationDidChangeStatusBarOrientationNotification
object:nil];
}
return self;
}
- (void)dealloc {
DCHECK([NSThread isMainThread]);
DCHECK(_isBeingDestroyed); // 'close' must have been called already.
DCHECK(!_webView);
}
#pragma mark - Public property accessors
- (void)setWebUsageEnabled:(BOOL)enabled {
if (_webUsageEnabled == enabled)
return;
// WKWebView autoreleases its WKProcessPool on removal from superview.
// Deferring WKProcessPool deallocation may lead to issues with cookie
// clearing and and Browsing Data Partitioning implementation.
@autoreleasepool {
if (!enabled) {
[self removeWebView];
}
}
_webUsageEnabled = enabled;
// WKWebView autoreleases its WKProcessPool on removal from superview.
// Deferring WKProcessPool deallocation may lead to issues with cookie
// clearing and and Browsing Data Partitioning implementation.
@autoreleasepool {
[self setNativeControllerWebUsageEnabled:_webUsageEnabled];
if (enabled) {
// Don't create the web view; let it be lazy created as needed.
} else {
self.webStateImpl->ClearTransientContent();
_touchTrackingRecognizer.touchTrackingDelegate = nil;
_touchTrackingRecognizer = nil;
_currentURLLoadWasTrigerred = NO;
}
}
}
- (UIView*)view {
[self ensureContainerViewCreated];
DCHECK(_containerView);
return _containerView;
}
- (id<CRWWebViewNavigationProxy>)webViewNavigationProxy {
return static_cast<id<CRWWebViewNavigationProxy>>(self.webView);
}
- (UIView*)viewForPrinting {
// Printing is not supported for native controllers.
return self.webView;
}
- (double)loadingProgress {
return [self.webView estimatedProgress];
}
- (void)setAllowsBackForwardNavigationGestures:
(BOOL)allowsBackForwardNavigationGestures {
// Store it to an instance variable as well as
// self.webView.allowsBackForwardNavigationGestures because self.webView may
// be nil. When self.webView is nil, it will be set later in -setWebView:.
_allowsBackForwardNavigationGestures = allowsBackForwardNavigationGestures;
self.webView.allowsBackForwardNavigationGestures =
allowsBackForwardNavigationGestures;
}
#pragma mark - Private properties accessors
- (void)setWebView:(WKWebView*)webView {
DCHECK_NE(_webView, webView);
// Unwind the old web view.
// TODO(crbug.com/543374): Remove CRWWKScriptMessageRouter once
// crbug.com/543374 is fixed.
CRWWKScriptMessageRouter* messageRouter =
[self webViewConfigurationProvider].GetScriptMessageRouter();
if (_webView) {
[messageRouter removeAllScriptMessageHandlersForWebView:_webView];
}
[_webView setNavigationDelegate:nil];
[_webView setUIDelegate:nil];
for (NSString* keyPath in self.WKWebViewObservers) {
[_webView removeObserver:self forKeyPath:keyPath];
}
_webView = webView;
// Set up the new web view.
if (webView) {
__weak CRWWebController* weakSelf = self;
[messageRouter
setScriptMessageHandler:^(WKScriptMessage* message) {
[weakSelf didReceiveScriptMessage:message];
}
name:kScriptMessageName
webView:webView];
[messageRouter
setScriptMessageHandler:^(WKScriptMessage* message) {
[weakSelf frameBecameAvailableWithMessage:message];
}
name:kFrameBecameAvailableMessageName
webView:webView];
[messageRouter
setScriptMessageHandler:^(WKScriptMessage* message) {
[weakSelf frameBecameUnavailableWithMessage:message];
}
name:kFrameBecameUnavailableMessageName
webView:webView];
_windowIDJSManager = [[CRWJSWindowIDManager alloc] initWithWebView:webView];
} else {
_windowIDJSManager = nil;
}
[_webView setNavigationDelegate:self];
[_webView setUIDelegate:self];
for (NSString* keyPath in self.WKWebViewObservers) {
[_webView addObserver:self forKeyPath:keyPath options:0 context:nullptr];
}
_webView.allowsBackForwardNavigationGestures =
_allowsBackForwardNavigationGestures;
_injectedScriptManagers = [[NSMutableSet alloc] init];
[self setDocumentURL:_defaultURL context:nullptr];
}
- (UIScrollView*)webScrollView {
return self.webView.scrollView;
}
- (web::PageDisplayState)pageDisplayState {
web::PageDisplayState displayState;
// If a native controller is present, record its display state instead of that
// of the underlying placeholder webview.
if (self.nativeController) {
if ([self.nativeController respondsToSelector:@selector(contentOffset)]) {
displayState.scroll_state().set_content_offset(
[self.nativeController contentOffset]);
}
if ([self.nativeController respondsToSelector:@selector(contentInset)]) {
displayState.scroll_state().set_content_inset(
[self.nativeController contentInset]);
}
} else if (self.webView) {
displayState.set_scroll_state(web::PageScrollState(
self.scrollPosition, self.webScrollView.contentInset));
UIScrollView* scrollView = self.webScrollView;
displayState.zoom_state().set_minimum_zoom_scale(
scrollView.minimumZoomScale);
displayState.zoom_state().set_maximum_zoom_scale(
scrollView.maximumZoomScale);
displayState.zoom_state().set_zoom_scale(scrollView.zoomScale);
}
return displayState;
}
- (void)setPageDisplayState:(web::PageDisplayState)displayState {
if (!displayState.IsValid())
return;
if (self.webView) {
// Page state is restored after a page load completes. If the user has
// scrolled or changed the zoom scale while the page is still loading, don't
// restore any state since it will confuse the user.
web::PageDisplayState currentPageDisplayState = self.pageDisplayState;
if (currentPageDisplayState.scroll_state() ==
_displayStateOnStartLoading.scroll_state() &&
!_pageHasZoomed) {
[self applyPageDisplayState:displayState];
}
}
}
- (id<CRWNativeContent>)nativeController {
return [_containerView nativeController];
}
- (void)setNativeController:(id<CRWNativeContent>)nativeController {
// Check for pointer equality.
if (self.nativeController == nativeController)
return;
// Unset the delegate on the previous instance.
if ([self.nativeController respondsToSelector:@selector(setDelegate:)])
[self.nativeController setDelegate:nil];
[_containerView displayNativeContent:nativeController];
[self setNativeControllerWebUsageEnabled:_webUsageEnabled];
}
- (NSDictionary*)WKWebViewObservers {
return @{
@"serverTrust" : @"webViewSecurityFeaturesDidChange",
@"estimatedProgress" : @"webViewEstimatedProgressDidChange",
@"hasOnlySecureContent" : @"webViewSecurityFeaturesDidChange",
@"title" : @"webViewTitleDidChange",
@"loading" : @"webViewLoadingStateDidChange",
@"URL" : @"webViewURLDidChange",
@"canGoForward" : @"webViewBackForwardStateDidChange",
@"canGoBack" : @"webViewBackForwardStateDidChange"
};
}
- (GURL)currentURL {
web::URLVerificationTrustLevel trustLevel =
web::URLVerificationTrustLevel::kNone;
return [self currentURLWithTrustLevel:&trustLevel];
}
- (web::Referrer)currentReferrer {
// Referrer string doesn't include the fragment, so in cases where the
// previous URL is equal to the current referrer plus the fragment the
// previous URL is returned as current referrer.
NSString* referrerString = _currentReferrerString;
// In case of an error evaluating the JavaScript simply return empty string.
if ([referrerString length] == 0)
return web::Referrer();
web::NavigationItem* item = self.currentNavItem;
GURL navigationURL = item ? item->GetVirtualURL() : GURL::EmptyGURL();
NSString* previousURLString = base::SysUTF8ToNSString(navigationURL.spec());
// Check if the referrer is equal to the previous URL minus the hash symbol.
// L'#' is used to convert the char '#' to a unichar.
if ([previousURLString length] > [referrerString length] &&
[previousURLString hasPrefix:referrerString] &&
[previousURLString characterAtIndex:[referrerString length]] == L'#') {
referrerString = previousURLString;
}
// Since referrer is being extracted from the destination page, the correct
// policy from the origin has *already* been applied. Since the extracted URL
// is the post-policy value, and the source policy is no longer available,
// the policy is set to Always so that whatever WebKit decided to send will be
// re-sent when replaying the entry.
// TODO(stuartmorgan): When possible, get the real referrer and policy in
// advance and use that instead. https://crbug.com/227769.
return web::Referrer(GURL(base::SysNSStringToUTF8(referrerString)),
web::ReferrerPolicyAlways);
}
- (BOOL)userClickedRecently {
// Scrolling generates a pair of touch on/off event which causes
// _lastUserInteraction to register that there was user interaction.
// Checks for scrolling first to override time-based click heuristics.
BOOL scrolling = [[self webScrollView] isDragging] ||
[[self webScrollView] isDecelerating];
if (scrolling)
return NO;
if (!_lastUserInteraction)
return NO;
return _clickInProgress ||
((CFAbsoluteTimeGetCurrent() - _lastUserInteraction->time) <
kMaximumDelayForUserInteractionInSeconds);
}
- (web::UserAgentType)userAgentType {
web::NavigationItem* item = self.currentNavItem;
return item ? item->GetUserAgentType() : web::UserAgentType::MOBILE;
}
- (web::MojoFacade*)mojoFacade {
if (!_mojoFacade) {
service_manager::mojom::InterfaceProvider* interfaceProvider =
self.webStateImpl->GetWebStateInterfaceProvider();
_mojoFacade.reset(new web::MojoFacade(interfaceProvider, self));
}
return _mojoFacade.get();
}
- (void)setUserInteractionRegistered:(BOOL)flag {
_userInteractionRegistered = flag;
if (flag)
_interactionRegisteredSinceLastURLChange = YES;
}
- (WebState*)webState {
return _webStateImpl;
}
- (CGPoint)scrollPosition {
return self.webScrollView.contentOffset;
}
- (CRWTouchTrackingRecognizer*)touchTrackingRecognizer {
if (!_touchTrackingRecognizer) {
_touchTrackingRecognizer =
[[CRWTouchTrackingRecognizer alloc] initWithDelegate:self];
}
return _touchTrackingRecognizer;
}
#pragma mark Session Information
- (CRWSessionController*)sessionController {
NavigationManagerImpl* navigationManager = self.navigationManagerImpl;
return navigationManager ? navigationManager->GetSessionController() : nil;
}
- (NavigationManagerImpl*)navigationManagerImpl {
return self.webStateImpl ? &(self.webStateImpl->GetNavigationManagerImpl())
: nil;
}
- (BOOL)hasOpener {
return self.webStateImpl ? self.webStateImpl->HasOpener() : NO;
}
- (web::NavigationItemImpl*)currentNavItem {
return self.navigationManagerImpl
? self.navigationManagerImpl->GetCurrentItemImpl()
: nullptr;
}
- (ui::PageTransition)currentTransition {
if (self.currentNavItem)
return self.currentNavItem->GetTransitionType();
else
return ui::PageTransitionFromInt(0);
}
- (web::Referrer)currentNavItemReferrer {
web::NavigationItem* currentItem = self.currentNavItem;
return currentItem ? currentItem->GetReferrer() : web::Referrer();
}
- (NSDictionary*)currentHTTPHeaders {
web::NavigationItem* currentItem = self.currentNavItem;
return currentItem ? currentItem->GetHttpRequestHeaders() : nil;
}
#pragma mark - ** Public Methods **
#pragma mark - Header public methods
- (web::NavigationItemImpl*)lastPendingItemForNewNavigation {
WKNavigation* navigation =
[_navigationStates lastNavigationWithPendingItemInNavigationContext];
if (!navigation)
return nullptr;
web::NavigationContextImpl* context =
[_navigationStates contextForNavigation:navigation];
return context->GetItem();
}
- (void)showTransientContentView:(CRWContentView*)contentView {
DCHECK(contentView);
DCHECK(contentView.scrollView);
// TODO(crbug.com/556848) Reenable DCHECK when |CRWWebControllerContainerView|
// is restructured so that subviews are not added during |layoutSubviews|.
// DCHECK([contentView.scrollView isDescendantOfView:contentView]);
[_containerView displayTransientContent:contentView];
}
- (void)clearTransientContentView {
// Early return if there is no transient content view.
if (![_containerView transientContentView])
return;
// Remove the transient content view from the hierarchy.
[_containerView clearTransientContentView];
}
// Stop doing stuff, especially network stuff. Close the request tracker.
- (void)terminateNetworkActivity {
DCHECK(!_isHalted);
_isHalted = YES;
// Cancel all outstanding perform requests, and clear anything already queued
// (since this may be called from within the handling loop) to prevent any
// asynchronous JavaScript invocation handling from continuing.
[NSObject cancelPreviousPerformRequestsWithTarget:self];
}
- (void)dismissModals {
if ([self.nativeController respondsToSelector:@selector(dismissModals)])
[self.nativeController dismissModals];
}
// Caller must reset the delegate before calling.
- (void)close {
self.webStateImpl->CancelDialogs();
_SSLStatusUpdater = nil;
self.nativeProvider = nil;
self.swipeRecognizerProvider = nil;
if ([self.nativeController respondsToSelector:@selector(close)])
[self.nativeController close];
if (!_isHalted) {
[self terminateNetworkActivity];
}
// Mark the destruction sequence has started, in case someone else holds a
// strong reference and tries to continue using the tab.
DCHECK(!_isBeingDestroyed);
_isBeingDestroyed = YES;
// Remove the web view now. Otherwise, delegate callbacks occur.
[self removeWebView];
// Explicitly reset content to clean up views and avoid dangling KVO
// observers.
[_containerView resetContent];
_webStateImpl = nullptr;
DCHECK(!self.webView);
// TODO(crbug.com/662860): Don't set the delegate to nil.
[_containerView setDelegate:nil];
if ([self.nativeController respondsToSelector:@selector(setDelegate:)]) {
[self.nativeController setDelegate:nil];
}
_touchTrackingRecognizer.touchTrackingDelegate = nil;
[[_webViewProxy scrollViewProxy] removeObserver:self];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (BOOL)isViewAlive {
return !_webProcessCrashed && [_containerView isViewAlive];
}
- (BOOL)contentIsHTML {
if (!self.webView)
return NO;
std::string MIMEType = self.webState->GetContentsMimeType();
return MIMEType == "text/html" || MIMEType == "application/xhtml+xml" ||
MIMEType == "application/xml";
}
- (GURL)currentURLWithTrustLevel:(web::URLVerificationTrustLevel*)trustLevel {
DCHECK(trustLevel) << "Verification of the trustLevel state is mandatory";
// The web view URL is the current URL only if it is neither a placeholder URL
// (used to hold WKBackForwardListItem for WebUI and Native Content views) nor
// a restore_session.html (used to replay session history in WKWebView).
// TODO(crbug.com/738020): Investigate if this method is still needed and if
// it can be implemented using NavigationManager API after removal of legacy
// navigation stack.
GURL webViewURL = net::GURLWithNSURL(self.webView.URL);
if (self.webView && !IsWKInternalUrl(webViewURL)) {
return [self webURLWithTrustLevel:trustLevel];
}
// Any non-web URL source is trusted.
*trustLevel = web::URLVerificationTrustLevel::kAbsolute;
if (self.nativeController) {
if ([self.nativeController respondsToSelector:@selector(virtualURL)]) {
return [self.nativeController virtualURL];
} else {
return [self.nativeController url];
}
}
web::NavigationItem* item =
self.navigationManagerImpl
->GetLastCommittedItemInCurrentOrRestoredSession();
return item ? item->GetVirtualURL() : GURL::EmptyGURL();
}
- (void)reloadWithRendererInitiatedNavigation:(BOOL)rendererInitiated {
// Clear last user interaction.
// TODO(crbug.com/546337): Move to after the load commits, in the subclass
// implementation. This will be inaccurate if the reload fails or is
// cancelled.
_lastUserInteraction = nullptr;
base::RecordAction(base::UserMetricsAction("Reload"));
GURL URL = self.currentNavItem->GetURL();
if ([self shouldLoadURLInNativeView:URL]) {
std::unique_ptr<web::NavigationContextImpl> navigationContext = [self
registerLoadRequestForURL:URL
referrer:self.currentNavItemReferrer
transition:ui::PageTransition::PAGE_TRANSITION_RELOAD
sameDocumentNavigation:NO
hasUserGesture:YES
rendererInitiated:rendererInitiated
placeholderNavigation:NO];
self.webStateImpl->OnNavigationStarted(navigationContext.get());
[self didStartLoading];
self.navigationManagerImpl->CommitPendingItem(
navigationContext->ReleaseItem());
[self.nativeController reload];
navigationContext->SetHasCommitted(true);
self.webStateImpl->OnNavigationFinished(navigationContext.get());
[self loadCompleteWithSuccess:YES forContext:nullptr];
} else {
web::NavigationItem* transientItem =
self.navigationManagerImpl->GetTransientItem();
if (transientItem) {
// If there's a transient item, a reload is considered a new navigation to
// the transient item's URL (as on other platforms).
NavigationManager::WebLoadParams reloadParams(transientItem->GetURL());
reloadParams.transition_type = ui::PAGE_TRANSITION_RELOAD;
reloadParams.extra_headers =
[transientItem->GetHttpRequestHeaders() copy];
self.webState->GetNavigationManager()->LoadURLWithParams(reloadParams);
} else {
self.currentNavItem->SetTransitionType(
ui::PageTransition::PAGE_TRANSITION_RELOAD);
if (web::GetWebClient()->IsSlimNavigationManagerEnabled() &&
!web::GetWebClient()->IsAppSpecificURL(
net::GURLWithNSURL(self.webView.URL))) {
// New navigation manager can delegate directly to WKWebView to reload
// for non-app-specific URLs. The necessary navigation states will be
// updated in WKNavigationDelegate callbacks.
WKNavigation* navigation = [self.webView reload];
[_navigationStates setState:web::WKNavigationState::REQUESTED
forNavigation:navigation];
std::unique_ptr<web::NavigationContextImpl> navigationContext = [self
registerLoadRequestForURL:URL
referrer:self.currentNavItemReferrer
transition:ui::PageTransition::PAGE_TRANSITION_RELOAD
sameDocumentNavigation:NO
hasUserGesture:YES
rendererInitiated:rendererInitiated
placeholderNavigation:NO];
[_navigationStates setContext:std::move(navigationContext)
forNavigation:navigation];
} else {
[self loadCurrentURLWithRendererInitiatedNavigation:rendererInitiated];
}
}
}
}
- (void)stopLoading {
_stoppedWKNavigation = [_navigationStates lastAddedNavigation];
base::RecordAction(base::UserMetricsAction("Stop"));
// Discard the pending and transient entried before notifying the tab model
// observers of the change via |-abortLoad|.
self.navigationManagerImpl->DiscardNonCommittedItems();
[self abortLoad];
web::NavigationItem* item = self.currentNavItem;
GURL navigationURL = item ? item->GetVirtualURL() : GURL::EmptyGURL();
// If discarding the non-committed entries results in an app-specific URL,
// reload it in its native view.
if (!self.nativeController &&
[self shouldLoadURLInNativeView:navigationURL]) {
// RendererInitiated flag is meaningless for showing previous native
// content page. RendererInitiated is used as less previledged.
[self loadCurrentURLInNativeViewWithRendererInitiatedNavigation:YES];
}
}
- (void)loadCurrentURLWithRendererInitiatedNavigation:(BOOL)rendererInitiated {
// If the content view doesn't exist, the tab has either been evicted, or
// never displayed. Bail, and let the URL be loaded when the tab is shown.
if (!_containerView)
return;
// WKBasedNavigationManagerImpl needs WKWebView to load native views, but
// WKWebView cannot be created while web usage is disabled to avoid breaking
// clearing browser data. Bail now and let the URL be loaded when web
// usage is enabled again. This can happen when purging web pages when an
// interstitial is presented over a native view. See https://crbug.com/865985
// for details.
if (web::GetWebClient()->IsSlimNavigationManagerEnabled() &&
!_webUsageEnabled)
return;
_currentURLLoadWasTrigerred = YES;
// Reset current WebUI if one exists.
[self clearWebUI];
// Abort any outstanding page load. This ensures the delegate gets informed
// about the outgoing page, and further messages from the page are suppressed.
if (_loadPhase != web::PAGE_LOADED)
[self abortLoad];
DCHECK(!_isHalted);
self.webStateImpl->ClearTransientContent();
web::NavigationItem* item = self.currentNavItem;
const GURL currentURL = item ? item->GetURL() : GURL::EmptyGURL();
const bool isCurrentURLAppSpecific =
web::GetWebClient()->IsAppSpecificURL(currentURL);
// If it's a chrome URL, but not a native one, create the WebUI instance.
if (isCurrentURLAppSpecific &&
![_nativeProvider hasControllerForURL:currentURL]) {
if (!(item->GetTransitionType() & ui::PAGE_TRANSITION_TYPED ||
item->GetTransitionType() & ui::PAGE_TRANSITION_AUTO_BOOKMARK) &&
self.hasOpener) {
// WebUI URLs can not be opened by DOM to prevent cross-site scripting as
// they have increased power. WebUI URLs may only be opened when the user
// types in the URL or use bookmarks.
self.navigationManagerImpl->DiscardNonCommittedItems();
return;
} else {
[self createWebUIForURL:currentURL];
}
}
// Loading a new url, must check here if it's a native chrome URL and
// replace the appropriate view if so, or transition back to a web view from
// a native view.
if ([self shouldLoadURLInNativeView:currentURL]) {
[self loadCurrentURLInNativeViewWithRendererInitiatedNavigation:
rendererInitiated];
} else if (web::GetWebClient()->IsSlimNavigationManagerEnabled() &&
isCurrentURLAppSpecific && self.webStateImpl->HasWebUI() &&
!web::features::WebUISchemeHandlingEnabled()) {
[self loadPlaceholderInWebViewForURL:currentURL
rendererInitiated:rendererInitiated
forContext:nullptr];
} else {
[self loadCurrentURLInWebView];
}
}
- (void)loadCurrentURLIfNecessary {
if (_webProcessCrashed) {
[self loadCurrentURLWithRendererInitiatedNavigation:NO];
} else if (!_currentURLLoadWasTrigerred) {
[self ensureContainerViewCreated];
// This method reloads last committed item, so make than item also pending.
self.sessionController.pendingItemIndex =
self.sessionController.lastCommittedItemIndex;
// TODO(crbug.com/796608): end the practice of calling |loadCurrentURL|
// when it is possible there is no current URL. If the call performs
// necessary initialization, break that out.
[self loadCurrentURLWithRendererInitiatedNavigation:NO];
}
}
- (void)loadData:(NSData*)data
MIMEType:(NSString*)MIMEType
forURL:(const GURL&)URL {
web::NavigationItemImpl* item =
self.navigationManagerImpl->GetLastCommittedItemImpl();
auto navigationContext = web::NavigationContextImpl::CreateNavigationContext(
self.webStateImpl, URL,
/*has_user_gesture=*/true, item->GetTransitionType(),
/*is_renderer_initiated=*/false);
_loadPhase = web::LOAD_REQUESTED;
navigationContext->SetNavigationItemUniqueID(item->GetUniqueID());
item->SetNavigationInitiationType(
web::NavigationInitiationType::BROWSER_INITIATED);
// The error_retry_state_machine may still be in the
// |kDisplayingWebErrorForFailedNavigation| from the navigation that is being
// replaced. As the navigation is now successful, the error can be cleared.
item->error_retry_state_machine().SetNoNavigationError();
// The load data call will replace the current navigation and the webView URL
// of the navigation will be replaced by |URL|. Set the URL of the
// navigationItem to keep them synced.
// Note: it is possible that the URL in item already match |url|. But item can
// also contain a placeholder URL intended to be replaced.
item->SetURL(URL);
navigationContext->SetMimeType(MIMEType);
if (item->GetUserAgentType() == web::UserAgentType::NONE &&
web::wk_navigation_util::URLNeedsUserAgentType(URL)) {
item->SetUserAgentType(web::UserAgentType::MOBILE);
}
WKNavigation* navigation =
[self.webView loadData:data
MIMEType:MIMEType
characterEncodingName:base::SysUTF8ToNSString(base::kCodepageUTF8)
baseURL:net::NSURLWithGURL(URL)];
[_navigationStates setContext:std::move(navigationContext)
forNavigation:navigation];
[_navigationStates setState:web::WKNavigationState::REQUESTED
forNavigation:navigation];
}
- (void)loadHTML:(NSString*)HTML forAppSpecificURL:(const GURL&)URL {
CHECK(web::GetWebClient()->IsAppSpecificURL(URL));
[self loadHTML:HTML forURL:URL];
}
// Loads the HTML into the page at the given URL. Extracted from
// loadHTML:forAppSpecificURL: for testing purpose.
- (void)loadHTML:(NSString*)HTML forURL:(const GURL&)URL {
DCHECK(HTML.length);
// Remove the transient content view.
self.webStateImpl->ClearTransientContent();
_loadPhase = web::LOAD_REQUESTED;
// Web View should not be created for App Specific URLs.
if (!web::GetWebClient()->IsAppSpecificURL(URL)) {
[self ensureWebViewCreated];
DCHECK(self.webView) << "self.webView null while trying to load HTML";
}
WKNavigation* navigation =
[self.webView loadHTMLString:HTML baseURL:net::NSURLWithGURL(URL)];
[_navigationStates setState:web::WKNavigationState::REQUESTED
forNavigation:navigation];
std::unique_ptr<web::NavigationContextImpl> context;
const ui::PageTransition loadHTMLTransition =
ui::PageTransition::PAGE_TRANSITION_TYPED;
if (self.webStateImpl->HasWebUI()) {
// WebUI uses |loadHTML:forURL:| to feed the content to web view. This
// should not be treated as a navigation, but WKNavigationDelegate callbacks
// still expect a valid context.
context = web::NavigationContextImpl::CreateNavigationContext(
self.webStateImpl, URL, /*has_user_gesture=*/true, loadHTMLTransition,
/*is_renderer_initiated=*/false);
context->SetNavigationItemUniqueID(self.currentNavItem->GetUniqueID());
if (web::features::StorePendingItemInContext()) {
// Transfer pending item ownership to NavigationContext.
// NavigationManager owns pending item after navigation is requested and
// until navigation context is created.
context->SetItem([self.sessionController releasePendingItem]);
}
} else {
context = [self registerLoadRequestForURL:URL
referrer:web::Referrer()
transition:loadHTMLTransition
sameDocumentNavigation:NO
hasUserGesture:YES
rendererInitiated:NO
placeholderNavigation:NO];
}
context->SetLoadingHtmlString(true);
context->SetMimeType(@"text/html");
[_navigationStates setContext:std::move(context) forNavigation:navigation];
}
- (void)executeUserJavaScript:(NSString*)script
completionHandler:(web::JavaScriptResultBlock)completion {
// For security reasons, executing JavaScript on pages with app-specific URLs
// is not allowed, because those pages may have elevated privileges.
GURL lastCommittedURL = self.webState->GetLastCommittedURL();
if (web::GetWebClient()->IsAppSpecificURL(lastCommittedURL)) {
if (completion) {
dispatch_async(dispatch_get_main_queue(), ^{
NSError* error = [[NSError alloc]
initWithDomain:web::kJSEvaluationErrorDomain
code:web::JS_EVALUATION_ERROR_CODE_NO_WEB_VIEW
userInfo:nil];
completion(nil, error);
});
}
return;
}
[self touched:YES];
[self executeJavaScript:script completionHandler:completion];
}
- (void)requirePageReconstruction {
// TODO(crbug.com/736103): Removing web view will destroy session history for
// WKBasedNavigationManager.
if (!web::GetWebClient()->IsSlimNavigationManagerEnabled())
[self removeWebView];
}
- (void)recordStateInHistory {
// Only record the state if:
// - the current NavigationItem's URL matches the current URL, and
// - the user has interacted with the page.
web::NavigationItem* item = self.currentNavItem;
if (item && item->GetURL() == [self currentURL] &&
self.userInteractionRegistered) {
item->SetPageDisplayState(self.pageDisplayState);
}
}
- (void)wasShown {
self.visible = YES;
if ([self.nativeController respondsToSelector:@selector(wasShown)]) {
[self.nativeController wasShown];
}
}
- (void)wasHidden {
self.visible = NO;
if (_isHalted)
return;
[self recordStateInHistory];
if ([self.nativeController respondsToSelector:@selector(wasHidden)]) {
[self.nativeController wasHidden];
}
}
- (void)addGestureRecognizerToWebView:(UIGestureRecognizer*)recognizer {
if ([_gestureRecognizers containsObject:recognizer])
return;
[self.webView addGestureRecognizer:recognizer];
[_gestureRecognizers addObject:recognizer];
}
- (void)removeGestureRecognizerFromWebView:(UIGestureRecognizer*)recognizer {
if (![_gestureRecognizers containsObject:recognizer])
return;
[self.webView removeGestureRecognizer:recognizer];
[_gestureRecognizers removeObject:recognizer];
}
- (void)didFinishGoToIndexSameDocumentNavigationWithType:
(web::NavigationInitiationType)type
hasUserGesture:(BOOL)hasUserGesture {
web::NavigationItem* item =
self.webStateImpl->GetNavigationManager()->GetLastCommittedItem();
GURL URL = item->GetVirtualURL();
std::unique_ptr<web::NavigationContextImpl> context =
web::NavigationContextImpl::CreateNavigationContext(
self.webStateImpl, URL, hasUserGesture,
static_cast<ui::PageTransition>(
item->GetTransitionType() |
ui::PageTransition::PAGE_TRANSITION_FORWARD_BACK),
type == web::NavigationInitiationType::RENDERER_INITIATED);
context->SetIsSameDocument(true);
self.webStateImpl->SetIsLoading(true);
self.webStateImpl->OnNavigationStarted(context.get());
[self updateHTML5HistoryState];
[self setDocumentURL:URL context:context.get()];
context->SetHasCommitted(true);
self.webStateImpl->OnNavigationFinished(context.get());
[self didFinishWithURL:URL loadSuccess:YES context:context.get()];
}
- (void)goToBackForwardListItem:(WKBackForwardListItem*)wk_item
navigationItem:(web::NavigationItem*)item
navigationInitiationType:(web::NavigationInitiationType)type
hasUserGesture:(BOOL)hasUserGesture {
WKNavigation* navigation = [self.webView goToBackForwardListItem:wk_item];
GURL URL = net::GURLWithNSURL(wk_item.URL);
if (IsPlaceholderUrl(URL)) {
// No need to create navigation context for placeholder back forward
// navigations. Future callbacks do not expect that context will exist.
return;
}
// This navigation can be an iframe navigation, but it's not possible to
// distinguish it from the main frame navigation, so context still has to be
// created.
std::unique_ptr<web::NavigationContextImpl> context =
web::NavigationContextImpl::CreateNavigationContext(
self.webStateImpl, URL, hasUserGesture,
static_cast<ui::PageTransition>(
item->GetTransitionType() |
ui::PageTransition::PAGE_TRANSITION_FORWARD_BACK),
type == web::NavigationInitiationType::RENDERER_INITIATED);
context->SetNavigationItemUniqueID(item->GetUniqueID());
if (!navigation) {
// goToBackForwardListItem: returns nil for same-document back forward
// navigations.
context->SetIsSameDocument(true);
} else {
self.webStateImpl->SetIsLoading(true);
_loadPhase = web::LOAD_REQUESTED;
}
web::WKBackForwardListItemHolder* holder =
web::WKBackForwardListItemHolder::FromNavigationItem(item);
holder->set_navigation_type(WKNavigationTypeBackForward);
context->SetIsPost((holder && [holder->http_method() isEqual:@"POST"]) ||
item->HasPostData());
if (holder) {
context->SetMimeType(holder->mime_type());
}
[_navigationStates setContext:std::move(context) forNavigation:navigation];
[_navigationStates setState:web::WKNavigationState::REQUESTED
forNavigation:navigation];
}
- (void)takeSnapshotWithRect:(CGRect)rect
completion:(void (^)(UIImage*))completion {
if (@available(iOS 11, *)) {
if (self.webView) {
WKSnapshotConfiguration* configuration =
[[WKSnapshotConfiguration alloc] init];
configuration.rect = [self.webView convertRect:rect fromView:self.view];
__weak CRWWebController* weakSelf = self;
[self.webView
takeSnapshotWithConfiguration:configuration
completionHandler:^(UIImage* snapshot, NSError* error) {
// Pass nil to the completion block if there is an error
// or if the web view has been removed before the
// snapshot is finished. |snapshot| can sometimes be
// corrupt if it's sent due to the WKWebView's
// deallocation, so callbacks received after
// |-removeWebView| are ignored to prevent crashing.
if (error || !weakSelf.webView) {
if (error) {
DLOG(ERROR) << "WKWebView snapshot error: "
<< error.description;
}
completion(nil);
} else {
completion(snapshot);
}
}];
return;
}
}
dispatch_async(dispatch_get_main_queue(), ^{
completion(nil);
});
}
#pragma mark - CRWJSInjectionEvaluator (Public)
- (void)executeJavaScript:(NSString*)script
completionHandler:(web::JavaScriptResultBlock)completionHandler {
NSString* safeScript = [self scriptByAddingWindowIDCheckForScript:script];
web::ExecuteJavaScript(self.webView, safeScript, completionHandler);
}
- (BOOL)scriptHasBeenInjectedForClass:(Class)injectionManagerClass {
return [_injectedScriptManagers containsObject:injectionManagerClass];
}
- (void)injectScript:(NSString*)script forClass:(Class)JSInjectionManagerClass {
DCHECK(script.length);
// Script execution is an asynchronous operation which may pass sensitive
// data to the page. executeJavaScript:completionHandler makes sure that
// receiver page did not change by checking its window id.
// |[self.webView executeJavaScript:completionHandler:]| is not used here
// because it does not check that page is the same.
[self executeJavaScript:script completionHandler:nil];
[_injectedScriptManagers addObject:JSInjectionManagerClass];
}
#pragma mark - CRWSessionControllerDelegate (Public)
- (web::NavigationItemImpl*)pendingItemForSessionController:
(CRWSessionController*)sessionController {
return [self lastPendingItemForNewNavigation];
}
#pragma mark - CRWTouchTrackingDelegate (Public)
- (void)touched:(BOOL)touched {
_clickInProgress = touched;
if (touched) {
self.userInteractionRegistered = YES;
_userInteractedWithWebController = YES;
if (_isBeingDestroyed)
return;
const NavigationManagerImpl* navigationManager = self.navigationManagerImpl;
GURL mainDocumentURL =
navigationManager->GetLastCommittedItem()
? navigationManager->GetLastCommittedItem()->GetURL()
: [self currentURL];
_lastUserInteraction =
std::make_unique<UserInteractionEvent>(mainDocumentURL);
}
}
#pragma mark - ** Private Methods **
#pragma mark -
- (BOOL)isSafeBrowsingWarningDisplayedInWebView {
// A SafeBrowsing warning is a UIScrollView that is inserted on top of
// WKWebView's scroll view. This method uses heuristics to detect this view.
// It may break in the future if WebKit's implementation of SafeBrowsing
// warnings changes.
UIView* containingView = self.webView.scrollView.superview;
if (!containingView)
return NO;
UIView* topView = containingView.subviews.lastObject;
if (topView == self.webView.scrollView)
return NO;
return
[topView isKindOfClass:[UIScrollView class]] &&
[NSStringFromClass([topView class]) containsString:@"Warning"] &&
topView.subviews.count > 0 &&
[topView.subviews[0].subviews.lastObject isKindOfClass:[UIButton class]];
}
- (void)setDocumentURL:(const GURL&)newURL
context:(web::NavigationContextImpl*)context {
if (newURL != _documentURL && newURL.is_valid()) {
_documentURL = newURL;
_interactionRegisteredSinceLastURLChange = NO;
}
if (web::GetWebClient()->IsSlimNavigationManagerEnabled() && context &&
!context->IsLoadingHtmlString() && !context->IsLoadingErrorPage() &&
!IsWKInternalUrl(newURL) && !newURL.SchemeIs(url::kAboutScheme) &&
self.webView) {
GURL documentOrigin = newURL.GetOrigin();
web::NavigationItem* committedItem =
self.webStateImpl->GetNavigationManager()->GetLastCommittedItem();
GURL committedOrigin =
committedItem ? committedItem->GetURL().GetOrigin() : GURL::EmptyGURL();
DCHECK_EQ(documentOrigin, committedOrigin)
<< "Old and new URL detection system have a mismatch";
ukm::SourceId sourceID = ukm::ConvertToSourceId(
context->GetNavigationId(), ukm::SourceIdType::NAVIGATION_ID);
if (sourceID != ukm::kInvalidSourceId) {
ukm::builders::IOS_URLMismatchInLegacyAndSlimNavigationManager(sourceID)
.SetHasMismatch(documentOrigin != committedOrigin)
.Record(ukm::UkmRecorder::Get());
}
}
}
- (void)setNavigationItemTitle:(NSString*)title {
DCHECK(title);
web::NavigationItem* item =
self.navigationManagerImpl->GetLastCommittedItem();
if (!item)
return;
item->SetTitle(base::SysNSStringToUTF16(title));
self.webStateImpl->OnTitleChanged();
}
- (BOOL)isCurrentNavigationItemPOST {
// |_pendingNavigationInfo| will be nil if the decidePolicy* delegate methods
// were not called.
NSString* HTTPMethod =
_pendingNavigationInfo
? [_pendingNavigationInfo HTTPMethod]
: [self currentBackForwardListItemHolder]->http_method();
if ([HTTPMethod isEqual:@"POST"]) {
return YES;
}
if (!self.currentNavItem) {
return NO;
}
return self.currentNavItem->HasPostData();
}
- (BOOL)isCurrentNavigationBackForward {
if (!self.currentNavItem)
return NO;
WKNavigationType currentNavigationType =
[self currentBackForwardListItemHolder]->navigation_type();
return currentNavigationType == WKNavigationTypeBackForward;
}
- (BOOL)isBackForwardListItemValid:(WKBackForwardListItem*)item {
// The current back-forward list item MUST be in the WKWebView's back-forward
// list to be valid.
WKBackForwardList* list = self.webView.backForwardList;
return list.currentItem == item ||
[list.forwardList indexOfObject:item] != NSNotFound ||
[list.backList indexOfObject:item] != NSNotFound;
}
- (std::unique_ptr<web::NavigationContextImpl>)
registerLoadRequestForURL:(const GURL&)URL
sameDocumentNavigation:(BOOL)sameDocumentNavigation
hasUserGesture:(BOOL)hasUserGesture
rendererInitiated:(BOOL)rendererInitiated
placeholderNavigation:(BOOL)placeholderNavigation {
// Get the navigation type from the last main frame load request, and try to
// map that to a PageTransition.
WKNavigationType navigationType =
_pendingNavigationInfo ? [_pendingNavigationInfo navigationType]
: WKNavigationTypeOther;
ui::PageTransition transition =
[self pageTransitionFromNavigationType:navigationType];
if (web::GetWebClient()->IsSlimNavigationManagerEnabled() &&
navigationType == WKNavigationTypeBackForward &&
self.webView.backForwardList.currentItem) {
web::NavigationItem* currentItem = [[CRWNavigationItemHolder
holderForBackForwardListItem:self.webView.backForwardList.currentItem]
navigationItem];
if (currentItem) {
transition = ui::PageTransitionFromInt(transition |
currentItem->GetTransitionType());
}
}
// The referrer is not known yet, and will be updated later.
const web::Referrer emptyReferrer;
std::unique_ptr<web::NavigationContextImpl> context =
[self registerLoadRequestForURL:URL
referrer:emptyReferrer
transition:transition
sameDocumentNavigation:sameDocumentNavigation
hasUserGesture:hasUserGesture
rendererInitiated:rendererInitiated
placeholderNavigation:placeholderNavigation];
context->SetWKNavigationType(navigationType);
return context;
}
- (std::unique_ptr<web::NavigationContextImpl>)
registerLoadRequestForURL:(const GURL&)requestURL
referrer:(const web::Referrer&)referrer
transition:(ui::PageTransition)transition
sameDocumentNavigation:(BOOL)sameDocumentNavigation
hasUserGesture:(BOOL)hasUserGesture
rendererInitiated:(BOOL)rendererInitiated
placeholderNavigation:(BOOL)placeholderNavigation {
// Transfer time is registered so that further transitions within the time
// envelope are not also registered as links.
_lastTransferTimeInSeconds = CFAbsoluteTimeGetCurrent();
// Add or update pending item before any WebStateObserver callbacks.
// See https://crbug.com/842151 for a scenario where this is important.
web::NavigationItem* item =
self.navigationManagerImpl->GetPendingItemInCurrentOrRestoredSession();
if (item) {
// Update the existing pending entry.
// Typically on PAGE_TRANSITION_CLIENT_REDIRECT.
// Don't update if request is a placeholder entry because the pending item
// should have the original target URL.
// Don't update if pending URL has a different origin, because client
// redirects can not change the origin. It is possible to have more than one
// pending navigations, so the redirect does not necesserily belong to the
// pending navigation item.
if (!placeholderNavigation &&
item->GetURL().GetOrigin() == requestURL.GetOrigin()) {
self.navigationManagerImpl->UpdatePendingItemUrl(requestURL);
}
} else {
self.navigationManagerImpl->AddPendingItem(
requestURL, referrer, transition,
rendererInitiated ? web::NavigationInitiationType::RENDERER_INITIATED
: web::NavigationInitiationType::BROWSER_INITIATED,
NavigationManager::UserAgentOverrideOption::INHERIT);
item =
self.navigationManagerImpl->GetPendingItemInCurrentOrRestoredSession();
}
bool redirect = transition & ui::PAGE_TRANSITION_IS_REDIRECT_MASK;
if (!redirect) {
// Before changing phases, the delegate should be informed that any existing
// request is being cancelled before completion.
[self loadCancelled];
DCHECK(_loadPhase == web::PAGE_LOADED);
}
_loadPhase = web::LOAD_REQUESTED;
// Record the state of outgoing web view. Do nothing if native controller
// exists, because in that case recordStateInHistory will record the state
// of incoming page as native controller is already inserted.
// TODO(crbug.com/811770) Don't record state under WKBasedNavigationManager
// because it may incorrectly clobber the incoming page if this is a
// back/forward navigation. WKWebView restores page scroll state for web view
// pages anyways so this only impacts user if WKWebView is deleted.
if (!redirect && !self.nativeController &&
!web::GetWebClient()->IsSlimNavigationManagerEnabled()) {
[self recordStateInHistory];
}
std::unique_ptr<web::NavigationContextImpl> context =
web::NavigationContextImpl::CreateNavigationContext(
self.webStateImpl, requestURL, hasUserGesture, transition,
rendererInitiated);
context->SetPlaceholderNavigation(placeholderNavigation);
// TODO(crbug.com/676129): LegacyNavigationManagerImpl::AddPendingItem does
// not create a pending item in case of reload. Remove this workaround once
// the bug is fixed or WKBasedNavigationManager is fully adopted.
if (!item) {
DCHECK(!web::GetWebClient()->IsSlimNavigationManagerEnabled());
item = self.navigationManagerImpl->GetLastCommittedItem();
}
context->SetNavigationItemUniqueID(item->GetUniqueID());
context->SetIsPost([self isCurrentNavigationItemPOST]);
context->SetIsSameDocument(sameDocumentNavigation);
if (!IsWKInternalUrl(requestURL) && !placeholderNavigation) {
self.webStateImpl->SetIsLoading(true);
// WKBasedNavigationManager triggers HTML load when placeholder navigation
// finishes.
if (!web::GetWebClient()->IsSlimNavigationManagerEnabled())
[_webUIManager loadWebUIForURL:requestURL];
}
// WKWebView may have multiple pending items. Move pending item ownership from
// NavigationManager to NavigationContext. NavigationManager owns pending item
// after navigation was requested and until NavigationContext is created.
if (web::features::StorePendingItemInContext()) {
// No need to transfer the ownership for NativeContent URLs, because the
// load of NativeContent is synchronous. No need to transfer the ownership
// for WebUI navigations, because those navigation do not have access to
// NavigationContext.
if (![_nativeProvider hasControllerForURL:context->GetUrl()] &&
!(_webUIManager &&
web::GetWebClient()->IsAppSpecificURL(context->GetUrl()))) {
if (self.navigationManagerImpl->GetPendingItemIndex() == -1) {
context->SetItem([self.sessionController releasePendingItem]);
}
}
}
return context;
}
- (ui::PageTransition)pageTransitionFromNavigationType:
(WKNavigationType)navigationType {
switch (navigationType) {
case WKNavigationTypeLinkActivated:
return ui::PAGE_TRANSITION_LINK;
case WKNavigationTypeFormSubmitted:
case WKNavigationTypeFormResubmitted:
return ui::PAGE_TRANSITION_FORM_SUBMIT;
case WKNavigationTypeBackForward:
return ui::PAGE_TRANSITION_FORWARD_BACK;
case WKNavigationTypeReload:
return ui::PAGE_TRANSITION_RELOAD;
case WKNavigationTypeOther:
// The "Other" type covers a variety of very different cases, which may
// or may not be the result of user actions. For now, guess based on
// whether there's been an interaction since the last URL change.
// TODO(crbug.com/549301): See if this heuristic can be improved.
return _interactionRegisteredSinceLastURLChange
? ui::PAGE_TRANSITION_LINK
: ui::PAGE_TRANSITION_CLIENT_REDIRECT;
}
}
// Load the current URL in a web view, first ensuring the web view is visible.
- (void)loadCurrentURLInWebView {
web::NavigationItem* item = self.currentNavItem;
GURL targetURL = item ? item->GetVirtualURL() : GURL::EmptyGURL();
// Load the url. The UIWebView delegate callbacks take care of updating the
// session history and UI.
if (!targetURL.is_valid()) {
[self didFinishWithURL:targetURL loadSuccess:NO context:nullptr];
self.webStateImpl->SetIsLoading(false);
self.webStateImpl->OnPageLoaded(targetURL, NO);
return;
}
// JavaScript should never be evaluated here. User-entered JS should be
// evaluated via stringByEvaluatingUserJavaScriptFromString.
DCHECK(!targetURL.SchemeIs(url::kJavaScriptScheme));
[self ensureWebViewCreated];
[self loadRequestForCurrentNavigationItem];
}
- (void)loadRequestForCurrentNavigationItem {
DCHECK(self.webView);
DCHECK(self.currentNavItem);
// If a load is kicked off on a WKWebView with a frame whose size is {0, 0} or
// that has a negative dimension for a size, rendering issues occur that
// manifest in erroneous scrolling and tap handling (crbug.com/574996,
// crbug.com/577793).
DCHECK_GT(CGRectGetWidth(self.webView.frame), 0.0);
DCHECK_GT(CGRectGetHeight(self.webView.frame), 0.0);
// If the current item uses a different user agent from that is currently used
// in the web view, update |customUserAgent| property, which will be used by
// the next request sent by this web view.
web::UserAgentType itemUserAgentType =
self.currentNavItem->GetUserAgentType();
if (itemUserAgentType != web::UserAgentType::NONE) {
NSString* userAgentString = base::SysUTF8ToNSString(
web::GetWebClient()->GetUserAgent(itemUserAgentType));
if (![self.webView.customUserAgent isEqualToString:userAgentString]) {
self.webView.customUserAgent = userAgentString;
}
}
web::WKBackForwardListItemHolder* holder =
[self currentBackForwardListItemHolder];
BOOL repostedForm =
[holder->http_method() isEqual:@"POST"] &&
(holder->navigation_type() == WKNavigationTypeFormResubmitted ||
holder->navigation_type() == WKNavigationTypeFormSubmitted);
web::NavigationItemImpl* currentItem = self.currentNavItem;
NSData* POSTData = currentItem->GetPostData();
NSMutableURLRequest* request = [self requestForCurrentNavigationItem];
BOOL sameDocumentNavigation = currentItem->IsCreatedFromPushState() ||
currentItem->IsCreatedFromHashChange();
if (holder->back_forward_list_item()) {
// Check if holder's WKBackForwardListItem still correctly represents
// navigation item. With LegacyNavigationManager, replaceState operation
// creates a new navigation item, leaving the old item committed. That
// old committed item will be associated with WKBackForwardListItem whose
// state was replaced. So old item won't have correct WKBackForwardListItem.
if (net::GURLWithNSURL(holder->back_forward_list_item().URL) !=
currentItem->GetURL()) {
// The state was replaced for this item. The item should not be a part of
// committed items, but it's too late to remove the item. Cleaup
// WKBackForwardListItem and mark item with "state replaced" flag.
currentItem->SetHasStateBeenReplaced(true);
holder->set_back_forward_list_item(nil);
}
}
// If the request has POST data and is not a repost form, configure and
// run the POST request.
if (POSTData.length && !repostedForm) {
[request setHTTPMethod:@"POST"];
[request setHTTPBody:POSTData];
[request setAllHTTPHeaderFields:self.currentHTTPHeaders];
// As of iOS 11, WKWebView supports requests with POST data, so the
// Javascript POST workaround only needs to be used if the OS version is
// less than iOS 11.
// TODO(crbug.com/740987): Remove POST workaround once iOS 10 is dropped.
if (!base::ios::IsRunningOnIOS11OrLater()) {
GURL navigationURL =
currentItem ? currentItem->GetURL() : GURL::EmptyGURL();
std::unique_ptr<web::NavigationContextImpl> navigationContext =
[self registerLoadRequestForURL:navigationURL
referrer:self.currentNavItemReferrer
transition:self.currentTransition
sameDocumentNavigation:sameDocumentNavigation
hasUserGesture:YES
rendererInitiated:NO
placeholderNavigation:NO];
WKNavigation* navigation = [self loadPOSTRequest:request];
[_navigationStates setContext:std::move(navigationContext)
forNavigation:navigation];
[_navigationStates setState:web::WKNavigationState::REQUESTED
forNavigation:navigation];
return;
}
}
ProceduralBlock defaultNavigationBlock = ^{
web::NavigationItem* item = self.currentNavItem;
GURL navigationURL = item ? item->GetURL() : GURL::EmptyGURL();
GURL virtualURL = item ? item->GetVirtualURL() : GURL::EmptyGURL();
// Set |item| to nullptr here to avoid any use-after-free issues, as it can
// be cleared by the call to -registerLoadRequestForURL below.
item = nullptr;
GURL contextURL = IsPlaceholderUrl(navigationURL)
? ExtractUrlFromPlaceholderUrl(navigationURL)
: navigationURL;
std::unique_ptr<web::NavigationContextImpl> navigationContext =
[self registerLoadRequestForURL:contextURL
referrer:self.currentNavItemReferrer
transition:self.currentTransition
sameDocumentNavigation:sameDocumentNavigation
hasUserGesture:YES
rendererInitiated:NO
placeholderNavigation:IsPlaceholderUrl(navigationURL)];
WKNavigation* navigation = nil;
if (navigationURL.SchemeIsFile() &&
web::GetWebClient()->IsAppSpecificURL(virtualURL)) {
// file:// URL navigations are allowed for app-specific URLs, which
// already have elevated privileges.
NSURL* navigationNSURL = net::NSURLWithGURL(navigationURL);
navigation = [self.webView loadFileURL:navigationNSURL
allowingReadAccessToURL:navigationNSURL];
} else {
navigation = [self.webView loadRequest:request];
}
[_navigationStates setState:web::WKNavigationState::REQUESTED
forNavigation:navigation];
[_navigationStates setContext:std::move(navigationContext)
forNavigation:navigation];
[self reportBackForwardNavigationTypeForFastNavigation:NO];
};
// When navigating via WKBackForwardListItem to pages created or updated by
// calls to pushState() and replaceState(), sometimes web_bundle.js is not
// injected correctly. This means that calling window.history navigation
// functions will invoke WKWebView's non-overridden implementations, causing a
// mismatch between the WKBackForwardList and NavigationManager.
// TODO(crbug.com/659816): Figure out how to prevent web_bundle.js injection
// flake.
if (currentItem->HasStateBeenReplaced() ||
currentItem->IsCreatedFromPushState()) {
defaultNavigationBlock();
return;
}
// If there is no corresponding WKBackForwardListItem, or the item is not in
// the current WKWebView's back-forward list, navigating using WKWebView API
// is not possible. In this case, fall back to the default navigation
// mechanism.
if (!holder->back_forward_list_item() ||
![self isBackForwardListItemValid:holder->back_forward_list_item()]) {
defaultNavigationBlock();
return;
}
ProceduralBlock webViewNavigationBlock = ^{
// If the current navigation URL is the same as the URL of the visible
// page, that means the user requested a reload. |goToBackForwardListItem|
// will be a no-op when it is passed the current back forward list item,
// so |reload| must be explicitly called.
web::NavigationItem* item = self.currentNavItem;
GURL navigationURL = item ? item->GetURL() : GURL::EmptyGURL();
std::unique_ptr<web::NavigationContextImpl> navigationContext =
[self registerLoadRequestForURL:navigationURL
referrer:self.currentNavItemReferrer
transition:self.currentTransition
sameDocumentNavigation:sameDocumentNavigation
hasUserGesture:YES
rendererInitiated:NO
placeholderNavigation:NO];
WKNavigation* navigation = nil;
if (navigationURL == net::GURLWithNSURL(self.webView.URL)) {
navigation = [self.webView reload];
} else {
// |didCommitNavigation:| may not be called for fast navigation, so update
// the navigation type now as it is already known.
navigationContext->SetWKNavigationType(WKNavigationTypeBackForward);
navigationContext->SetMimeType(holder->mime_type());
holder->set_navigation_type(WKNavigationTypeBackForward);
navigation = [self.webView
goToBackForwardListItem:holder->back_forward_list_item()];
[self reportBackForwardNavigationTypeForFastNavigation:YES];
}
[_navigationStates setState:web::WKNavigationState::REQUESTED
forNavigation:navigation];
[_navigationStates setContext:std::move(navigationContext)
forNavigation:navigation];
};
// If the request is not a form submission or resubmission, or the user
// doesn't need to confirm the load, then continue right away.
if (!repostedForm || currentItem->ShouldSkipRepostFormConfirmation()) {
webViewNavigationBlock();
return;
}
// If the request is form submission or resubmission, then prompt the
// user before proceeding.
DCHECK(repostedForm);
DCHECK(!web::GetWebClient()->IsSlimNavigationManagerEnabled());
self.webStateImpl->ShowRepostFormWarningDialog(
base::BindOnce(^(bool shouldContinue) {
if (_isBeingDestroyed)
return;
if (shouldContinue)
webViewNavigationBlock();
else
[self stopLoading];
}));
}
- (WKNavigation*)loadPOSTRequest:(NSMutableURLRequest*)request {
if (!_POSTRequestLoader) {
_POSTRequestLoader = [[CRWJSPOSTRequestLoader alloc] init];
}
CRWWKScriptMessageRouter* messageRouter =
[self webViewConfigurationProvider].GetScriptMessageRouter();
return
[_POSTRequestLoader loadPOSTRequest:request
inWebView:self.webView
messageRouter:messageRouter
completionHandler:^(NSError* loadError) {
if (loadError)
[self handleLoadError:loadError
forNavigation:nil
provisionalLoad:YES];
else
self.webStateImpl->SetContentsMimeType("text/html");
}];
}
- (void)reportBackForwardNavigationTypeForFastNavigation:(BOOL)isFast {
NavigationManager* navigationManager = self.navigationManagerImpl;
int pendingIndex = navigationManager->GetPendingItemIndex();
if (pendingIndex == -1) {
// Pending navigation is not a back forward navigation.
return;
}
BOOL isBack = pendingIndex < navigationManager->GetLastCommittedItemIndex();
BackForwardNavigationType type = BackForwardNavigationType::FAST_BACK;
if (isBack) {
type = isFast ? BackForwardNavigationType::FAST_BACK
: BackForwardNavigationType::SLOW_BACK;
} else {
type = isFast ? BackForwardNavigationType::FAST_FORWARD
: BackForwardNavigationType::SLOW_FORWARD;
}
UMA_HISTOGRAM_ENUMERATION(
"Navigation.IOSWKWebViewSlowFastBackForward", type,
BackForwardNavigationType::BACK_FORWARD_NAVIGATION_TYPE_COUNT);
}
- (void)updatePendingNavigationInfoFromNavigationAction:
(WKNavigationAction*)action {
if (action.targetFrame.mainFrame) {
_pendingNavigationInfo =
[[CRWWebControllerPendingNavigationInfo alloc] init];
[_pendingNavigationInfo
setReferrer:[self referrerFromNavigationAction:action]];
[_pendingNavigationInfo setNavigationType:action.navigationType];
[_pendingNavigationInfo setHTTPMethod:action.request.HTTPMethod];
BOOL hasUserGesture = web::GetNavigationActionInitiationType(action) ==
web::NavigationActionInitiationType::kUserInitiated;
[_pendingNavigationInfo setHasUserGesture:hasUserGesture];
}
}
- (void)updatePendingNavigationInfoFromNavigationResponse:
(WKNavigationResponse*)response {
if (response.isForMainFrame) {
if (!_pendingNavigationInfo) {
_pendingNavigationInfo =
[[CRWWebControllerPendingNavigationInfo alloc] init];
}
[_pendingNavigationInfo setMIMEType:response.response.MIMEType];
}
}
- (void)commitPendingNavigationInfo {
if ([_pendingNavigationInfo referrer]) {
_currentReferrerString = [[_pendingNavigationInfo referrer] copy];
}
[self updateCurrentBackForwardListItemHolder];
_pendingNavigationInfo = nil;
}
- (NSMutableURLRequest*)requestForCurrentNavigationItem {
web::NavigationItem* item = self.currentNavItem;
const GURL currentNavigationURL = item ? item->GetURL() : GURL::EmptyGURL();
NSMutableURLRequest* request = [NSMutableURLRequest
requestWithURL:net::NSURLWithGURL(currentNavigationURL)];
const web::Referrer referrer(self.currentNavItemReferrer);
if (referrer.url.is_valid()) {
std::string referrerValue =
web::ReferrerHeaderValueForNavigation(currentNavigationURL, referrer);
if (!referrerValue.empty()) {
[request setValue:base::SysUTF8ToNSString(referrerValue)
forHTTPHeaderField:kReferrerHeaderName];
}
}
// If there are headers in the current session entry add them to |request|.
// Headers that would overwrite fields already present in |request| are
// skipped.
NSDictionary* headers = self.currentHTTPHeaders;
for (NSString* headerName in headers) {
if (![request valueForHTTPHeaderField:headerName]) {
[request setValue:[headers objectForKey:headerName]
forHTTPHeaderField:headerName];
}
}
return request;
}
- (web::NavigationContextImpl*)contextForPendingMainFrameNavigationWithURL:
(const GURL&)URL {
// Here the enumeration variable |navigation| is __strong to allow setting it
// to nil.
for (__strong id navigation in [_navigationStates pendingNavigations]) {
if (navigation == [NSNull null]) {
// null is a valid navigation object passed to WKNavigationDelegate
// callbacks and represents window opening action.
navigation = nil;
}
web::NavigationContextImpl* context =
[_navigationStates contextForNavigation:navigation];
if (context && context->GetUrl() == URL) {
return context;
}
}
return nullptr;
}
- (web::WKBackForwardListItemHolder*)currentBackForwardListItemHolder {
web::NavigationItem* item = self.currentNavItem;
DCHECK(item);
web::WKBackForwardListItemHolder* holder =
web::WKBackForwardListItemHolder::FromNavigationItem(item);
DCHECK(holder);
return holder;
}
- (void)updateCurrentBackForwardListItemHolder {
// WebUI pages (which are loaded via loadHTMLString:baseURL:) have no entry
// in the back/forward list, so the current item will still be the previous
// page, and should not be associated.
if (_webUIManager)
return;
if (!self.currentNavItem) {
// TODO(crbug.com/925304): Pending item (which stores the holder) should be
// owned by NavigationContext object. Pending item should never be null.
return;
}
web::WKBackForwardListItemHolder* holder =
[self currentBackForwardListItemHolder];
WKNavigationType navigationType =
_pendingNavigationInfo ? [_pendingNavigationInfo navigationType]
: WKNavigationTypeOther;
holder->set_back_forward_list_item(self.webView.backForwardList.currentItem);
holder->set_navigation_type(navigationType);
holder->set_http_method([_pendingNavigationInfo HTTPMethod]);
// Only update the MIME type in the holder if there was MIME type information
// as part of this pending load. It will be nil when doing a fast
// back/forward navigation, for instance, because the callback that would
// populate it is not called in that flow.
if ([_pendingNavigationInfo MIMEType])
holder->set_mime_type([_pendingNavigationInfo MIMEType]);
}
- (void)loadErrorPageForNavigationItem:(web::NavigationItemImpl*)item
navigationContext:(web::NavigationContextImpl*)context {
NSError* error = context->GetError();
DCHECK(error);
DCHECK_EQ(item->GetUniqueID(), context->GetNavigationItemUniqueID());
if (web::IsWKWebViewSSLCertError(error)) {
// This could happen only if certificate is absent or could not be parsed.
error = web::NetErrorFromError(error, net::ERR_SSL_SERVER_CERT_BAD_FORMAT);
#if defined(DEBUG)
net::SSLInfo info;
web::GetSSLInfoFromWKWebViewSSLCertError(error, &info);
CHECK(!error.cert);
#endif
} else {
error = web::NetErrorFromError(error);
}
NSString* failingURLString =
error.userInfo[NSURLErrorFailingURLStringErrorKey];
GURL failingURL(base::SysNSStringToUTF8(failingURLString));
NSString* errorHTML = nil;
web::GetWebClient()->PrepareErrorPage(
self.webStateImpl, failingURL, error, context->IsPost(),
self.webStateImpl->GetBrowserState()->IsOffTheRecord(), &errorHTML);
WKNavigation* navigation =
[self.webView loadHTMLString:errorHTML
baseURL:net::NSURLWithGURL(failingURL)];
auto loadHTMLContext = web::NavigationContextImpl::CreateNavigationContext(
self.webStateImpl, failingURL,
/*has_user_gesture=*/false, ui::PAGE_TRANSITION_FIRST,
/*is_renderer_initiated=*/false);
loadHTMLContext->SetLoadingErrorPage(true);
loadHTMLContext->SetNavigationItemUniqueID(item->GetUniqueID());
[_navigationStates setContext:std::move(loadHTMLContext)
forNavigation:navigation];
[_navigationStates setState:web::WKNavigationState::REQUESTED
forNavigation:navigation];
// TODO(crbug.com/803503): only call these for placeholder navigation because
// they should have already been triggered during navigation commit for
// failures that happen after commit.
[self didStartLoading];
self.navigationManagerImpl->CommitPendingItem(context->ReleaseItem());
web::NavigationItem* lastCommittedItem =
self.navigationManagerImpl->GetLastCommittedItem();
[self setDocumentURL:lastCommittedItem->GetURL() context:context];
// If |context| is a placeholder navigation, this is the second part of the
// error page load for a provisional load failure. Rewrite the context URL to
// actual URL and trigger the deferred |OnNavigationFinished| callback. This
// is also needed if |context| is not yet committed, which can happen on a
// reload/back/forward load that failed in provisional navigation.
if (context->IsPlaceholderNavigation() || !context->HasCommitted()) {
context->SetUrl(item->GetURL());
context->SetPlaceholderNavigation(false);
context->SetHasCommitted(true);
self.webStateImpl->OnNavigationFinished(context);
}
[self loadCompleteWithSuccess:NO forContext:context];
self.webStateImpl->SetIsLoading(false);
self.webStateImpl->OnPageLoaded(failingURL, NO);
}
- (web::NavigationContextImpl*)
loadPlaceholderInWebViewForURL:(const GURL&)originalURL
rendererInitiated:(BOOL)rendererInitiated
forContext:(std::unique_ptr<web::NavigationContextImpl>)
originalContext {
GURL placeholderURL = CreatePlaceholderUrlForUrl(originalURL);
[self ensureWebViewCreated];
NSURLRequest* request =
[NSURLRequest requestWithURL:net::NSURLWithGURL(placeholderURL)];
WKNavigation* navigation = [self.webView loadRequest:request];
[_navigationStates setState:web::WKNavigationState::REQUESTED
forNavigation:navigation];
std::unique_ptr<web::NavigationContextImpl> navigationContext;
if (originalContext) {
navigationContext = std::move(originalContext);
navigationContext->SetPlaceholderNavigation(YES);
} else {
navigationContext = [self registerLoadRequestForURL:originalURL
sameDocumentNavigation:NO
hasUserGesture:NO
rendererInitiated:rendererInitiated
placeholderNavigation:YES];
}
[_navigationStates setContext:std::move(navigationContext)
forNavigation:navigation];
return [_navigationStates contextForNavigation:navigation];
}
- (void)handleErrorRetryCommand:(web::ErrorRetryCommand)command
navigationItem:(web::NavigationItemImpl*)item
navigationContext:(web::NavigationContextImpl*)context
originalNavigation:(WKNavigation*)originalNavigation {
if (command == web::ErrorRetryCommand::kDoNothing)
return;
DCHECK_EQ(item->GetUniqueID(), context->GetNavigationItemUniqueID());
switch (command) {
case web::ErrorRetryCommand::kLoadPlaceholder: {
// This case only happens when a new request failed in provisional
// navigation. Disassociate the navigation context from the original
// request and resuse it for the placeholder navigation.
std::unique_ptr<web::NavigationContextImpl> originalContext =
[_navigationStates removeNavigation:originalNavigation];
[self loadPlaceholderInWebViewForURL:item->GetURL()
rendererInitiated:context->IsRendererInitiated()
forContext:std::move(originalContext)];
} break;
case web::ErrorRetryCommand::kLoadErrorView:
[self loadErrorPageForNavigationItem:item navigationContext:context];
break;
case web::ErrorRetryCommand::kReload:
[self.webView reload];
break;
case web::ErrorRetryCommand::kRewriteWebViewURL: {
std::unique_ptr<web::NavigationContextImpl> navigationContext =
[self registerLoadRequestForURL:item->GetURL()
sameDocumentNavigation:NO
hasUserGesture:NO
rendererInitiated:context->IsRendererInitiated()
placeholderNavigation:NO];
WKNavigation* navigation =
[self.webView loadHTMLString:@""
baseURL:net::NSURLWithGURL(item->GetURL())];
navigationContext->SetError(context->GetError());
navigationContext->SetIsPost(context->IsPost());
[_navigationStates setContext:std::move(navigationContext)
forNavigation:navigation];
} break;
case web::ErrorRetryCommand::kDoNothing:
NOTREACHED();
}
}
- (GURL)webURLWithTrustLevel:(web::URLVerificationTrustLevel*)trustLevel {
DCHECK(trustLevel);
*trustLevel = web::URLVerificationTrustLevel::kAbsolute;
// Placeholder URL is an implementation detail. Don't expose it to users of
// web layer.
if (IsPlaceholderUrl(_documentURL))
return ExtractUrlFromPlaceholderUrl(_documentURL);
return _documentURL;
}
- (void)abortLoad {
[self.webView stopLoading];
[_pendingNavigationInfo setCancelled:YES];
_certVerificationErrors->Clear();
[self loadCancelled];
_safeBrowsingWarningDetectionTimer.Stop();
}
- (void)loadCancelled {
// TODO(crbug.com/821995): Check if this function should be removed.
if (_loadPhase != web::PAGE_LOADED) {
_loadPhase = web::PAGE_LOADED;
if (!_isHalted) {
self.webStateImpl->SetIsLoading(false);
}
}
}
- (BOOL)contentIsImage {
if (!self.webView)
return NO;
const std::string image = "image";
std::string MIMEType = self.webState->GetContentsMimeType();
return MIMEType.compare(0, image.length(), image) == 0;
}
- (void)didReceiveRedirectForNavigation:(web::NavigationContextImpl*)context
withURL:(const GURL&)URL {
context->SetUrl(URL);
web::NavigationItemImpl* item =
web::GetItemWithUniqueID(self.navigationManagerImpl, context);
// Associated item can be a pending item, previously discarded by another
// navigation. WKWebView allows multiple provisional navigations, while
// Navigation Manager has only one pending navigation.
if (item) {
if (!web::wk_navigation_util::IsWKInternalUrl(URL)) {
item->SetVirtualURL(URL);
item->SetURL(URL);
}
// Redirects (3xx response code), must change POST requests to GETs.
item->SetPostData(nil);
item->ResetHttpRequestHeaders();
}
_lastTransferTimeInSeconds = CFAbsoluteTimeGetCurrent();
}
- (void)didFinishNavigation:(web::NavigationContextImpl*)context {
// This can be called at multiple times after the document has loaded. Do
// nothing if the document has already loaded.
if (_loadPhase == web::PAGE_LOADED)
return;
BOOL success = !context || !context->GetError();
[self loadCompleteWithSuccess:success forContext:context];
}
- (void)loadCompleteWithSuccess:(BOOL)loadSuccess
forContext:(web::NavigationContextImpl*)context {
// The webView may have been torn down (or replaced by a native view). Be
// safe and do nothing if that's happened.
if (_loadPhase != web::PAGE_LOADING)
return;
const GURL currentURL([self currentURL]);
_loadPhase = web::PAGE_LOADED;
[self optOutScrollsToTopForSubviews];
// Perform post-load-finished updates.
[self didFinishWithURL:currentURL loadSuccess:loadSuccess context:context];
// Execute the pending LoadCompleteActions.
for (ProceduralBlock action in _pendingLoadCompleteActions) {
action();
}
[_pendingLoadCompleteActions removeAllObjects];
}
- (void)didFinishWithURL:(const GURL&)currentURL
loadSuccess:(BOOL)loadSuccess
context:(nullable const web::NavigationContextImpl*)context {
DCHECK(_loadPhase == web::PAGE_LOADED);
// Rather than creating a new WKBackForwardListItem when loading WebUI pages,
// WKWebView will cache the WebUI HTML in the previous WKBackForwardListItem
// since it's loaded via |-loadHTML:forURL:| instead of an NSURLRequest. As a
// result, the WebUI's HTML and URL will be loaded when navigating to that
// WKBackForwardListItem, causing a mismatch between the visible content and
// the visible URL (WebUI page will be visible, but URL will be the previous
// page's URL). To prevent this potential URL spoofing vulnerability, reset
// the previous NavigationItem's WKBackForwardListItem to force loading via
// NSURLRequest.
if (_webUIManager) {
web::NavigationItem* lastNavigationItem =
self.sessionController.previousItem;
if (lastNavigationItem) {
web::WKBackForwardListItemHolder* holder =
web::WKBackForwardListItemHolder::FromNavigationItem(
lastNavigationItem);
DCHECK(holder);
holder->set_back_forward_list_item(nil);
}
}
[self restoreStateFromHistory];
// Placeholder and restore session URLs are implementation details so should
// not notify WebStateObservers. If |context| is nullptr, don't skip
// placeholder URLs because this may be the only opportunity to update
// |isLoading| for native view reload.
if (context && context->IsPlaceholderNavigation())
return;
if (context && IsRestoreSessionUrl(context->GetUrl()))
return;
if (IsRestoreSessionUrl(net::GURLWithNSURL(self.webView.URL)))
return;
if (context && context->IsLoadingErrorPage())
return;
if (!loadSuccess) {
// WebStateObserver callbacks will be called for load failure after
// loading placeholder URL.
return;
}
if (![_navigationStates lastNavigationWithPendingItemInNavigationContext] ||
!web::features::StorePendingItemInContext()) {
self.webStateImpl->SetIsLoading(false);
} else {
// There is another pending navigation, so the state is still loading.
}
self.webStateImpl->OnPageLoaded(currentURL, YES);
}
- (BOOL)shouldClosePageOnNativeApplicationLoad {
// The page should be closed if it was initiated by the DOM and there has been
// no user interaction with the page since the web view was created, or if
// the page has no navigation items, as occurs when an App Store link is
// opened from another application.
BOOL rendererInitiatedWithoutInteraction =
self.hasOpener && !_userInteractedWithWebController;
BOOL noNavigationItems = !(self.navigationManagerImpl->GetItemCount());
return rendererInitiatedWithoutInteraction || noNavigationItems;
}
#pragma mark - JavaScript history manipulation
// Updates the HTML5 history state of the page using the current NavigationItem.
// For same-document navigations and navigations affected by
// window.history.[push/replace]State(), the URL and serialized state object
// will be updated to the current NavigationItem's values. A popState event
// will be triggered for all same-document navigations. Additionally, a
// hashchange event will be triggered for same-document navigations where the
// only difference between the current and previous URL is the fragment.
// TODO(crbug.com/788465): Verify that the history state management here are not
// needed for WKBasedNavigationManagerImpl and delete this method. The
// OnNavigationItemCommitted() call is likely the only thing that needs to be
// retained.
- (void)updateHTML5HistoryState {
web::NavigationItemImpl* currentItem = self.currentNavItem;
if (!currentItem)
return;
// Same-document navigations must trigger a popState event.
CRWSessionController* sessionController = self.sessionController;
BOOL sameDocumentNavigation = [sessionController
isSameDocumentNavigationBetweenItem:sessionController.currentItem
andItem:sessionController.previousItem];
// WKWebView doesn't send hashchange events for same-document non-BFLI
// navigations, so one must be dispatched manually for hash change same-
// document navigations.
const GURL URL = currentItem->GetURL();
web::NavigationItem* previousItem = self.sessionController.previousItem;
const GURL oldURL = previousItem ? previousItem->GetURL() : GURL();
BOOL shouldDispatchHashchange = sameDocumentNavigation && previousItem &&
(web::GURLByRemovingRefFromGURL(URL) ==
web::GURLByRemovingRefFromGURL(oldURL));
// The URL and state object must be set for same-document navigations and
// NavigationItems that were created or updated by calls to pushState() or
// replaceState().
BOOL shouldUpdateState = sameDocumentNavigation ||
currentItem->IsCreatedFromPushState() ||
currentItem->HasStateBeenReplaced();
if (!shouldUpdateState)
return;
// TODO(stuartmorgan): Make CRWSessionController manage this internally (or
// remove it; it's not clear this matches other platforms' behavior).
self.navigationManagerImpl->OnNavigationItemCommitted();
// Record that a same-document hashchange event will be fired. This flag will
// be reset when resonding to the hashchange message. Note that resetting the
// flag in the completion block below is too early, as that block is called
// before hashchange event listeners have a chance to fire.
_dispatchingSameDocumentHashChangeEvent = shouldDispatchHashchange;
// Inject the JavaScript to update the state on the browser side.
[self injectHTML5HistoryScriptWithHashChange:shouldDispatchHashchange
sameDocumentNavigation:sameDocumentNavigation];
}
// Generates the JavaScript string used to update the UIWebView's URL so that it
// matches the URL displayed in the omnibox and sets window.history.state to
// stateObject. Needed for history.pushState() and history.replaceState().
- (NSString*)javaScriptToReplaceWebViewURL:(const GURL&)URL
stateObjectJSON:(NSString*)stateObject {
std::string outURL;
base::EscapeJSONString(URL.spec(), true, &outURL);
return
[NSString stringWithFormat:@"__gCrWeb.replaceWebViewURL(%@, %@);",
base::SysUTF8ToNSString(outURL), stateObject];
}
// Generates the JavaScript string used to manually dispatch a popstate event,
// using |stateObjectJSON| as the event parameter.
- (NSString*)javaScriptToDispatchPopStateWithObject:(NSString*)stateObjectJSON {
std::string outState;
base::EscapeJSONString(base::SysNSStringToUTF8(stateObjectJSON), true,
&outState);
return [NSString stringWithFormat:@"__gCrWeb.dispatchPopstateEvent(%@);",
base::SysUTF8ToNSString(outState)];
}