Browse Source

Merge branch 'master' into patch-1

eladgel 4 years ago
parent
commit
f59e4004f8
No account linked to committer's email address
7 changed files with 148 additions and 64 deletions
  1. 33
    38
      docs/Guide.md
  2. 37
    7
      docs/Reference.md
  3. 2
    0
      ios/RNCWebView.h
  4. 64
    16
      ios/RNCWebView.m
  5. 2
    0
      ios/RNCWebViewManager.m
  6. 1
    1
      package.json
  7. 9
    2
      src/WebViewTypes.ts

+ 33
- 38
docs/Guide.md View File

@@ -149,44 +149,6 @@ class MyWeb extends Component {
149 149
 }
150 150
 ```
151 151
 
152
-#### Intercepting hash URL changes
153
-
154
-While `onNavigationStateChange` will trigger on URL changes, it does not trigger when only the hash URL ("anchor") changes, e.g. from `https://example.com/users#list` to `https://example.com/users#help`.
155
-
156
-You can inject some JavaScript to wrap the history functions in order to intercept these hash URL changes.
157
-
158
-```jsx
159
-<WebView
160
-  source={{ uri: someURI }}
161
-  injectedJavaScript={`
162
-    (function() {
163
-      function wrap(fn) {
164
-        return function wrapper() {
165
-          var res = fn.apply(this, arguments);
166
-          window.ReactNativeWebView.postMessage('navigationStateChange');
167
-          return res;
168
-        }
169
-      }
170
-
171
-      history.pushState = wrap(history.pushState);
172
-      history.replaceState = wrap(history.replaceState);
173
-      window.addEventListener('popstate', function() {
174
-        window.ReactNativeWebView.postMessage('navigationStateChange');
175
-      });
176
-    })();
177
-
178
-    true;
179
-  `}
180
-  onMessage={({ nativeEvent: state }) => {
181
-    if (state.data === 'navigationStateChange') {
182
-      // Navigation state updated, can check state.canGoBack, etc.
183
-    }
184
-  }}
185
-/>
186
-```
187
-
188
-Thanks to [Janic Duplessis](https://github.com/react-native-community/react-native-webview/issues/24#issuecomment-483956651) for this workaround.
189
-
190 152
 ### Add support for File Upload
191 153
 
192 154
 ##### iOS
@@ -336,6 +298,39 @@ _Under the hood_
336 298
 > On iOS, `injectedJavaScript` runs a method on WebView called `evaluateJavaScript:completionHandler:`
337 299
 > On Android, `injectedJavaScript` runs a method on the Android WebView called `evaluateJavascriptWithFallback`
338 300
 
301
+
302
+#### The `injectedJavaScriptBeforeContentLoaded` prop
303
+
304
+This is a script that runs **before** the web page loads for the first time. It only runs once, even if the page is reloaded or navigated away. This is useful if you want to inject anything into the window, localstorage, or document prior to the web code executing. 
305
+
306
+```jsx
307
+import React, { Component } from 'react';
308
+import { View } from 'react-native';
309
+import { WebView } from 'react-native-webview';
310
+
311
+export default class App extends Component {
312
+  render() {
313
+    const runFirst = `
314
+      window.isNativeApp = true;
315
+      true; // note: this is required, or you'll sometimes get silent failures
316
+    `;
317
+    return (
318
+      <View style={{ flex: 1 }}>
319
+        <WebView
320
+          source={{
321
+            uri:
322
+              'https://github.com/react-native-community/react-native-webview',
323
+          }}
324
+          injectedJavaScriptBeforeContentLoaded={runFirst}
325
+        />
326
+      </View>
327
+    );
328
+  }
329
+}
330
+```
331
+
332
+This runs the JavaScript in the `runFirst` string before the page is loaded. In this case, the value of `window.isNativeApp` will be set to true before the web code executes. 
333
+
339 334
 #### The `injectJavaScript` method
340 335
 
341 336
 While convenient, the downside to the previously mentioned `injectedJavaScript` prop is that it only runs once. That's why we also expose a method on the webview ref called `injectJavaScript` (note the slightly different name!).

+ 37
- 7
docs/Reference.md View File

@@ -7,6 +7,7 @@ This document lays out the current public properties and methods for the React N
7 7
 - [`source`](Reference.md#source)
8 8
 - [`automaticallyAdjustContentInsets`](Reference.md#automaticallyadjustcontentinsets)
9 9
 - [`injectedJavaScript`](Reference.md#injectedjavascript)
10
+- [`injectedJavaScriptBeforeContentLoaded`](Reference.md#injectedJavaScriptBeforeContentLoaded)
10 11
 - [`mediaPlaybackRequiresUserAction`](Reference.md#mediaplaybackrequiresuseraction)
11 12
 - [`nativeConfig`](Reference.md#nativeconfig)
12 13
 - [`onError`](Reference.md#onerror)
@@ -144,6 +145,35 @@ const INJECTED_JAVASCRIPT = `(function() {
144 145
 
145 146
 ---
146 147
 
148
+### `injectedJavaScriptBeforeContentLoaded`
149
+
150
+Set this to provide JavaScript that will be injected into the web page after the document element is created, but before any other content is loaded. Make sure the string evaluates to a valid type (`true` works) and doesn't otherwise throw an exception.
151
+On iOS, see [WKUserScriptInjectionTimeAtDocumentStart](https://developer.apple.com/documentation/webkit/wkuserscriptinjectiontime/wkuserscriptinjectiontimeatdocumentstart?language=objc)
152
+
153
+| Type   | Required |
154
+| ------ | -------- |
155
+| string | No       |
156
+
157
+To learn more, read the [Communicating between JS and Native](Guide.md#communicating-between-js-and-native) guide.
158
+
159
+Example:
160
+
161
+Post message a JSON object of `window.location` to be handled by [`onMessage`](Reference.md#onmessage)
162
+
163
+```jsx
164
+const INJECTED_JAVASCRIPT = `(function() {
165
+    window.ReactNativeWebView.postMessage(JSON.stringify(window.location));
166
+})();`;
167
+
168
+<WebView
169
+  source={{ uri: 'https://facebook.github.io/react-native' }}
170
+  injectedJavaScriptBeforeContentLoaded={INJECTED_JAVASCRIPT}
171
+  onMessage={this.onMessage}
172
+/>;
173
+```
174
+
175
+---
176
+
147 177
 ### `mediaPlaybackRequiresUserAction`
148 178
 
149 179
 Boolean that determines whether HTML5 audio and video requires the user to tap them before they start playing. The default value is `true`. (Android API minimum version 17).
@@ -656,11 +686,11 @@ Boolean value to control whether DOM Storage is enabled. Used only in Android.
656 686
 
657 687
 ### `javaScriptEnabled`
658 688
 
659
-Boolean value to enable JavaScript in the `WebView`. Used on Android only as JavaScript is enabled by default on iOS. The default value is `true`.
689
+Boolean value to enable JavaScript in the `WebView`. The default value is `true`.
660 690
 
661
-| Type | Required | Platform |
662
-| ---- | -------- | -------- |
663
-| bool | No       | Android  |
691
+| Type | Required |
692
+| ---- | -------- |
693
+| bool | No       |
664 694
 
665 695
 ---
666 696
 
@@ -884,9 +914,9 @@ Set whether Geolocation is enabled in the `WebView`. The default value is `false
884 914
 
885 915
 Boolean that sets whether JavaScript running in the context of a file scheme URL should be allowed to access content from other file scheme URLs. The default value is `false`.
886 916
 
887
-| Type | Required | Platform |
888
-| ---- | -------- | -------- |
889
-| bool | No       | Android  |
917
+| Type | Required |
918
+| ---- | -------- |
919
+| bool | No       |
890 920
 
891 921
 ---
892 922
 

+ 2
- 0
ios/RNCWebView.h View File

@@ -25,6 +25,7 @@
25 25
 @property (nonatomic, copy) NSDictionary * _Nullable source;
26 26
 @property (nonatomic, assign) BOOL messagingEnabled;
27 27
 @property (nonatomic, copy) NSString * _Nullable injectedJavaScript;
28
+@property (nonatomic, copy) NSString * _Nullable injectedJavaScriptBeforeContentLoaded;
28 29
 @property (nonatomic, assign) BOOL scrollEnabled;
29 30
 @property (nonatomic, assign) BOOL sharedCookiesEnabled;
30 31
 @property (nonatomic, assign) BOOL pagingEnabled;
@@ -46,6 +47,7 @@
46 47
 @property (nonatomic, copy) NSString * _Nullable applicationNameForUserAgent;
47 48
 @property (nonatomic, assign) BOOL cacheEnabled;
48 49
 @property (nonatomic, assign) BOOL javaScriptEnabled;
50
+@property (nonatomic, assign) BOOL allowFileAccessFromFileURLs;
49 51
 @property (nonatomic, assign) BOOL allowsLinkPreview;
50 52
 @property (nonatomic, assign) BOOL showsHorizontalScrollIndicator;
51 53
 @property (nonatomic, assign) BOOL showsVerticalScrollIndicator;

+ 64
- 16
ios/RNCWebView.m View File

@@ -14,6 +14,7 @@
14 14
 #import "objc/runtime.h"
15 15
 
16 16
 static NSTimer *keyboardTimer;
17
+static NSString *const HistoryShimName = @"ReactNativeHistoryShim";
17 18
 static NSString *const MessageHandlerName = @"ReactNativeWebView";
18 19
 static NSURLCredential* clientAuthenticationCredential;
19 20
 static NSDictionary* customCertificatesForHost;
@@ -138,8 +139,16 @@ static NSDictionary* customCertificatesForHost;
138 139
   if (self.window != nil && _webView == nil) {
139 140
     WKWebViewConfiguration *wkWebViewConfig = [WKWebViewConfiguration new];
140 141
     WKPreferences *prefs = [[WKPreferences alloc]init];
142
+    BOOL _prefsUsed = NO;
141 143
     if (!_javaScriptEnabled) {
142 144
       prefs.javaScriptEnabled = NO;
145
+      _prefsUsed = YES;
146
+    }
147
+    if (_allowFileAccessFromFileURLs) {
148
+      [prefs setValue:@TRUE forKey:@"allowFileAccessFromFileURLs"];
149
+      _prefsUsed = YES;
150
+    }
151
+    if (_prefsUsed) {
143 152
       wkWebViewConfig.preferences = prefs;
144 153
     }
145 154
     if (_incognito) {
@@ -152,6 +161,31 @@ static NSDictionary* customCertificatesForHost;
152 161
     }
153 162
     wkWebViewConfig.userContentController = [WKUserContentController new];
154 163
 
164
+    // Shim the HTML5 history API:
165
+    [wkWebViewConfig.userContentController addScriptMessageHandler:self name:HistoryShimName];
166
+    NSString *source = [NSString stringWithFormat:
167
+      @"(function(history) {\n"
168
+      "  function notify(type) {\n"
169
+      "    setTimeout(function() {\n"
170
+      "      window.webkit.messageHandlers.%@.postMessage(type)\n"
171
+      "    }, 0)\n"
172
+      "  }\n"
173
+      "  function shim(f) {\n"
174
+      "    return function pushState() {\n"
175
+      "      notify('other')\n"
176
+      "      return f.apply(history, arguments)\n"
177
+      "    }\n"
178
+      "  }\n"
179
+      "  history.pushState = shim(history.pushState)\n"
180
+      "  history.replaceState = shim(history.replaceState)\n"
181
+      "  window.addEventListener('popstate', function() {\n"
182
+      "    notify('backforward')\n"
183
+      "  })\n"
184
+      "})(window.history)\n", HistoryShimName
185
+    ];
186
+    WKUserScript *script = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
187
+    [wkWebViewConfig.userContentController addUserScript:script];
188
+
155 189
     if (_messagingEnabled) {
156 190
       [wkWebViewConfig.userContentController addScriptMessageHandler:self name:MessageHandlerName];
157 191
 
@@ -165,6 +199,12 @@ static NSDictionary* customCertificatesForHost;
165 199
 
166 200
       WKUserScript *script = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
167 201
       [wkWebViewConfig.userContentController addUserScript:script];
202
+        
203
+      if (_injectedJavaScriptBeforeContentLoaded) {
204
+        // If user has provided an injectedJavascript prop, execute it at the start of the document
205
+        WKUserScript *injectedScript = [[WKUserScript alloc] initWithSource:_injectedJavaScriptBeforeContentLoaded injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
206
+        [wkWebViewConfig.userContentController addUserScript:injectedScript];
207
+      }
168 208
     }
169 209
 
170 210
     wkWebViewConfig.allowsInlineMediaPlayback = _allowsInlineMediaPlayback;
@@ -390,10 +430,18 @@ static NSDictionary* customCertificatesForHost;
390 430
 - (void)userContentController:(WKUserContentController *)userContentController
391 431
        didReceiveScriptMessage:(WKScriptMessage *)message
392 432
 {
393
-  if (_onMessage != nil) {
394
-    NSMutableDictionary<NSString *, id> *event = [self baseEvent];
395
-    [event addEntriesFromDictionary: @{@"data": message.body}];
396
-    _onMessage(event);
433
+  if ([message.name isEqualToString:HistoryShimName]) {
434
+    if (_onLoadingFinish) {
435
+      NSMutableDictionary<NSString *, id> *event = [self baseEvent];
436
+      [event addEntriesFromDictionary: @{@"navigationType": message.body}];
437
+      _onLoadingFinish(event);
438
+    }
439
+  } else if ([message.name isEqualToString:MessageHandlerName]) {
440
+    if (_onMessage) {
441
+      NSMutableDictionary<NSString *, id> *event = [self baseEvent];
442
+      [event addEntriesFromDictionary: @{@"data": message.body}];
443
+      _onMessage(event);
444
+    }
397 445
   }
398 446
 }
399 447
 
@@ -922,7 +970,7 @@ static NSDictionary* customCertificatesForHost;
922 970
       return;
923 971
     }
924 972
 
925
-    if ([error.domain isEqualToString:@"WebKitErrorDomain"] && error.code == 102) {
973
+    if ([error.domain isEqualToString:@"WebKitErrorDomain"] && error.code == 102 || [error.domain isEqualToString:@"WebKitErrorDomain"] && error.code == 101) {
926 974
       // Error code 102 "Frame load interrupted" is raised by the WKWebView
927 975
       // when the URL is from an http redirect. This is a common pattern when
928 976
       // implementing OAuth with a WebView.
@@ -957,19 +1005,19 @@ static NSDictionary* customCertificatesForHost;
957 1005
  * Called when the navigation is complete.
958 1006
  * @see https://fburl.com/rtys6jlb
959 1007
  */
960
-- (void)      webView:(WKWebView *)webView
1008
+- (void)webView:(WKWebView *)webView
961 1009
   didFinishNavigation:(WKNavigation *)navigation
962 1010
 {
963
-  if (_injectedJavaScript) {
964
-    [self evaluateJS: _injectedJavaScript thenCall: ^(NSString *jsEvaluationValue) {
965
-      NSMutableDictionary *event = [self baseEvent];
966
-      event[@"jsEvaluationValue"] = jsEvaluationValue;
967
-
968
-      if (self.onLoadingFinish) {
969
-        self.onLoadingFinish(event);
970
-      }
971
-    }];
972
-  } else if (_onLoadingFinish) {
1011
+   if (_injectedJavaScript) {
1012
+     [self evaluateJS: _injectedJavaScript thenCall: ^(NSString *jsEvaluationValue) {
1013
+       NSMutableDictionary *event = [self baseEvent];
1014
+       event[@"jsEvaluationValue"] = jsEvaluationValue;
1015
+
1016
+       if (self.onLoadingFinish) {
1017
+         self.onLoadingFinish(event);
1018
+       }
1019
+     }];
1020
+   } else if (_onLoadingFinish) {
973 1021
     _onLoadingFinish([self baseEvent]);
974 1022
   }
975 1023
 }

+ 2
- 0
ios/RNCWebViewManager.m View File

@@ -51,7 +51,9 @@ RCT_EXPORT_VIEW_PROPERTY(onHttpError, RCTDirectEventBlock)
51 51
 RCT_EXPORT_VIEW_PROPERTY(onShouldStartLoadWithRequest, RCTDirectEventBlock)
52 52
 RCT_EXPORT_VIEW_PROPERTY(onContentProcessDidTerminate, RCTDirectEventBlock)
53 53
 RCT_EXPORT_VIEW_PROPERTY(injectedJavaScript, NSString)
54
+RCT_EXPORT_VIEW_PROPERTY(injectedJavaScriptBeforeContentLoaded, NSString)
54 55
 RCT_EXPORT_VIEW_PROPERTY(javaScriptEnabled, BOOL)
56
+RCT_EXPORT_VIEW_PROPERTY(allowFileAccessFromFileURLs, BOOL)
55 57
 RCT_EXPORT_VIEW_PROPERTY(allowsInlineMediaPlayback, BOOL)
56 58
 RCT_EXPORT_VIEW_PROPERTY(mediaPlaybackRequiresUserAction, BOOL)
57 59
 #if WEBKIT_IOS_10_APIS_AVAILABLE

+ 1
- 1
package.json View File

@@ -8,7 +8,7 @@
8 8
     "Thibault Malbranche <malbranche.thibault@gmail.com>"
9 9
   ],
10 10
   "license": "MIT",
11
-  "version": "7.5.2",
11
+  "version": "8.0.1",
12 12
   "homepage": "https://github.com/react-native-community/react-native-webview#readme",
13 13
   "scripts": {
14 14
     "ci": "CI=true && yarn lint && yarn test",

+ 9
- 2
src/WebViewTypes.ts View File

@@ -20,7 +20,7 @@ type AndroidWebViewCommands = 'clearHistory' | 'clearCache' | 'clearFormData';
20 20
 
21 21
 interface RNCWebViewUIManager<Commands extends string> extends UIManagerStatic {
22 22
   getViewManagerConfig: (
23
-      name: string,
23
+    name: string,
24 24
   ) => {
25 25
     Commands: {[key in Commands]: number};
26 26
   };
@@ -216,6 +216,7 @@ export interface CommonNativeWebViewProps extends ViewProps {
216 216
   cacheEnabled?: boolean;
217 217
   incognito?: boolean;
218 218
   injectedJavaScript?: string;
219
+  injectedJavaScriptBeforeContentLoaded?: string;
219 220
   mediaPlaybackRequiresUserAction?: boolean;
220 221
   messagingEnabled: boolean;
221 222
   onScroll?: (event: NativeScrollEvent) => void;
@@ -501,7 +502,7 @@ export interface AndroidWebViewProps extends WebViewSharedProps {
501 502
    */
502 503
   geolocationEnabled?: boolean;
503 504
 
504
-
505
+  
505 506
   /**
506 507
    * Boolean that sets whether JavaScript running in the context of a file
507 508
    * scheme URL should be allowed to access content from other file scheme URLs.
@@ -685,6 +686,12 @@ export interface WebViewSharedProps extends ViewProps {
685 686
    */
686 687
   injectedJavaScript?: string;
687 688
 
689
+  /**
690
+   * Set this to provide JavaScript that will be injected into the web page
691
+   * once the webview is initialized but before the view loads any content.
692
+   */
693
+  injectedJavaScriptBeforeContentLoaded?: string;
694
+
688 695
   /**
689 696
    * Boolean value that determines whether a horizontal scroll indicator is
690 697
    * shown in the `WebView`. The default value is `true`.