react-native-webview.git

RNCWebView.m 44KB

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