/
WebView.android.tsx
334 lines (306 loc) · 10.5 KB
/
WebView.android.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import React, {
forwardRef,
ReactElement,
useCallback,
useEffect,
useImperativeHandle,
useRef,
} from 'react';
import { Image, View, ImageSourcePropType, HostComponent } from 'react-native';
import BatchedBridge from 'react-native/Libraries/BatchedBridge/BatchedBridge';
import EventEmitter from 'react-native/Libraries/vendor/emitter/EventEmitter';
import invariant from 'invariant';
import RNCWebView, { Commands, NativeProps } from './RNCWebViewNativeComponent';
import RNCWebViewModule from './NativeRNCWebView';
import {
defaultOriginWhitelist,
defaultRenderError,
defaultRenderLoading,
useWebViewLogic,
} from './WebViewShared';
import {
AndroidWebViewProps,
WebViewSourceUri,
type WebViewMessageEvent,
type ShouldStartLoadRequestEvent,
} from './WebViewTypes';
import styles from './WebView.styles';
const { resolveAssetSource } = Image;
const directEventEmitter = new EventEmitter();
const registerCallableModule: (name: string, module: Object) => void =
// `registerCallableModule()` is available in React Native 0.74 and above.
// Fallback to use `BatchedBridge.registerCallableModule()` for older versions.
require('react-native').registerCallableModule ??
BatchedBridge.registerCallableModule.bind(BatchedBridge);
registerCallableModule('RNCWebViewMessagingModule', {
onShouldStartLoadWithRequest: (
event: ShouldStartLoadRequestEvent & { messagingModuleName?: string }
) => {
directEventEmitter.emit('onShouldStartLoadWithRequest', event);
},
onMessage: (
event: WebViewMessageEvent & { messagingModuleName?: string }
) => {
directEventEmitter.emit('onMessage', event);
},
});
/**
* A simple counter to uniquely identify WebView instances. Do not use this for anything else.
*/
let uniqueRef = 0;
const WebViewComponent = forwardRef<{}, AndroidWebViewProps>(
(
{
overScrollMode = 'always',
javaScriptEnabled = true,
thirdPartyCookiesEnabled = true,
scalesPageToFit = true,
allowsFullscreenVideo = false,
allowFileAccess = false,
saveFormDataDisabled = false,
cacheEnabled = true,
androidLayerType = 'none',
originWhitelist = defaultOriginWhitelist,
setSupportMultipleWindows = true,
setBuiltInZoomControls = true,
setDisplayZoomControls = false,
nestedScrollEnabled = false,
startInLoadingState,
onNavigationStateChange,
onLoadStart,
onError,
onLoad,
onLoadEnd,
onLoadProgress,
onHttpError: onHttpErrorProp,
onRenderProcessGone: onRenderProcessGoneProp,
onMessage: onMessageProp,
onOpenWindow: onOpenWindowProp,
renderLoading,
renderError,
style,
containerStyle,
source,
nativeConfig,
onShouldStartLoadWithRequest: onShouldStartLoadWithRequestProp,
injectedJavaScriptObject,
...otherProps
},
ref
) => {
const messagingModuleName = useRef<string>(
`WebViewMessageHandler${(uniqueRef += 1)}`
).current;
const webViewRef = useRef<React.ComponentRef<
HostComponent<NativeProps>
> | null>(null);
const onShouldStartLoadWithRequestCallback = useCallback(
(shouldStart: boolean, url: string, lockIdentifier?: number) => {
if (lockIdentifier) {
RNCWebViewModule.shouldStartLoadWithLockIdentifier(
shouldStart,
lockIdentifier
);
} else if (shouldStart && webViewRef.current) {
Commands.loadUrl(webViewRef.current, url);
}
},
[]
);
const {
onLoadingStart,
onShouldStartLoadWithRequest,
onMessage,
viewState,
setViewState,
lastErrorEvent,
onHttpError,
onLoadingError,
onLoadingFinish,
onLoadingProgress,
onOpenWindow,
onRenderProcessGone,
} = useWebViewLogic({
onNavigationStateChange,
onLoad,
onError,
onHttpErrorProp,
onLoadEnd,
onLoadProgress,
onLoadStart,
onRenderProcessGoneProp,
onMessageProp,
onOpenWindowProp,
startInLoadingState,
originWhitelist,
onShouldStartLoadWithRequestProp,
onShouldStartLoadWithRequestCallback,
});
useImperativeHandle(
ref,
() => ({
goForward: () =>
webViewRef.current && Commands.goForward(webViewRef.current),
goBack: () => webViewRef.current && Commands.goBack(webViewRef.current),
reload: () => {
setViewState('LOADING');
if (webViewRef.current) {
Commands.reload(webViewRef.current);
}
},
stopLoading: () =>
webViewRef.current && Commands.stopLoading(webViewRef.current),
postMessage: (data: string) =>
webViewRef.current && Commands.postMessage(webViewRef.current, data),
injectJavaScript: (data: string) =>
webViewRef.current &&
Commands.injectJavaScript(webViewRef.current, data),
requestFocus: () =>
webViewRef.current && Commands.requestFocus(webViewRef.current),
clearFormData: () =>
webViewRef.current && Commands.clearFormData(webViewRef.current),
clearCache: (includeDiskFiles: boolean) =>
webViewRef.current &&
Commands.clearCache(webViewRef.current, includeDiskFiles),
clearHistory: () =>
webViewRef.current && Commands.clearHistory(webViewRef.current),
}),
[setViewState, webViewRef]
);
useEffect(() => {
const onShouldStartLoadWithRequestSubscription =
directEventEmitter.addListener(
'onShouldStartLoadWithRequest',
(
event: ShouldStartLoadRequestEvent & {
messagingModuleName?: string;
}
) => {
if (event.messagingModuleName === messagingModuleName) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { messagingModuleName: _, ...rest } = event;
onShouldStartLoadWithRequest(rest);
}
}
);
const onMessageSubscription = directEventEmitter.addListener(
'onMessage',
(event: WebViewMessageEvent & { messagingModuleName?: string }) => {
if (event.messagingModuleName === messagingModuleName) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { messagingModuleName: _, ...rest } = event;
onMessage(rest);
}
}
);
return () => {
onShouldStartLoadWithRequestSubscription.remove();
onMessageSubscription.remove();
};
}, [messagingModuleName, onMessage, onShouldStartLoadWithRequest]);
let otherView: ReactElement | undefined;
if (viewState === 'LOADING') {
otherView = (renderLoading || defaultRenderLoading)();
} else if (viewState === 'ERROR') {
invariant(
lastErrorEvent != null,
'lastErrorEvent expected to be non-null'
);
if (lastErrorEvent) {
otherView = (renderError || defaultRenderError)(
lastErrorEvent.domain,
lastErrorEvent.code,
lastErrorEvent.description
);
}
} else if (viewState !== 'IDLE') {
console.error(`RNCWebView invalid state encountered: ${viewState}`);
}
const webViewStyles = [styles.container, styles.webView, style];
const webViewContainerStyle = [styles.container, containerStyle];
if (typeof source !== 'number' && source && 'method' in source) {
if (source.method === 'POST' && source.headers) {
console.warn(
'WebView: `source.headers` is not supported when using POST.'
);
} else if (source.method === 'GET' && source.body) {
console.warn('WebView: `source.body` is not supported when using GET.');
}
}
const NativeWebView =
(nativeConfig?.component as typeof RNCWebView | undefined) || RNCWebView;
const sourceResolved = resolveAssetSource(source as ImageSourcePropType);
const newSource =
typeof sourceResolved === 'object'
? Object.entries(sourceResolved as WebViewSourceUri).reduce(
(prev, [currKey, currValue]) => {
return {
...prev,
[currKey]:
currKey === 'headers' &&
currValue &&
typeof currValue === 'object'
? Object.entries(currValue).map(([key, value]) => {
return {
name: key,
value,
};
})
: currValue,
};
},
{}
)
: sourceResolved;
const webView = (
<NativeWebView
key="webViewKey"
{...otherProps}
messagingEnabled={typeof onMessageProp === 'function'}
messagingModuleName={messagingModuleName}
hasOnScroll={!!otherProps.onScroll}
onLoadingError={onLoadingError}
onLoadingFinish={onLoadingFinish}
onLoadingProgress={onLoadingProgress}
onLoadingStart={onLoadingStart}
onHttpError={onHttpError}
onRenderProcessGone={onRenderProcessGone}
onMessage={onMessage}
onOpenWindow={onOpenWindow}
hasOnOpenWindowEvent={onOpenWindowProp !== undefined}
onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
ref={webViewRef}
// TODO: find a better way to type this.
// @ts-expect-error source is old arch
source={sourceResolved}
newSource={newSource}
style={webViewStyles}
overScrollMode={overScrollMode}
javaScriptEnabled={javaScriptEnabled}
thirdPartyCookiesEnabled={thirdPartyCookiesEnabled}
scalesPageToFit={scalesPageToFit}
allowsFullscreenVideo={allowsFullscreenVideo}
allowFileAccess={allowFileAccess}
saveFormDataDisabled={saveFormDataDisabled}
cacheEnabled={cacheEnabled}
androidLayerType={androidLayerType}
setSupportMultipleWindows={setSupportMultipleWindows}
setBuiltInZoomControls={setBuiltInZoomControls}
setDisplayZoomControls={setDisplayZoomControls}
nestedScrollEnabled={nestedScrollEnabled}
injectedJavaScriptObject={JSON.stringify(injectedJavaScriptObject)}
{...nativeConfig?.props}
/>
);
return (
<View style={webViewContainerStyle}>
{webView}
{otherView}
</View>
);
}
);
// native implementation should return "true" only for Android 5+
const { isFileUploadSupported } = RNCWebViewModule;
const WebView = Object.assign(WebViewComponent, { isFileUploadSupported });
export default WebView;