react-native-webview.git

RNCWebView.m 44KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  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];
  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 (_injectedJavaScript) {
  811. [self evaluateJS: _injectedJavaScript thenCall: ^(NSString *jsEvaluationValue) {
  812. NSMutableDictionary *event = [self baseEvent];
  813. event[@"jsEvaluationValue"] = jsEvaluationValue;
  814. if (self.onLoadingFinish) {
  815. self.onLoadingFinish(event);
  816. }
  817. }];
  818. } else if (_onLoadingFinish) {
  819. _onLoadingFinish([self baseEvent]);
  820. }
  821. }
  822. - (void)injectJavaScript:(NSString *)script
  823. {
  824. [self evaluateJS: script thenCall: nil];
  825. }
  826. - (void)goForward
  827. {
  828. [_webView goForward];
  829. }
  830. - (void)goBack
  831. {
  832. [_webView goBack];
  833. }
  834. - (void)reload
  835. {
  836. /**
  837. * When the initial load fails due to network connectivity issues,
  838. * [_webView reload] doesn't reload the webpage. Therefore, we must
  839. * manually call [_webView loadRequest:request].
  840. */
  841. NSURLRequest *request = [self requestForSource:self.source];
  842. if (request.URL && !_webView.URL.absoluteString.length) {
  843. [_webView loadRequest:request];
  844. } else {
  845. [_webView reload];
  846. }
  847. }
  848. - (void)stopLoading
  849. {
  850. [_webView stopLoading];
  851. }
  852. - (void)setBounces:(BOOL)bounces
  853. {
  854. _bounces = bounces;
  855. _webView.scrollView.bounces = bounces;
  856. }
  857. - (void)setInjectedJavaScript:(NSString *)script {
  858. _injectedJavaScript = script;
  859. self.atStartScript = script == nil ? nil : [[WKUserScript alloc] initWithSource:script
  860. injectionTime:WKUserScriptInjectionTimeAtDocumentStart
  861. forMainFrameOnly:_injectedJavaScriptForMainFrameOnly];
  862. [self resetupScripts];
  863. }
  864. - (void)setInjectedJavaScriptBeforeContentLoaded:(NSString *)script {
  865. _injectedJavaScriptBeforeContentLoaded = script;
  866. self.atEndScript = script == nil ? nil : [[WKUserScript alloc] initWithSource:script
  867. injectionTime:WKUserScriptInjectionTimeAtDocumentEnd
  868. forMainFrameOnly:_injectedJavaScriptBeforeContentLoadedForMainFrameOnly];
  869. [self resetupScripts];
  870. }
  871. - (void)setInjectedJavaScriptForMainFrameOnly:(BOOL)inject {
  872. _injectedJavaScriptForMainFrameOnly = inject;
  873. [self setInjectedJavaScript:_injectedJavaScript];
  874. }
  875. - (void)setInjectedJavaScriptBeforeContentLoadedForMainFrameOnly:(BOOL)inject {
  876. _injectedJavaScriptBeforeContentLoadedForMainFrameOnly = inject;
  877. [self setInjectedJavaScriptBeforeContentLoaded:_injectedJavaScriptBeforeContentLoaded];
  878. }
  879. - (void)setMessagingEnabled:(BOOL)messagingEnabled {
  880. _messagingEnabled = messagingEnabled;
  881. self.postMessageScript = _messagingEnabled ?
  882. [
  883. [WKUserScript alloc]
  884. initWithSource: [
  885. NSString
  886. stringWithFormat:
  887. @"window.%@ = {"
  888. " postMessage: function (data) {"
  889. " window.webkit.messageHandlers.%@.postMessage(String(data));"
  890. " }"
  891. "};", MessageHandlerName, MessageHandlerName
  892. ]
  893. injectionTime:WKUserScriptInjectionTimeAtDocumentStart
  894. /* This was previously YES, but I'm following react-native-wkwebview's approach on this;
  895. * It's very useful to be able to inject postMessage into iframes. */
  896. forMainFrameOnly:_injectedJavaScriptBeforeContentLoadedForMainFrameOnly
  897. ] :
  898. nil;
  899. [self resetupScripts];
  900. }
  901. - (void)resetupScripts {
  902. [_webView.configuration.userContentController removeAllUserScripts];
  903. [_webView.configuration.userContentController removeScriptMessageHandlerForName:MessageHandlerName];
  904. NSString *html5HistoryAPIShimSource = [NSString stringWithFormat:
  905. @"(function(history) {\n"
  906. " function notify(type) {\n"
  907. " setTimeout(function() {\n"
  908. " window.webkit.messageHandlers.%@.postMessage(type)\n"
  909. " }, 0)\n"
  910. " }\n"
  911. " function shim(f) {\n"
  912. " return function pushState() {\n"
  913. " notify('other')\n"
  914. " return f.apply(history, arguments)\n"
  915. " }\n"
  916. " }\n"
  917. " history.pushState = shim(history.pushState)\n"
  918. " history.replaceState = shim(history.replaceState)\n"
  919. " window.addEventListener('popstate', function() {\n"
  920. " notify('backforward')\n"
  921. " })\n"
  922. "})(window.history)\n", HistoryShimName
  923. ];
  924. WKUserScript *script = [[WKUserScript alloc] initWithSource:html5HistoryAPIShimSource injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
  925. [_webView.configuration.userContentController addUserScript:script];
  926. if(_sharedCookiesEnabled) {
  927. // More info to sending cookies with WKWebView
  928. // https://stackoverflow.com/questions/26573137/can-i-set-the-cookies-to-be-used-by-a-wkwebview/26577303#26577303
  929. if (@available(iOS 11.0, *)) {
  930. // Set Cookies in iOS 11 and above, initialize websiteDataStore before setting cookies
  931. // See also https://forums.developer.apple.com/thread/97194
  932. // check if websiteDataStore has not been initialized before
  933. if(!_incognito && !_cacheEnabled) {
  934. _webView.configuration.websiteDataStore = [WKWebsiteDataStore nonPersistentDataStore];
  935. }
  936. for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
  937. [_webView.configuration.websiteDataStore.httpCookieStore setCookie:cookie completionHandler:nil];
  938. }
  939. } else {
  940. NSMutableString *script = [NSMutableString string];
  941. // Clear all existing cookies in a direct called function. This ensures that no
  942. // javascript error will break the web content javascript.
  943. // We keep this code here, if someone requires that Cookies are also removed within the
  944. // the WebView and want to extends the current sharedCookiesEnabled option with an
  945. // additional property.
  946. // Generates JS: document.cookie = "key=; Expires=Thu, 01 Jan 1970 00:00:01 GMT;"
  947. // for each cookie which is already available in the WebView context.
  948. /*
  949. [script appendString:@"(function () {\n"];
  950. [script appendString:@" var cookies = document.cookie.split('; ');\n"];
  951. [script appendString:@" for (var i = 0; i < cookies.length; i++) {\n"];
  952. [script appendString:@" if (cookies[i].indexOf('=') !== -1) {\n"];
  953. [script appendString:@" document.cookie = cookies[i].split('=')[0] + '=; Expires=Thu, 01 Jan 1970 00:00:01 GMT';\n"];
  954. [script appendString:@" }\n"];
  955. [script appendString:@" }\n"];
  956. [script appendString:@"})();\n\n"];
  957. */
  958. // Set cookies in a direct called function. This ensures that no
  959. // javascript error will break the web content javascript.
  960. // Generates JS: document.cookie = "key=value; Path=/; Expires=Thu, 01 Jan 20xx 00:00:01 GMT;"
  961. // for each cookie which is available in the application context.
  962. [script appendString:@"(function () {\n"];
  963. for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
  964. [script appendFormat:@"document.cookie = %@ + '=' + %@",
  965. RCTJSONStringify(cookie.name, NULL),
  966. RCTJSONStringify(cookie.value, NULL)];
  967. if (cookie.path) {
  968. [script appendFormat:@" + '; Path=' + %@", RCTJSONStringify(cookie.path, NULL)];
  969. }
  970. if (cookie.expiresDate) {
  971. [script appendFormat:@" + '; Expires=' + new Date(%f).toUTCString()",
  972. cookie.expiresDate.timeIntervalSince1970 * 1000
  973. ];
  974. }
  975. [script appendString:@";\n"];
  976. }
  977. [script appendString:@"})();\n"];
  978. WKUserScript* cookieInScript = [[WKUserScript alloc] initWithSource:script
  979. injectionTime:WKUserScriptInjectionTimeAtDocumentStart
  980. forMainFrameOnly:YES];
  981. [_webView.configuration.userContentController addUserScript:cookieInScript];
  982. }
  983. }
  984. if(_messagingEnabled){
  985. if (self.postMessageScript){
  986. [_webView.configuration.userContentController addScriptMessageHandler:[[RNCWeakScriptMessageDelegate alloc] initWithDelegate:self]
  987. name:MessageHandlerName];
  988. [_webView.configuration.userContentController addUserScript:self.postMessageScript];
  989. }
  990. if (self.atStartScript) {
  991. [_webView.configuration.userContentController addUserScript:self.atStartScript];
  992. }
  993. if (self.atEndScript) {
  994. [_webView.configuration.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