react-native-webview.git

RNCWebView.m 39KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  1. /**
  2. * Copyright (c) 2015-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. #import "RNCWebView.h"
  8. #import <React/RCTConvert.h>
  9. #import <React/RCTAutoInsetsProtocol.h>
  10. #import "RNCWKProcessPoolManager.h"
  11. #import <UIKit/UIKit.h>
  12. #import "objc/runtime.h"
  13. static NSTimer *keyboardTimer;
  14. static NSString *const MessageHandlerName = @"ReactNativeWebView";
  15. static NSURLCredential* clientAuthenticationCredential;
  16. static NSDictionary* customCertificatesForHost;
  17. // runtime trick to remove WKWebView keyboard default toolbar
  18. // see: http://stackoverflow.com/questions/19033292/ios-7-uiwebview-keyboard-issue/19042279#19042279
  19. @interface _SwizzleHelperWK : UIView
  20. @property (nonatomic, copy) WKWebView *webView;
  21. @end
  22. @implementation _SwizzleHelperWK
  23. -(id)inputAccessoryView
  24. {
  25. if (_webView == nil) {
  26. return nil;
  27. }
  28. if ([_webView respondsToSelector:@selector(inputAssistantItem)]) {
  29. UITextInputAssistantItem *inputAssistantItem = [_webView inputAssistantItem];
  30. inputAssistantItem.leadingBarButtonGroups = @[];
  31. inputAssistantItem.trailingBarButtonGroups = @[];
  32. }
  33. return nil;
  34. }
  35. @end
  36. @interface RNCWebView () <WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler, UIScrollViewDelegate, RCTAutoInsetsProtocol>
  37. @property (nonatomic, copy) RCTDirectEventBlock onLoadingStart;
  38. @property (nonatomic, copy) RCTDirectEventBlock onLoadingFinish;
  39. @property (nonatomic, copy) RCTDirectEventBlock onLoadingError;
  40. @property (nonatomic, copy) RCTDirectEventBlock onLoadingProgress;
  41. @property (nonatomic, copy) RCTDirectEventBlock onShouldStartLoadWithRequest;
  42. @property (nonatomic, copy) RCTDirectEventBlock onHttpError;
  43. @property (nonatomic, copy) RCTDirectEventBlock onMessage;
  44. @property (nonatomic, copy) RCTDirectEventBlock onScroll;
  45. @property (nonatomic, copy) RCTDirectEventBlock onContentProcessDidTerminate;
  46. @property (nonatomic, copy) WKWebView *webView;
  47. @end
  48. @implementation RNCWebView
  49. {
  50. UIColor * _savedBackgroundColor;
  51. BOOL _savedHideKeyboardAccessoryView;
  52. BOOL _savedKeyboardDisplayRequiresUserAction;
  53. // Workaround for StatusBar appearance bug for iOS 12
  54. // https://github.com/react-native-community/react-native-webview/issues/62
  55. BOOL _isFullScreenVideoOpen;
  56. UIStatusBarStyle _savedStatusBarStyle;
  57. BOOL _savedStatusBarHidden;
  58. #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
  59. UIScrollViewContentInsetAdjustmentBehavior _savedContentInsetAdjustmentBehavior;
  60. #endif
  61. }
  62. - (instancetype)initWithFrame:(CGRect)frame
  63. {
  64. if ((self = [super initWithFrame:frame])) {
  65. super.backgroundColor = [UIColor clearColor];
  66. _bounces = YES;
  67. _scrollEnabled = YES;
  68. _showsHorizontalScrollIndicator = YES;
  69. _showsVerticalScrollIndicator = YES;
  70. _directionalLockEnabled = YES;
  71. _automaticallyAdjustContentInsets = YES;
  72. _contentInset = UIEdgeInsetsZero;
  73. _savedKeyboardDisplayRequiresUserAction = YES;
  74. _savedStatusBarStyle = RCTSharedApplication().statusBarStyle;
  75. _savedStatusBarHidden = RCTSharedApplication().statusBarHidden;
  76. #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
  77. _savedContentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
  78. #endif
  79. }
  80. if (@available(iOS 12.0, *)) {
  81. // Workaround for a keyboard dismissal bug present in iOS 12
  82. // https://openradar.appspot.com/radar?id=5018321736957952
  83. [[NSNotificationCenter defaultCenter]
  84. addObserver:self
  85. selector:@selector(keyboardWillHide)
  86. name:UIKeyboardWillHideNotification object:nil];
  87. [[NSNotificationCenter defaultCenter]
  88. addObserver:self
  89. selector:@selector(keyboardWillShow)
  90. name:UIKeyboardWillShowNotification object:nil];
  91. // Workaround for StatusBar appearance bug for iOS 12
  92. // https://github.com/react-native-community/react-native-webview/issues/62
  93. [[NSNotificationCenter defaultCenter] addObserver:self
  94. selector:@selector(showFullScreenVideoStatusBars)
  95. name:UIWindowDidBecomeVisibleNotification
  96. object:nil];
  97. [[NSNotificationCenter defaultCenter] addObserver:self
  98. selector:@selector(hideFullScreenVideoStatusBars)
  99. name:UIWindowDidBecomeHiddenNotification
  100. object:nil];
  101. }
  102. return self;
  103. }
  104. - (void)dealloc
  105. {
  106. [[NSNotificationCenter defaultCenter] removeObserver:self];
  107. }
  108. /**
  109. * See https://stackoverflow.com/questions/25713069/why-is-wkwebview-not-opening-links-with-target-blank/25853806#25853806 for details.
  110. */
  111. - (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
  112. {
  113. if (!navigationAction.targetFrame.isMainFrame) {
  114. [webView loadRequest:navigationAction.request];
  115. }
  116. return nil;
  117. }
  118. - (void)didMoveToWindow
  119. {
  120. if (self.window != nil && _webView == nil) {
  121. WKWebViewConfiguration *wkWebViewConfig = [WKWebViewConfiguration new];
  122. WKPreferences *prefs = [[WKPreferences alloc]init];
  123. BOOL _prefsUsed = NO;
  124. if (!_javaScriptEnabled) {
  125. prefs.javaScriptEnabled = NO;
  126. _prefsUsed = YES;
  127. }
  128. if (_allowFileAccessFromFileURLs) {
  129. [prefs setValue:@TRUE forKey:@"allowFileAccessFromFileURLs"];
  130. _prefsUsed = YES;
  131. }
  132. if (_prefsUsed) {
  133. wkWebViewConfig.preferences = prefs;
  134. }
  135. if (_incognito) {
  136. wkWebViewConfig.websiteDataStore = [WKWebsiteDataStore nonPersistentDataStore];
  137. } else if (_cacheEnabled) {
  138. wkWebViewConfig.websiteDataStore = [WKWebsiteDataStore defaultDataStore];
  139. }
  140. if(self.useSharedProcessPool) {
  141. wkWebViewConfig.processPool = [[RNCWKProcessPoolManager sharedManager] sharedProcessPool];
  142. }
  143. wkWebViewConfig.userContentController = [WKUserContentController new];
  144. if (_messagingEnabled) {
  145. [wkWebViewConfig.userContentController addScriptMessageHandler:self name:MessageHandlerName];
  146. NSString *source = [NSString stringWithFormat:
  147. @"window.%@ = {"
  148. " postMessage: function (data) {"
  149. " window.webkit.messageHandlers.%@.postMessage(String(data));"
  150. " }"
  151. "};", MessageHandlerName, MessageHandlerName
  152. ];
  153. WKUserScript *script = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
  154. [wkWebViewConfig.userContentController addUserScript:script];
  155. if (_injectedJavaScriptBeforeContentLoaded) {
  156. // If user has provided an injectedJavascript prop, execute it at the start of the document
  157. WKUserScript *injectedScript = [[WKUserScript alloc] initWithSource:_injectedJavaScriptBeforeContentLoaded injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
  158. [wkWebViewConfig.userContentController addUserScript:injectedScript];
  159. }
  160. }
  161. wkWebViewConfig.allowsInlineMediaPlayback = _allowsInlineMediaPlayback;
  162. #if WEBKIT_IOS_10_APIS_AVAILABLE
  163. wkWebViewConfig.mediaTypesRequiringUserActionForPlayback = _mediaPlaybackRequiresUserAction
  164. ? WKAudiovisualMediaTypeAll
  165. : WKAudiovisualMediaTypeNone;
  166. wkWebViewConfig.dataDetectorTypes = _dataDetectorTypes;
  167. #else
  168. wkWebViewConfig.mediaPlaybackRequiresUserAction = _mediaPlaybackRequiresUserAction;
  169. #endif
  170. if (_applicationNameForUserAgent) {
  171. wkWebViewConfig.applicationNameForUserAgent = [NSString stringWithFormat:@"%@ %@", wkWebViewConfig.applicationNameForUserAgent, _applicationNameForUserAgent];
  172. }
  173. if(_sharedCookiesEnabled) {
  174. // More info to sending cookies with WKWebView
  175. // https://stackoverflow.com/questions/26573137/can-i-set-the-cookies-to-be-used-by-a-wkwebview/26577303#26577303
  176. if (@available(iOS 11.0, *)) {
  177. // Set Cookies in iOS 11 and above, initialize websiteDataStore before setting cookies
  178. // See also https://forums.developer.apple.com/thread/97194
  179. // check if websiteDataStore has not been initialized before
  180. if(!_incognito && !_cacheEnabled) {
  181. wkWebViewConfig.websiteDataStore = [WKWebsiteDataStore nonPersistentDataStore];
  182. }
  183. for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
  184. [wkWebViewConfig.websiteDataStore.httpCookieStore setCookie:cookie completionHandler:nil];
  185. }
  186. } else {
  187. NSMutableString *script = [NSMutableString string];
  188. // Clear all existing cookies in a direct called function. This ensures that no
  189. // javascript error will break the web content javascript.
  190. // We keep this code here, if someone requires that Cookies are also removed within the
  191. // the WebView and want to extends the current sharedCookiesEnabled option with an
  192. // additional property.
  193. // Generates JS: document.cookie = "key=; Expires=Thu, 01 Jan 1970 00:00:01 GMT;"
  194. // for each cookie which is already available in the WebView context.
  195. /*
  196. [script appendString:@"(function () {\n"];
  197. [script appendString:@" var cookies = document.cookie.split('; ');\n"];
  198. [script appendString:@" for (var i = 0; i < cookies.length; i++) {\n"];
  199. [script appendString:@" if (cookies[i].indexOf('=') !== -1) {\n"];
  200. [script appendString:@" document.cookie = cookies[i].split('=')[0] + '=; Expires=Thu, 01 Jan 1970 00:00:01 GMT';\n"];
  201. [script appendString:@" }\n"];
  202. [script appendString:@" }\n"];
  203. [script appendString:@"})();\n\n"];
  204. */
  205. // Set cookies in a direct called function. This ensures that no
  206. // javascript error will break the web content javascript.
  207. // Generates JS: document.cookie = "key=value; Path=/; Expires=Thu, 01 Jan 20xx 00:00:01 GMT;"
  208. // for each cookie which is available in the application context.
  209. [script appendString:@"(function () {\n"];
  210. for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
  211. [script appendFormat:@"document.cookie = %@ + '=' + %@",
  212. RCTJSONStringify(cookie.name, NULL),
  213. RCTJSONStringify(cookie.value, NULL)];
  214. if (cookie.path) {
  215. [script appendFormat:@" + '; Path=' + %@", RCTJSONStringify(cookie.path, NULL)];
  216. }
  217. if (cookie.expiresDate) {
  218. [script appendFormat:@" + '; Expires=' + new Date(%f).toUTCString()",
  219. cookie.expiresDate.timeIntervalSince1970 * 1000
  220. ];
  221. }
  222. [script appendString:@";\n"];
  223. }
  224. [script appendString:@"})();\n"];
  225. WKUserScript* cookieInScript = [[WKUserScript alloc] initWithSource:script
  226. injectionTime:WKUserScriptInjectionTimeAtDocumentStart
  227. forMainFrameOnly:YES];
  228. [wkWebViewConfig.userContentController addUserScript:cookieInScript];
  229. }
  230. }
  231. _webView = [[WKWebView alloc] initWithFrame:self.bounds configuration: wkWebViewConfig];
  232. [self setBackgroundColor: _savedBackgroundColor];
  233. _webView.scrollView.delegate = self;
  234. _webView.UIDelegate = self;
  235. _webView.navigationDelegate = self;
  236. _webView.scrollView.scrollEnabled = _scrollEnabled;
  237. _webView.scrollView.pagingEnabled = _pagingEnabled;
  238. _webView.scrollView.bounces = _bounces;
  239. _webView.scrollView.showsHorizontalScrollIndicator = _showsHorizontalScrollIndicator;
  240. _webView.scrollView.showsVerticalScrollIndicator = _showsVerticalScrollIndicator;
  241. _webView.scrollView.directionalLockEnabled = _directionalLockEnabled;
  242. _webView.allowsLinkPreview = _allowsLinkPreview;
  243. [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
  244. _webView.allowsBackForwardNavigationGestures = _allowsBackForwardNavigationGestures;
  245. if (_userAgent) {
  246. _webView.customUserAgent = _userAgent;
  247. }
  248. #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
  249. if ([_webView.scrollView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
  250. _webView.scrollView.contentInsetAdjustmentBehavior = _savedContentInsetAdjustmentBehavior;
  251. }
  252. #endif
  253. [self addSubview:_webView];
  254. [self setHideKeyboardAccessoryView: _savedHideKeyboardAccessoryView];
  255. [self setKeyboardDisplayRequiresUserAction: _savedKeyboardDisplayRequiresUserAction];
  256. [self visitSource];
  257. }
  258. }
  259. // Update webview property when the component prop changes.
  260. - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures {
  261. _allowsBackForwardNavigationGestures = allowsBackForwardNavigationGestures;
  262. _webView.allowsBackForwardNavigationGestures = _allowsBackForwardNavigationGestures;
  263. }
  264. - (void)removeFromSuperview
  265. {
  266. if (_webView) {
  267. [_webView.configuration.userContentController removeScriptMessageHandlerForName:MessageHandlerName];
  268. [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
  269. [_webView removeFromSuperview];
  270. _webView.scrollView.delegate = nil;
  271. _webView = nil;
  272. }
  273. [super removeFromSuperview];
  274. }
  275. -(void)showFullScreenVideoStatusBars
  276. {
  277. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  278. _isFullScreenVideoOpen = YES;
  279. RCTUnsafeExecuteOnMainQueueSync(^{
  280. [RCTSharedApplication() setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
  281. });
  282. #pragma clang diagnostic pop
  283. }
  284. -(void)hideFullScreenVideoStatusBars
  285. {
  286. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  287. _isFullScreenVideoOpen = NO;
  288. RCTUnsafeExecuteOnMainQueueSync(^{
  289. [RCTSharedApplication() setStatusBarHidden:self->_savedStatusBarHidden animated:YES];
  290. [RCTSharedApplication() setStatusBarStyle:self->_savedStatusBarStyle animated:YES];
  291. });
  292. #pragma clang diagnostic pop
  293. }
  294. -(void)keyboardWillHide
  295. {
  296. keyboardTimer = [NSTimer scheduledTimerWithTimeInterval:0 target:self selector:@selector(keyboardDisplacementFix) userInfo:nil repeats:false];
  297. [[NSRunLoop mainRunLoop] addTimer:keyboardTimer forMode:NSRunLoopCommonModes];
  298. }
  299. -(void)keyboardWillShow
  300. {
  301. if (keyboardTimer != nil) {
  302. [keyboardTimer invalidate];
  303. }
  304. }
  305. -(void)keyboardDisplacementFix
  306. {
  307. // Additional viewport checks to prevent unintentional scrolls
  308. UIScrollView *scrollView = self.webView.scrollView;
  309. double maxContentOffset = scrollView.contentSize.height - scrollView.frame.size.height;
  310. if (maxContentOffset < 0) {
  311. maxContentOffset = 0;
  312. }
  313. if (scrollView.contentOffset.y > maxContentOffset) {
  314. // https://stackoverflow.com/a/9637807/824966
  315. [UIView animateWithDuration:.25 animations:^{
  316. scrollView.contentOffset = CGPointMake(0, maxContentOffset);
  317. }];
  318. }
  319. }
  320. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
  321. if ([keyPath isEqual:@"estimatedProgress"] && object == self.webView) {
  322. if(_onLoadingProgress){
  323. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  324. [event addEntriesFromDictionary:@{@"progress":[NSNumber numberWithDouble:self.webView.estimatedProgress]}];
  325. _onLoadingProgress(event);
  326. }
  327. }else{
  328. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  329. }
  330. }
  331. - (void)setBackgroundColor:(UIColor *)backgroundColor
  332. {
  333. _savedBackgroundColor = backgroundColor;
  334. if (_webView == nil) {
  335. return;
  336. }
  337. CGFloat alpha = CGColorGetAlpha(backgroundColor.CGColor);
  338. self.opaque = _webView.opaque = (alpha == 1.0);
  339. _webView.scrollView.backgroundColor = backgroundColor;
  340. _webView.backgroundColor = backgroundColor;
  341. }
  342. #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
  343. - (void)setContentInsetAdjustmentBehavior:(UIScrollViewContentInsetAdjustmentBehavior)behavior
  344. {
  345. _savedContentInsetAdjustmentBehavior = behavior;
  346. if (_webView == nil) {
  347. return;
  348. }
  349. if ([_webView.scrollView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
  350. CGPoint contentOffset = _webView.scrollView.contentOffset;
  351. _webView.scrollView.contentInsetAdjustmentBehavior = behavior;
  352. _webView.scrollView.contentOffset = contentOffset;
  353. }
  354. }
  355. #endif
  356. /**
  357. * This method is called whenever JavaScript running within the web view calls:
  358. * - window.webkit.messageHandlers[MessageHandlerName].postMessage
  359. */
  360. - (void)userContentController:(WKUserContentController *)userContentController
  361. didReceiveScriptMessage:(WKScriptMessage *)message
  362. {
  363. if (_onMessage != nil) {
  364. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  365. [event addEntriesFromDictionary: @{@"data": message.body}];
  366. _onMessage(event);
  367. }
  368. }
  369. - (void)setSource:(NSDictionary *)source
  370. {
  371. if (![_source isEqualToDictionary:source]) {
  372. _source = [source copy];
  373. if (_webView != nil) {
  374. [self visitSource];
  375. }
  376. }
  377. }
  378. - (void)setAllowingReadAccessToURL:(NSString *)allowingReadAccessToURL
  379. {
  380. if (![_allowingReadAccessToURL isEqualToString:allowingReadAccessToURL]) {
  381. _allowingReadAccessToURL = [allowingReadAccessToURL copy];
  382. if (_webView != nil) {
  383. [self visitSource];
  384. }
  385. }
  386. }
  387. - (void)setContentInset:(UIEdgeInsets)contentInset
  388. {
  389. _contentInset = contentInset;
  390. [RCTView autoAdjustInsetsForView:self
  391. withScrollView:_webView.scrollView
  392. updateOffset:NO];
  393. }
  394. - (void)refreshContentInset
  395. {
  396. [RCTView autoAdjustInsetsForView:self
  397. withScrollView:_webView.scrollView
  398. updateOffset:YES];
  399. }
  400. - (void)visitSource
  401. {
  402. // Check for a static html source first
  403. NSString *html = [RCTConvert NSString:_source[@"html"]];
  404. if (html) {
  405. NSURL *baseURL = [RCTConvert NSURL:_source[@"baseUrl"]];
  406. if (!baseURL) {
  407. baseURL = [NSURL URLWithString:@"about:blank"];
  408. }
  409. [_webView loadHTMLString:html baseURL:baseURL];
  410. return;
  411. }
  412. NSURLRequest *request = [self requestForSource:_source];
  413. // Because of the way React works, as pages redirect, we actually end up
  414. // passing the redirect urls back here, so we ignore them if trying to load
  415. // the same url. We'll expose a call to 'reload' to allow a user to load
  416. // the existing page.
  417. if ([request.URL isEqual:_webView.URL]) {
  418. return;
  419. }
  420. if (!request.URL) {
  421. // Clear the webview
  422. [_webView loadHTMLString:@"" baseURL:nil];
  423. return;
  424. }
  425. if (request.URL.host) {
  426. [_webView loadRequest:request];
  427. }
  428. else {
  429. NSURL* readAccessUrl = _allowingReadAccessToURL ? [RCTConvert NSURL:_allowingReadAccessToURL] : request.URL;
  430. [_webView loadFileURL:request.URL allowingReadAccessToURL:readAccessUrl];
  431. }
  432. }
  433. -(void)setKeyboardDisplayRequiresUserAction:(BOOL)keyboardDisplayRequiresUserAction
  434. {
  435. if (_webView == nil) {
  436. _savedKeyboardDisplayRequiresUserAction = keyboardDisplayRequiresUserAction;
  437. return;
  438. }
  439. if (_savedKeyboardDisplayRequiresUserAction == true) {
  440. return;
  441. }
  442. UIView* subview;
  443. for (UIView* view in _webView.scrollView.subviews) {
  444. if([[view.class description] hasPrefix:@"WK"])
  445. subview = view;
  446. }
  447. if(subview == nil) return;
  448. Class class = subview.class;
  449. NSOperatingSystemVersion iOS_11_3_0 = (NSOperatingSystemVersion){11, 3, 0};
  450. NSOperatingSystemVersion iOS_12_2_0 = (NSOperatingSystemVersion){12, 2, 0};
  451. NSOperatingSystemVersion iOS_13_0_0 = (NSOperatingSystemVersion){13, 0, 0};
  452. Method method;
  453. IMP override;
  454. if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion: iOS_13_0_0]) {
  455. // iOS 13.0.0 - Future
  456. SEL selector = sel_getUid("_elementDidFocus:userIsInteracting:blurPreviousNode:activityStateChanges:userObject:");
  457. method = class_getInstanceMethod(class, selector);
  458. IMP original = method_getImplementation(method);
  459. override = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, BOOL arg3, id arg4) {
  460. ((void (*)(id, SEL, void*, BOOL, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3, arg4);
  461. });
  462. }
  463. else if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion: iOS_12_2_0]) {
  464. // iOS 12.2.0 - iOS 13.0.0
  465. SEL selector = sel_getUid("_elementDidFocus:userIsInteracting:blurPreviousNode:changingActivityState:userObject:");
  466. method = class_getInstanceMethod(class, selector);
  467. IMP original = method_getImplementation(method);
  468. override = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, BOOL arg3, id arg4) {
  469. ((void (*)(id, SEL, void*, BOOL, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3, arg4);
  470. });
  471. }
  472. else if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion: iOS_11_3_0]) {
  473. // iOS 11.3.0 - 12.2.0
  474. SEL selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:changingActivityState:userObject:");
  475. method = class_getInstanceMethod(class, selector);
  476. IMP original = method_getImplementation(method);
  477. override = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, BOOL arg3, id arg4) {
  478. ((void (*)(id, SEL, void*, BOOL, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3, arg4);
  479. });
  480. } else {
  481. // iOS 9.0 - 11.3.0
  482. SEL selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:userObject:");
  483. method = class_getInstanceMethod(class, selector);
  484. IMP original = method_getImplementation(method);
  485. override = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, id arg3) {
  486. ((void (*)(id, SEL, void*, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3);
  487. });
  488. }
  489. method_setImplementation(method, override);
  490. }
  491. -(void)setHideKeyboardAccessoryView:(BOOL)hideKeyboardAccessoryView
  492. {
  493. if (_webView == nil) {
  494. _savedHideKeyboardAccessoryView = hideKeyboardAccessoryView;
  495. return;
  496. }
  497. if (_savedHideKeyboardAccessoryView == false) {
  498. return;
  499. }
  500. UIView* subview;
  501. for (UIView* view in _webView.scrollView.subviews) {
  502. if([[view.class description] hasPrefix:@"WK"])
  503. subview = view;
  504. }
  505. if(subview == nil) return;
  506. NSString* name = [NSString stringWithFormat:@"%@_SwizzleHelperWK", subview.class.superclass];
  507. Class newClass = NSClassFromString(name);
  508. if(newClass == nil)
  509. {
  510. newClass = objc_allocateClassPair(subview.class, [name cStringUsingEncoding:NSASCIIStringEncoding], 0);
  511. if(!newClass) return;
  512. Method method = class_getInstanceMethod([_SwizzleHelperWK class], @selector(inputAccessoryView));
  513. class_addMethod(newClass, @selector(inputAccessoryView), method_getImplementation(method), method_getTypeEncoding(method));
  514. objc_registerClassPair(newClass);
  515. }
  516. object_setClass(subview, newClass);
  517. }
  518. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  519. {
  520. scrollView.decelerationRate = _decelerationRate;
  521. }
  522. - (void)setScrollEnabled:(BOOL)scrollEnabled
  523. {
  524. _scrollEnabled = scrollEnabled;
  525. _webView.scrollView.scrollEnabled = scrollEnabled;
  526. }
  527. - (void)scrollViewDidScroll:(UIScrollView *)scrollView
  528. {
  529. // Don't allow scrolling the scrollView.
  530. if (!_scrollEnabled) {
  531. scrollView.bounds = _webView.bounds;
  532. }
  533. else if (_onScroll != nil) {
  534. NSDictionary *event = @{
  535. @"contentOffset": @{
  536. @"x": @(scrollView.contentOffset.x),
  537. @"y": @(scrollView.contentOffset.y)
  538. },
  539. @"contentInset": @{
  540. @"top": @(scrollView.contentInset.top),
  541. @"left": @(scrollView.contentInset.left),
  542. @"bottom": @(scrollView.contentInset.bottom),
  543. @"right": @(scrollView.contentInset.right)
  544. },
  545. @"contentSize": @{
  546. @"width": @(scrollView.contentSize.width),
  547. @"height": @(scrollView.contentSize.height)
  548. },
  549. @"layoutMeasurement": @{
  550. @"width": @(scrollView.frame.size.width),
  551. @"height": @(scrollView.frame.size.height)
  552. },
  553. @"zoomScale": @(scrollView.zoomScale ?: 1),
  554. };
  555. _onScroll(event);
  556. }
  557. }
  558. - (void)setDirectionalLockEnabled:(BOOL)directionalLockEnabled
  559. {
  560. _directionalLockEnabled = directionalLockEnabled;
  561. _webView.scrollView.directionalLockEnabled = directionalLockEnabled;
  562. }
  563. - (void)setShowsHorizontalScrollIndicator:(BOOL)showsHorizontalScrollIndicator
  564. {
  565. _showsHorizontalScrollIndicator = showsHorizontalScrollIndicator;
  566. _webView.scrollView.showsHorizontalScrollIndicator = showsHorizontalScrollIndicator;
  567. }
  568. - (void)setShowsVerticalScrollIndicator:(BOOL)showsVerticalScrollIndicator
  569. {
  570. _showsVerticalScrollIndicator = showsVerticalScrollIndicator;
  571. _webView.scrollView.showsVerticalScrollIndicator = showsVerticalScrollIndicator;
  572. }
  573. - (void)postMessage:(NSString *)message
  574. {
  575. NSDictionary *eventInitDict = @{@"data": message};
  576. NSString *source = [NSString
  577. stringWithFormat:@"window.dispatchEvent(new MessageEvent('message', %@));",
  578. RCTJSONStringify(eventInitDict, NULL)
  579. ];
  580. [self injectJavaScript: source];
  581. }
  582. - (void)layoutSubviews
  583. {
  584. [super layoutSubviews];
  585. // Ensure webview takes the position and dimensions of RNCWebView
  586. _webView.frame = self.bounds;
  587. _webView.scrollView.contentInset = _contentInset;
  588. }
  589. - (NSMutableDictionary<NSString *, id> *)baseEvent
  590. {
  591. NSDictionary *event = @{
  592. @"url": _webView.URL.absoluteString ?: @"",
  593. @"title": _webView.title ?: @"",
  594. @"loading" : @(_webView.loading),
  595. @"canGoBack": @(_webView.canGoBack),
  596. @"canGoForward" : @(_webView.canGoForward)
  597. };
  598. return [[NSMutableDictionary alloc] initWithDictionary: event];
  599. }
  600. + (void)setClientAuthenticationCredential:(nullable NSURLCredential*)credential {
  601. clientAuthenticationCredential = credential;
  602. }
  603. + (void)setCustomCertificatesForHost:(nullable NSDictionary*)certificates {
  604. customCertificatesForHost = certificates;
  605. }
  606. - (void) webView:(WKWebView *)webView
  607. didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
  608. completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable))completionHandler
  609. {
  610. NSString* host = nil;
  611. if (webView.URL != nil) {
  612. host = webView.URL.host;
  613. }
  614. if ([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodClientCertificate) {
  615. completionHandler(NSURLSessionAuthChallengeUseCredential, clientAuthenticationCredential);
  616. return;
  617. }
  618. if ([[challenge protectionSpace] serverTrust] != nil && customCertificatesForHost != nil && host != nil) {
  619. SecCertificateRef localCertificate = (__bridge SecCertificateRef)([customCertificatesForHost objectForKey:host]);
  620. if (localCertificate != nil) {
  621. NSData *localCertificateData = (NSData*) CFBridgingRelease(SecCertificateCopyData(localCertificate));
  622. SecTrustRef trust = [[challenge protectionSpace] serverTrust];
  623. long count = SecTrustGetCertificateCount(trust);
  624. for (long i = 0; i < count; i++) {
  625. SecCertificateRef serverCertificate = SecTrustGetCertificateAtIndex(trust, i);
  626. if (serverCertificate == nil) { continue; }
  627. NSData *serverCertificateData = (NSData *) CFBridgingRelease(SecCertificateCopyData(serverCertificate));
  628. if ([serverCertificateData isEqualToData:localCertificateData]) {
  629. NSURLCredential *useCredential = [NSURLCredential credentialForTrust:trust];
  630. if (challenge.sender != nil) {
  631. [challenge.sender useCredential:useCredential forAuthenticationChallenge:challenge];
  632. }
  633. completionHandler(NSURLSessionAuthChallengeUseCredential, useCredential);
  634. return;
  635. }
  636. }
  637. }
  638. }
  639. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  640. }
  641. #pragma mark - WKNavigationDelegate methods
  642. /**
  643. * alert
  644. */
  645. - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
  646. {
  647. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
  648. [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  649. completionHandler();
  650. }]];
  651. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  652. }
  653. /**
  654. * confirm
  655. */
  656. - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
  657. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
  658. [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  659. completionHandler(YES);
  660. }]];
  661. [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  662. completionHandler(NO);
  663. }]];
  664. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  665. }
  666. /**
  667. * prompt
  668. */
  669. - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *))completionHandler{
  670. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:prompt preferredStyle:UIAlertControllerStyleAlert];
  671. [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  672. textField.text = defaultText;
  673. }];
  674. UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  675. completionHandler([[alert.textFields lastObject] text]);
  676. }];
  677. [alert addAction:okAction];
  678. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  679. completionHandler(nil);
  680. }];
  681. [alert addAction:cancelAction];
  682. alert.preferredAction = okAction;
  683. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  684. }
  685. /**
  686. * topViewController
  687. */
  688. -(UIViewController *)topViewController{
  689. UIViewController *controller = [self topViewControllerWithRootViewController:[self getCurrentWindow].rootViewController];
  690. return controller;
  691. }
  692. /**
  693. * topViewControllerWithRootViewController
  694. */
  695. -(UIViewController *)topViewControllerWithRootViewController:(UIViewController *)viewController{
  696. if (viewController==nil) return nil;
  697. if (viewController.presentedViewController!=nil) {
  698. return [self topViewControllerWithRootViewController:viewController.presentedViewController];
  699. } else if ([viewController isKindOfClass:[UITabBarController class]]){
  700. return [self topViewControllerWithRootViewController:[(UITabBarController *)viewController selectedViewController]];
  701. } else if ([viewController isKindOfClass:[UINavigationController class]]){
  702. return [self topViewControllerWithRootViewController:[(UINavigationController *)viewController visibleViewController]];
  703. } else {
  704. return viewController;
  705. }
  706. }
  707. /**
  708. * getCurrentWindow
  709. */
  710. -(UIWindow *)getCurrentWindow{
  711. UIWindow *window = [UIApplication sharedApplication].keyWindow;
  712. if (window.windowLevel!=UIWindowLevelNormal) {
  713. for (UIWindow *wid in [UIApplication sharedApplication].windows) {
  714. if (window.windowLevel==UIWindowLevelNormal) {
  715. window = wid;
  716. break;
  717. }
  718. }
  719. }
  720. return window;
  721. }
  722. /**
  723. * Decides whether to allow or cancel a navigation.
  724. * @see https://fburl.com/42r9fxob
  725. */
  726. - (void) webView:(WKWebView *)webView
  727. decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
  728. decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
  729. {
  730. static NSDictionary<NSNumber *, NSString *> *navigationTypes;
  731. static dispatch_once_t onceToken;
  732. dispatch_once(&onceToken, ^{
  733. navigationTypes = @{
  734. @(WKNavigationTypeLinkActivated): @"click",
  735. @(WKNavigationTypeFormSubmitted): @"formsubmit",
  736. @(WKNavigationTypeBackForward): @"backforward",
  737. @(WKNavigationTypeReload): @"reload",
  738. @(WKNavigationTypeFormResubmitted): @"formresubmit",
  739. @(WKNavigationTypeOther): @"other",
  740. };
  741. });
  742. WKNavigationType navigationType = navigationAction.navigationType;
  743. NSURLRequest *request = navigationAction.request;
  744. if (_onShouldStartLoadWithRequest) {
  745. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  746. [event addEntriesFromDictionary: @{
  747. @"url": (request.URL).absoluteString,
  748. @"mainDocumentURL": (request.mainDocumentURL).absoluteString,
  749. @"navigationType": navigationTypes[@(navigationType)]
  750. }];
  751. if (![self.delegate webView:self
  752. shouldStartLoadForRequest:event
  753. withCallback:_onShouldStartLoadWithRequest]) {
  754. decisionHandler(WKNavigationActionPolicyCancel);
  755. return;
  756. }
  757. }
  758. if (_onLoadingStart) {
  759. // We have this check to filter out iframe requests and whatnot
  760. BOOL isTopFrame = [request.URL isEqual:request.mainDocumentURL];
  761. if (isTopFrame) {
  762. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  763. [event addEntriesFromDictionary: @{
  764. @"url": (request.URL).absoluteString,
  765. @"navigationType": navigationTypes[@(navigationType)]
  766. }];
  767. _onLoadingStart(event);
  768. }
  769. }
  770. // Allow all navigation by default
  771. decisionHandler(WKNavigationActionPolicyAllow);
  772. }
  773. /**
  774. * Called when the web view’s content process is terminated.
  775. * @see https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455639-webviewwebcontentprocessdidtermi?language=objc
  776. */
  777. - (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView
  778. {
  779. RCTLogWarn(@"Webview Process Terminated");
  780. if (_onContentProcessDidTerminate) {
  781. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  782. _onContentProcessDidTerminate(event);
  783. }
  784. }
  785. /**
  786. * Decides whether to allow or cancel a navigation after its response is known.
  787. * @see https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455643-webview?language=objc
  788. */
  789. - (void) webView:(WKWebView *)webView
  790. decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse
  791. decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
  792. {
  793. if (_onHttpError && navigationResponse.forMainFrame) {
  794. if ([navigationResponse.response isKindOfClass:[NSHTTPURLResponse class]]) {
  795. NSHTTPURLResponse *response = (NSHTTPURLResponse *)navigationResponse.response;
  796. NSInteger statusCode = response.statusCode;
  797. if (statusCode >= 400) {
  798. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  799. [event addEntriesFromDictionary: @{
  800. @"url": response.URL.absoluteString,
  801. @"statusCode": @(statusCode)
  802. }];
  803. _onHttpError(event);
  804. }
  805. }
  806. }
  807. decisionHandler(WKNavigationResponsePolicyAllow);
  808. }
  809. /**
  810. * Called when an error occurs while the web view is loading content.
  811. * @see https://fburl.com/km6vqenw
  812. */
  813. - (void) webView:(WKWebView *)webView
  814. didFailProvisionalNavigation:(WKNavigation *)navigation
  815. withError:(NSError *)error
  816. {
  817. if (_onLoadingError) {
  818. if ([error.domain isEqualToString:NSURLErrorDomain] && error.code == NSURLErrorCancelled) {
  819. // NSURLErrorCancelled is reported when a page has a redirect OR if you load
  820. // a new URL in the WebView before the previous one came back. We can just
  821. // ignore these since they aren't real errors.
  822. // http://stackoverflow.com/questions/1024748/how-do-i-fix-nsurlerrordomain-error-999-in-iphone-3-0-os
  823. return;
  824. }
  825. if ([error.domain isEqualToString:@"WebKitErrorDomain"] && error.code == 102) {
  826. // Error code 102 "Frame load interrupted" is raised by the WKWebView
  827. // when the URL is from an http redirect. This is a common pattern when
  828. // implementing OAuth with a WebView.
  829. return;
  830. }
  831. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  832. [event addEntriesFromDictionary:@{
  833. @"didFailProvisionalNavigation": @YES,
  834. @"domain": error.domain,
  835. @"code": @(error.code),
  836. @"description": error.localizedDescription,
  837. }];
  838. _onLoadingError(event);
  839. }
  840. }
  841. - (void)evaluateJS:(NSString *)js
  842. thenCall: (void (^)(NSString*)) callback
  843. {
  844. [self.webView evaluateJavaScript: js completionHandler: ^(id result, NSError *error) {
  845. if (callback != nil) {
  846. callback([NSString stringWithFormat:@"%@", result]);
  847. }
  848. if (error != nil) {
  849. RCTLogWarn(@"%@", [NSString stringWithFormat:@"Error evaluating injectedJavaScript: This is possibly due to an unsupported return type. Try adding true to the end of your injectedJavaScript string. %@", error]);
  850. }
  851. }];
  852. }
  853. /**
  854. * Called when the navigation is complete.
  855. * @see https://fburl.com/rtys6jlb
  856. */
  857. - (void)webView:(WKWebView *)webView
  858. didFinishNavigation:(WKNavigation *)navigation
  859. {
  860. if (_injectedJavaScript) {
  861. [self evaluateJS: _injectedJavaScript thenCall: ^(NSString *jsEvaluationValue) {
  862. NSMutableDictionary *event = [self baseEvent];
  863. event[@"jsEvaluationValue"] = jsEvaluationValue;
  864. if (self.onLoadingFinish) {
  865. self.onLoadingFinish(event);
  866. }
  867. }];
  868. } else if (_onLoadingFinish) {
  869. _onLoadingFinish([self baseEvent]);
  870. }
  871. }
  872. - (void)injectJavaScript:(NSString *)script
  873. {
  874. [self evaluateJS: script thenCall: nil];
  875. }
  876. - (void)goForward
  877. {
  878. [_webView goForward];
  879. }
  880. - (void)goBack
  881. {
  882. [_webView goBack];
  883. }
  884. - (void)reload
  885. {
  886. /**
  887. * When the initial load fails due to network connectivity issues,
  888. * [_webView reload] doesn't reload the webpage. Therefore, we must
  889. * manually call [_webView loadRequest:request].
  890. */
  891. NSURLRequest *request = [self requestForSource:self.source];
  892. if (request.URL && !_webView.URL.absoluteString.length) {
  893. [_webView loadRequest:request];
  894. } else {
  895. [_webView reload];
  896. }
  897. }
  898. - (void)stopLoading
  899. {
  900. [_webView stopLoading];
  901. }
  902. - (void)setBounces:(BOOL)bounces
  903. {
  904. _bounces = bounces;
  905. _webView.scrollView.bounces = bounces;
  906. }
  907. - (NSURLRequest *)requestForSource:(id)json {
  908. NSURLRequest *request = [RCTConvert NSURLRequest:self.source];
  909. // If sharedCookiesEnabled we automatically add all application cookies to the
  910. // http request. This is automatically done on iOS 11+ in the WebView constructor.
  911. // Se we need to manually add these shared cookies here only for iOS versions < 11.
  912. if (_sharedCookiesEnabled) {
  913. if (@available(iOS 11.0, *)) {
  914. // see WKWebView initialization for added cookies
  915. } else {
  916. NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:request.URL];
  917. NSDictionary<NSString *, NSString *> *cookieHeader = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
  918. NSMutableURLRequest *mutableRequest = [request mutableCopy];
  919. [mutableRequest setAllHTTPHeaderFields:cookieHeader];
  920. return mutableRequest;
  921. }
  922. }
  923. return request;
  924. }
  925. @end