react-native-webview.git

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