react-native-minimal-webview 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +130 -2
- package/android/build.gradle +26 -0
- package/android/consumer-rules.pro +4 -0
- package/android/src/main/AndroidManifest.xml +2 -0
- package/android/src/main/java/expo/modules/minimalwebview/Asks.kt +44 -0
- package/android/src/main/java/expo/modules/minimalwebview/DocumentEnd.kt +31 -0
- package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +496 -0
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +510 -0
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +359 -0
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +245 -0
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +199 -0
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +191 -0
- package/android/src/main/java/expo/modules/minimalwebview/NavigationRules.kt +113 -0
- package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +306 -0
- package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +76 -0
- package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +258 -0
- package/android/src/main/java/expo/modules/minimalwebview/requests/FileUpload.kt +44 -0
- package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +87 -0
- package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +77 -0
- package/build/WebView.d.ts +99 -0
- package/build/WebView.d.ts.map +1 -0
- package/build/WebView.js +448 -0
- package/build/WebView.js.map +1 -0
- package/build/bridge/createBridge.d.ts +32 -0
- package/build/bridge/createBridge.d.ts.map +1 -0
- package/build/bridge/createBridge.js +135 -0
- package/build/bridge/createBridge.js.map +1 -0
- package/build/bridge/endpoint.d.ts +35 -0
- package/build/bridge/endpoint.d.ts.map +1 -0
- package/build/bridge/endpoint.js +100 -0
- package/build/bridge/endpoint.js.map +1 -0
- package/build/bridge/origins.d.ts +25 -0
- package/build/bridge/origins.d.ts.map +1 -0
- package/build/bridge/origins.js +60 -0
- package/build/bridge/origins.js.map +1 -0
- package/build/bridge/pageClient.generated.d.ts +3 -0
- package/build/bridge/pageClient.generated.d.ts.map +1 -0
- package/build/bridge/pageClient.generated.js +4 -0
- package/build/bridge/pageClient.generated.js.map +1 -0
- package/build/bridge/protocol.d.ts +50 -0
- package/build/bridge/protocol.d.ts.map +1 -0
- package/build/bridge/protocol.js +52 -0
- package/build/bridge/protocol.js.map +1 -0
- package/build/defaultNavigationRules.d.ts +16 -0
- package/build/defaultNavigationRules.d.ts.map +1 -0
- package/build/defaultNavigationRules.js +23 -0
- package/build/defaultNavigationRules.js.map +1 -0
- package/build/index.d.ts +31 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +30 -0
- package/build/index.js.map +1 -0
- package/build/platform.generated.d.ts +702 -0
- package/build/platform.generated.d.ts.map +1 -0
- package/build/platform.generated.js +199 -0
- package/build/platform.generated.js.map +1 -0
- package/build/reactNativeWebViewDefaults.d.ts +21 -0
- package/build/reactNativeWebViewDefaults.d.ts.map +1 -0
- package/build/reactNativeWebViewDefaults.js +12 -0
- package/build/reactNativeWebViewDefaults.js.map +1 -0
- package/build/reactNativeWebViewMessages.d.ts +22 -0
- package/build/reactNativeWebViewMessages.d.ts.map +1 -0
- package/build/reactNativeWebViewMessages.js +30 -0
- package/build/reactNativeWebViewMessages.js.map +1 -0
- package/build/refStore.d.ts +31 -0
- package/build/refStore.d.ts.map +1 -0
- package/build/refStore.js +113 -0
- package/build/refStore.js.map +1 -0
- package/build/types.d.ts +1127 -0
- package/build/types.d.ts.map +1 -0
- package/build/types.defaults.d.ts +8 -0
- package/build/types.defaults.d.ts.map +1 -0
- package/build/types.defaults.js +17 -0
- package/build/types.defaults.js.map +1 -0
- package/build/types.js +2 -0
- package/build/types.js.map +1 -0
- package/expo-module.config.json +9 -0
- package/ios/Asks.swift +45 -0
- package/ios/DelegateProxy.swift +162 -0
- package/ios/DocumentEnd.swift +23 -0
- package/ios/DownloadName.swift +12 -0
- package/ios/Downloads.swift +51 -0
- package/ios/Hooks.swift +308 -0
- package/ios/Loads.swift +44 -0
- package/ios/MRWExceptions.h +9 -0
- package/ios/MRWExceptions.m +10 -0
- package/ios/MRWInvoke.h +23 -0
- package/ios/MRWInvoke.m +187 -0
- package/ios/MinimalWebView+Dialogs.swift +99 -0
- package/ios/MinimalWebView+Navigation.swift +244 -0
- package/ios/MinimalWebView+Scripts.swift +92 -0
- package/ios/MinimalWebView.docc/MinimalWebView.md +13 -0
- package/ios/MinimalWebView.podspec +32 -0
- package/ios/MinimalWebView.swift +512 -0
- package/ios/MinimalWebViewModule.swift +110 -0
- package/ios/NavigationRules.swift +123 -0
- package/ios/OriginRules.swift +35 -0
- package/ios/PlatformCompletions.generated.swift +39 -0
- package/ios/PlatformSettings.swift +247 -0
- package/ios/ReadAccess.swift +19 -0
- package/ios/Recovery.swift +25 -0
- package/ios/SharedCookies.swift +59 -0
- package/package.json +94 -4
- package/src/WebView.tsx +623 -0
- package/src/bridge/createBridge.ts +176 -0
- package/src/bridge/endpoint.ts +119 -0
- package/src/bridge/origins.ts +62 -0
- package/src/bridge/pageClient.generated.ts +5 -0
- package/src/bridge/pageClient.ts +68 -0
- package/src/bridge/protocol.ts +78 -0
- package/src/defaultNavigationRules.ts +25 -0
- package/src/index.ts +37 -0
- package/src/platform.generated.ts +694 -0
- package/src/reactNativeWebViewDefaults.ts +13 -0
- package/src/reactNativeWebViewMessages.ts +32 -0
- package/src/refStore.ts +164 -0
- package/src/types.defaults.ts +24 -0
- package/src/types.ts +1194 -0
package/src/WebView.tsx
ADDED
|
@@ -0,0 +1,623 @@
|
|
|
1
|
+
import { requireNativeModule, requireNativeView } from 'expo';
|
|
2
|
+
import { type Ref, useEffect, useMemo, useRef, useState } from 'react';
|
|
3
|
+
import { AppState, Platform, type ViewProps } from 'react-native';
|
|
4
|
+
|
|
5
|
+
import { CONNECTION, originGuard } from './bridge/createBridge';
|
|
6
|
+
import { codedError } from './bridge/endpoint';
|
|
7
|
+
import { defaultNavigationRules } from './defaultNavigationRules';
|
|
8
|
+
import { REACT_NATIVE_WEBVIEW_DEFAULTS } from './reactNativeWebViewDefaults';
|
|
9
|
+
import { useAttach } from './refStore';
|
|
10
|
+
import type {
|
|
11
|
+
HookExtension,
|
|
12
|
+
InjectedScript,
|
|
13
|
+
LoadErrorEvent,
|
|
14
|
+
NavigationEvent,
|
|
15
|
+
NavigationRule,
|
|
16
|
+
NavigationState,
|
|
17
|
+
ProcessGoneEvent,
|
|
18
|
+
SettingValue,
|
|
19
|
+
WebViewProps,
|
|
20
|
+
WebViewRef,
|
|
21
|
+
} from './types';
|
|
22
|
+
import { DEFAULTS } from './types.defaults';
|
|
23
|
+
|
|
24
|
+
type Native<T> = { nativeEvent: T };
|
|
25
|
+
/** The native view's event props, by name and payload. */
|
|
26
|
+
type NativeHandlers<E> = { [K in keyof E]: (event: Native<E[K]>) => void };
|
|
27
|
+
|
|
28
|
+
/** The event without the `target` (the view's tag) React Native adds to every native event. */
|
|
29
|
+
const own = <T,>({ target: _, ...event }: T & { target?: unknown }) => event as T;
|
|
30
|
+
|
|
31
|
+
/** A page's message comes with its origin, as native verified it (`location.origin` form). */
|
|
32
|
+
export type BridgeEvent =
|
|
33
|
+
{ message: string; origin: string } | { navigated: true } | { unavailable: true };
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* An event as native sends it: `key` is the hook's key, `core` for the core's own. `askId` is set when native waits for
|
|
37
|
+
* the answer.
|
|
38
|
+
*/
|
|
39
|
+
export type AskableEvent = {
|
|
40
|
+
key: string;
|
|
41
|
+
name: string;
|
|
42
|
+
payload: Record<string, unknown>;
|
|
43
|
+
askId?: number;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Page requests the core answers natively, by prop name, and `onNavigation`, for the decisions it reports. Native sends
|
|
48
|
+
* JS each only while its prop is set, and reads the set when it would send one, so a prop can come and go.
|
|
49
|
+
*/
|
|
50
|
+
const REQUESTS = [
|
|
51
|
+
'onNavigationRequest',
|
|
52
|
+
'onOpenExternal',
|
|
53
|
+
'onFileRequest',
|
|
54
|
+
'onFullscreenChange',
|
|
55
|
+
'onPermissionRequest',
|
|
56
|
+
'onDownload',
|
|
57
|
+
'onNavigation',
|
|
58
|
+
] as const;
|
|
59
|
+
|
|
60
|
+
/** Every prop that is not a `ViewProps` one, so it never reaches the outermost view. */
|
|
61
|
+
const OWN = [
|
|
62
|
+
'source',
|
|
63
|
+
'ios',
|
|
64
|
+
'android',
|
|
65
|
+
'userAgent',
|
|
66
|
+
'navigationRules',
|
|
67
|
+
'injectedScripts',
|
|
68
|
+
'bridge',
|
|
69
|
+
'pullToRefresh',
|
|
70
|
+
'sharedCookies',
|
|
71
|
+
'extensions',
|
|
72
|
+
'onNavigationStateChange',
|
|
73
|
+
'onError',
|
|
74
|
+
'onProcessGone',
|
|
75
|
+
'onLoadStart',
|
|
76
|
+
'onLoadEnd',
|
|
77
|
+
...REQUESTS,
|
|
78
|
+
'ref',
|
|
79
|
+
'children',
|
|
80
|
+
] as const satisfies (Exclude<keyof WebViewProps, keyof ViewProps> | 'children')[];
|
|
81
|
+
type Unlisted = Exclude<Exclude<keyof WebViewProps, keyof ViewProps>, (typeof OWN)[number]>;
|
|
82
|
+
// A prop missing from OWN fails to compile here, by name.
|
|
83
|
+
const OWN_SET: Set<string> &
|
|
84
|
+
([Unlisted] extends [never] ? unknown : Record<Unlisted, 'missing from OWN'>) = new Set(OWN);
|
|
85
|
+
|
|
86
|
+
type NativeSettings = Record<string, Record<string, SettingValue | undefined>>;
|
|
87
|
+
|
|
88
|
+
type NativeProps = ViewProps &
|
|
89
|
+
Pick<WebViewProps, 'source' | 'navigationRules' | 'pullToRefresh'> & {
|
|
90
|
+
/** With each script's `origins` in its code (`nativeScripts`). */
|
|
91
|
+
injectedScripts: Omit<InjectedScript, 'origins'>[] | undefined;
|
|
92
|
+
ref: Ref<NativeMethods>;
|
|
93
|
+
/** iOS only: Android's CookieManager is already shared. */
|
|
94
|
+
sharedCookies: boolean | undefined;
|
|
95
|
+
/**
|
|
96
|
+
* The platform's settings by root and name, as JSON: `ios` or `android` with the cross-platform props on top. A
|
|
97
|
+
* string, so that a `null` (reset this key) survives the trip; the native dictionary conversion drops it.
|
|
98
|
+
*/
|
|
99
|
+
settings: string;
|
|
100
|
+
bridgeScript: string | undefined;
|
|
101
|
+
bridgeOrigins: string[] | undefined;
|
|
102
|
+
hookOptions: Record<string, unknown> | undefined;
|
|
103
|
+
requestHandlers: string[];
|
|
104
|
+
} & NativeHandlers<{
|
|
105
|
+
onNavigation: NavigationEvent;
|
|
106
|
+
onNavigationState: NavigationState;
|
|
107
|
+
onBridge: BridgeEvent;
|
|
108
|
+
onHookEvent: AskableEvent;
|
|
109
|
+
onError: LoadErrorEvent;
|
|
110
|
+
onProcessGone: ProcessGoneEvent;
|
|
111
|
+
}>;
|
|
112
|
+
|
|
113
|
+
/** The native view's methods, on its ref. */
|
|
114
|
+
export type NativeMethods = {
|
|
115
|
+
goBack(): Promise<void>;
|
|
116
|
+
goForward(): Promise<void>;
|
|
117
|
+
reload(): Promise<void>;
|
|
118
|
+
stopLoading(): Promise<void>;
|
|
119
|
+
bridgePost(message: string): Promise<void>;
|
|
120
|
+
/** Answers a native `ask`. `json` is JSON, as for `call`. */
|
|
121
|
+
answer(askId: number, json: string): Promise<void>;
|
|
122
|
+
/** The JSON-encoded result. */
|
|
123
|
+
evaluate(script: string): Promise<string>;
|
|
124
|
+
/** Reads a platform setting: the JSON of its value. */
|
|
125
|
+
get(path: string): Promise<string>;
|
|
126
|
+
/**
|
|
127
|
+
* Calls a platform method: the JSON of its result. `argsJson` is JSON, so that a `null` argument survives the native
|
|
128
|
+
* conversion.
|
|
129
|
+
*/
|
|
130
|
+
call(path: string, argsJson: string): Promise<string>;
|
|
131
|
+
/** A hook's `context.handle` handler: the JSON of its reply. `args` is JSON, as for `call`. */
|
|
132
|
+
hook(name: string, method: string, args: string): Promise<string>;
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
const NativeWebView = requireNativeView<NativeProps>('MinimalWebView');
|
|
136
|
+
const nativeModule = () =>
|
|
137
|
+
requireNativeModule<{
|
|
138
|
+
defaultUserAgent: string;
|
|
139
|
+
warmUp(): void;
|
|
140
|
+
preconnect(url: string): Promise<void>;
|
|
141
|
+
setWebContentsDebuggingEnabled(enabled: boolean): Promise<void>;
|
|
142
|
+
}>('MinimalWebView');
|
|
143
|
+
|
|
144
|
+
/** Android rejects a view function with this until Expo has registered the view. */
|
|
145
|
+
const notRegistered = (error: unknown) =>
|
|
146
|
+
(error as { code?: string } | null)?.code === 'ERR_VIEW_NOT_FOUND';
|
|
147
|
+
|
|
148
|
+
/** A native call nothing awaits: a rejection is logged, bar one for a view not registered yet, where it does nothing. */
|
|
149
|
+
const unawaited = (call: Promise<unknown> | undefined, name: string) =>
|
|
150
|
+
void call?.catch((error: unknown) => {
|
|
151
|
+
if (!notRegistered(error))
|
|
152
|
+
console.error(`[react-native-minimal-webview] ${name} failed`, error);
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* A WebView whose native side decides navigations and owns the navigation state: see {@link WebViewProps} and
|
|
157
|
+
* {@link WebViewRef}.
|
|
158
|
+
* @group WebView
|
|
159
|
+
*/
|
|
160
|
+
export function WebView(props: WebViewProps) {
|
|
161
|
+
useBridgeChangeWarning(props.bridge);
|
|
162
|
+
return <WebViewInstance key={creationKey(props)} {...props} />;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Warns in development, once per WebView, when another bridge replaces its bridge, which recreated it: a bridge made
|
|
167
|
+
* in render (`bridge={createBridge(…)}`) would reload the page at every render.
|
|
168
|
+
*/
|
|
169
|
+
function useBridgeChangeWarning(bridge: WebViewProps['bridge']) {
|
|
170
|
+
const last = useRef(bridge);
|
|
171
|
+
const warned = useRef(false);
|
|
172
|
+
useEffect(() => {
|
|
173
|
+
if (__DEV__ && !warned.current && last.current && bridge && bridge !== last.current) {
|
|
174
|
+
warned.current = true;
|
|
175
|
+
console.warn(
|
|
176
|
+
'[react-native-minimal-webview] bridge: another bridge recreated the WebView, and its page loaded again; ' +
|
|
177
|
+
'create the bridge once, at module scope or with useMemo'
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
last.current = bridge;
|
|
181
|
+
}, [bridge]);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** One native WebView's life: a new creation key remounts it, so its state, ref attachment and bridge start over. */
|
|
185
|
+
function WebViewInstance({ ref, ...props }: WebViewProps) {
|
|
186
|
+
const native = useRef<NativeMethods>(null);
|
|
187
|
+
|
|
188
|
+
// The rejecters of native calls not settled yet. An unmount rejects them: native may never answer (a hook handler
|
|
189
|
+
// that never replies), and a late answer then settles nothing.
|
|
190
|
+
const [inFlight] = useState(() => new Set<(error: Error) => void>());
|
|
191
|
+
useEffect(
|
|
192
|
+
() => () => {
|
|
193
|
+
const message = 'the WebView unmounted before the call was answered';
|
|
194
|
+
inFlight.forEach((reject) => reject(codedError({ code: 'navigated', message })));
|
|
195
|
+
inFlight.clear();
|
|
196
|
+
},
|
|
197
|
+
[inFlight]
|
|
198
|
+
);
|
|
199
|
+
|
|
200
|
+
// A handle can outlive its native view (one captured before an unmount): navigation is then a no-op, and what
|
|
201
|
+
// answers rejects with `unavailable`.
|
|
202
|
+
const [handle] = useState((): WebViewRef => {
|
|
203
|
+
const gone = (): never => {
|
|
204
|
+
throw codedError({ code: 'unavailable', message: 'the WebView is gone' });
|
|
205
|
+
};
|
|
206
|
+
const settled = (promise: Promise<string>) =>
|
|
207
|
+
new Promise<string>((resolve, reject) => {
|
|
208
|
+
inFlight.add(reject);
|
|
209
|
+
promise.then(
|
|
210
|
+
(value) => {
|
|
211
|
+
inFlight.delete(reject);
|
|
212
|
+
resolve(value);
|
|
213
|
+
},
|
|
214
|
+
(error: unknown) => {
|
|
215
|
+
inFlight.delete(reject);
|
|
216
|
+
reject(error);
|
|
217
|
+
}
|
|
218
|
+
);
|
|
219
|
+
});
|
|
220
|
+
// Retries each frame until Expo has registered the view.
|
|
221
|
+
const mounted = async (call: () => Promise<string> | undefined) => {
|
|
222
|
+
for (let frame = 0; ; frame++) {
|
|
223
|
+
try {
|
|
224
|
+
return JSON.parse(await settled(call() ?? gone())) as unknown;
|
|
225
|
+
} catch (error) {
|
|
226
|
+
if (!notRegistered(error)) throw error;
|
|
227
|
+
if (frame === 60 || AppState.currentState === 'background') gone();
|
|
228
|
+
await new Promise((resolve) => requestAnimationFrame(resolve));
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
return {
|
|
233
|
+
goBack: () => unawaited(native.current?.goBack(), 'goBack'),
|
|
234
|
+
goForward: () => unawaited(native.current?.goForward(), 'goForward'),
|
|
235
|
+
reload: () => unawaited(native.current?.reload(), 'reload'),
|
|
236
|
+
stopLoading: () => unawaited(native.current?.stopLoading(), 'stopLoading'),
|
|
237
|
+
evaluate: (script) => mounted(() => native.current?.evaluate(script)),
|
|
238
|
+
get: (key) => mounted(() => native.current?.get(key)),
|
|
239
|
+
call: (method, args = []) =>
|
|
240
|
+
mounted(() => native.current?.call(method, JSON.stringify(args))),
|
|
241
|
+
hook: (name, method, args = []) =>
|
|
242
|
+
mounted(() => native.current?.hook(name, method, JSON.stringify(args))),
|
|
243
|
+
};
|
|
244
|
+
});
|
|
245
|
+
const publish = useAttach(ref, handle);
|
|
246
|
+
|
|
247
|
+
// onLoadStart and onLoadEnd are the edges of `loading`; native sets the ended load's `outcome`.
|
|
248
|
+
const onNavigationState = ({ nativeEvent }: Native<NavigationState>) => {
|
|
249
|
+
const state = own(nativeEvent);
|
|
250
|
+
const was = publish(state);
|
|
251
|
+
props.onNavigationStateChange?.(state);
|
|
252
|
+
if (!was.loading && state.loading) props.onLoadStart?.(state);
|
|
253
|
+
if (was.loading && !state.loading) props.onLoadEnd?.(state);
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
// The same string while nothing in it changed, so a re-render sends native nothing.
|
|
257
|
+
const settings = JSON.stringify(platformSettings(props));
|
|
258
|
+
const injectedScripts = useMemo(
|
|
259
|
+
() => nativeScripts(props.injectedScripts),
|
|
260
|
+
[props.injectedScripts]
|
|
261
|
+
);
|
|
262
|
+
const connection = props.bridge?.[CONNECTION];
|
|
263
|
+
useEffect(() => {
|
|
264
|
+
if (!connection) return undefined;
|
|
265
|
+
connection.attach((message) => unawaited(native.current?.bridgePost(message), 'bridgePost'));
|
|
266
|
+
return () => connection.detach();
|
|
267
|
+
}, [connection]);
|
|
268
|
+
|
|
269
|
+
const onBridge = ({ nativeEvent }: Native<BridgeEvent>) => {
|
|
270
|
+
if ('message' in nativeEvent) connection?.receive(nativeEvent.message, nativeEvent.origin);
|
|
271
|
+
else if ('navigated' in nativeEvent) connection?.navigated();
|
|
272
|
+
else connection?.markUnavailable();
|
|
273
|
+
};
|
|
274
|
+
|
|
275
|
+
const requestHandlers = useRequestHandlers(props);
|
|
276
|
+
const hookOptions = useHookOptions(props.extensions);
|
|
277
|
+
const navigationRules = useNavigationRules(props.navigationRules);
|
|
278
|
+
|
|
279
|
+
// One per ask in flight, by id: aborted when native stops waiting (the core's `askCancelled`) or at unmount.
|
|
280
|
+
const [asks] = useState(() => new Map<number, AbortController>());
|
|
281
|
+
useEffect(() => () => asks.forEach((controller) => controller.abort()), [asks]);
|
|
282
|
+
|
|
283
|
+
// The core's own events: a warning for the developer, and an ask native stopped waiting for.
|
|
284
|
+
const onCoreEvent = (name: string, payload: Record<string, unknown>) => {
|
|
285
|
+
if (name === 'warning')
|
|
286
|
+
console.warn(`[react-native-minimal-webview] ${String(payload['message'])}`);
|
|
287
|
+
else if (name === 'askCancelled') asks.get(payload['askId'] as number)?.abort();
|
|
288
|
+
else return false;
|
|
289
|
+
return true;
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
const onHookEvent = async ({
|
|
293
|
+
nativeEvent: { key, name, payload, askId },
|
|
294
|
+
}: Native<AskableEvent>) => {
|
|
295
|
+
const core = key === 'core';
|
|
296
|
+
if (core && onCoreEvent(name, payload)) return;
|
|
297
|
+
const request = REQUESTS.find((prop) => core && prop === name);
|
|
298
|
+
// The later of two extensions with one key, as in useHookOptions. No hook is registered under `core`.
|
|
299
|
+
const owner = props.extensions?.findLast((e): e is HookExtension => !!e && e.key === key);
|
|
300
|
+
const handler = request
|
|
301
|
+
? (props[request] as ((payload: unknown, signal?: AbortSignal) => unknown) | undefined)
|
|
302
|
+
: (_: unknown, signal?: AbortSignal) => owner?.onEvent?.({ name, payload }, signal);
|
|
303
|
+
// Only an ask can be cancelled, so only an ask gets a signal.
|
|
304
|
+
let controller: AbortController | undefined;
|
|
305
|
+
if (askId !== undefined) {
|
|
306
|
+
controller = new AbortController();
|
|
307
|
+
asks.set(askId, controller);
|
|
308
|
+
}
|
|
309
|
+
const failure = request ? `${request} failed` : `onEvent failed for ${key}.${name}`;
|
|
310
|
+
let value: unknown = null;
|
|
311
|
+
try {
|
|
312
|
+
value = await handler?.(payload, controller?.signal);
|
|
313
|
+
} catch (error) {
|
|
314
|
+
// Native waits on this handler: one that throws still answers, with null (native's safe default).
|
|
315
|
+
console.error(`[react-native-minimal-webview] ${failure}`, error);
|
|
316
|
+
}
|
|
317
|
+
if (askId === undefined) return;
|
|
318
|
+
asks.delete(askId);
|
|
319
|
+
// Native already answered a cancelled ask with null; a late answer would find nothing.
|
|
320
|
+
if (!controller?.signal.aborted) await native.current?.answer(askId, answerJson(value));
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
return (
|
|
324
|
+
<NativeWebView
|
|
325
|
+
{...viewPropsOf(props)}
|
|
326
|
+
ref={native}
|
|
327
|
+
source={props.source}
|
|
328
|
+
settings={settings}
|
|
329
|
+
pullToRefresh={props.pullToRefresh}
|
|
330
|
+
sharedCookies={Platform.OS === 'ios' ? props.sharedCookies : undefined}
|
|
331
|
+
navigationRules={navigationRules}
|
|
332
|
+
injectedScripts={injectedScripts}
|
|
333
|
+
bridgeScript={connection?.script}
|
|
334
|
+
bridgeOrigins={connection?.allowedOrigins}
|
|
335
|
+
hookOptions={hookOptions}
|
|
336
|
+
requestHandlers={requestHandlers}
|
|
337
|
+
onNavigation={({ nativeEvent }) => props.onNavigation?.(own(nativeEvent))}
|
|
338
|
+
onNavigationState={onNavigationState}
|
|
339
|
+
onBridge={onBridge}
|
|
340
|
+
onHookEvent={onHookEvent}
|
|
341
|
+
onError={({ nativeEvent }) => props.onError?.(own(nativeEvent))}
|
|
342
|
+
onProcessGone={({ nativeEvent }) => props.onProcessGone?.(own(nativeEvent))}
|
|
343
|
+
/>
|
|
344
|
+
);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** An ask's answer for native: null for one JSON can't encode (a function, a cycle, a BigInt), so the ask settles. */
|
|
348
|
+
function answerJson(value: unknown) {
|
|
349
|
+
try {
|
|
350
|
+
return JSON.stringify(value) ?? 'null';
|
|
351
|
+
} catch {
|
|
352
|
+
return 'null';
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* The scripts as native runs them: one whose `origins` lack `*` runs inside a function, so that even its function
|
|
358
|
+
* declarations take effect only where the guard lets it run.
|
|
359
|
+
*/
|
|
360
|
+
function nativeScripts(scripts: InjectedScript[] | undefined) {
|
|
361
|
+
return scripts?.map(({ code, allFrames, origins }) => {
|
|
362
|
+
if (!Array.isArray(origins))
|
|
363
|
+
throw new Error("injectedScripts: every script needs origins (['*'] for every origin)");
|
|
364
|
+
const guard = originGuard('injectedScripts: invalid origins', origins);
|
|
365
|
+
return { code: guard ? `if (${guard}) (() => {\n${code}\n})();` : code, allFrames };
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** Each rule field's kind, from its type, so that a field missing here, or not in the type, fails to compile. */
|
|
370
|
+
const RULE_FIELDS = new Map(
|
|
371
|
+
Object.entries({
|
|
372
|
+
scheme: 'list',
|
|
373
|
+
host: 'list',
|
|
374
|
+
path: 'list',
|
|
375
|
+
query: 'list',
|
|
376
|
+
mainFrame: 'flag',
|
|
377
|
+
newWindow: 'flag',
|
|
378
|
+
userInitiated: 'flag',
|
|
379
|
+
action: 'action',
|
|
380
|
+
} satisfies {
|
|
381
|
+
[K in keyof NavigationRule]-?: NonNullable<NavigationRule[K]> extends readonly string[]
|
|
382
|
+
? 'list'
|
|
383
|
+
: NonNullable<NavigationRule[K]> extends boolean
|
|
384
|
+
? 'flag'
|
|
385
|
+
: 'action';
|
|
386
|
+
})
|
|
387
|
+
);
|
|
388
|
+
const ACTIONS: unknown[] = Object.keys({
|
|
389
|
+
allow: 0,
|
|
390
|
+
block: 0,
|
|
391
|
+
external: 0,
|
|
392
|
+
ask: 0,
|
|
393
|
+
} satisfies Record<NavigationRule['action'], 0>);
|
|
394
|
+
|
|
395
|
+
/** A value as a warning shows it. */
|
|
396
|
+
const shown = (value: unknown) => JSON.stringify(value) ?? String(value);
|
|
397
|
+
|
|
398
|
+
/** What a field of each kind takes, as a warning says it, and the check. */
|
|
399
|
+
const FIELD_KINDS = {
|
|
400
|
+
list: {
|
|
401
|
+
takes: 'an array of strings',
|
|
402
|
+
ok: (value: unknown) =>
|
|
403
|
+
Array.isArray(value) && value.every((entry) => typeof entry === 'string'),
|
|
404
|
+
},
|
|
405
|
+
flag: { takes: 'true or false', ok: (value: unknown) => typeof value === 'boolean' },
|
|
406
|
+
action: { takes: `one of ${shown(ACTIONS)}`, ok: (value: unknown) => ACTIONS.includes(value) },
|
|
407
|
+
};
|
|
408
|
+
|
|
409
|
+
/** What is wrong with a rule, if anything. */
|
|
410
|
+
function ruleProblem(rule: unknown) {
|
|
411
|
+
if (typeof rule !== 'object' || rule === null) return `must be an object, not ${shown(rule)}`;
|
|
412
|
+
// A missing action is checked as an undefined one; any other field may be undefined (unset).
|
|
413
|
+
for (const [key, value] of Object.entries({ action: undefined, ...rule })) {
|
|
414
|
+
const kind = RULE_FIELDS.get(key);
|
|
415
|
+
if (!kind) return `unknown key ${shown(key)}`;
|
|
416
|
+
if ((value !== undefined || kind === 'action') && !FIELD_KINDS[kind].ok(value))
|
|
417
|
+
return `${key} must be ${FIELD_KINDS[kind].takes}, not ${shown(value)}`;
|
|
418
|
+
}
|
|
419
|
+
return undefined;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* The rules as native gets them. Native skips an unknown key and a flag that isn't a boolean, which would widen a rule
|
|
424
|
+
* (`hosts` would match every host), so a malformed rule becomes one that blocks whatever reaches it, never more than
|
|
425
|
+
* the rule meant, and a development warning names it. The same array when no rule is malformed.
|
|
426
|
+
*/
|
|
427
|
+
function useNavigationRules(rules: WebViewProps['navigationRules']) {
|
|
428
|
+
const given: unknown = rules ?? defaultNavigationRules;
|
|
429
|
+
const { checked, warnings } = useMemo(() => {
|
|
430
|
+
if (!Array.isArray(given))
|
|
431
|
+
return {
|
|
432
|
+
checked: [],
|
|
433
|
+
warnings: [`navigationRules: must be an array, not ${shown(given)}; treated as []`],
|
|
434
|
+
};
|
|
435
|
+
const problems = given.map(ruleProblem);
|
|
436
|
+
return {
|
|
437
|
+
checked: problems.some(Boolean)
|
|
438
|
+
? given.map((rule: unknown, i) => (problems[i] ? { action: 'block' } : rule))
|
|
439
|
+
: given,
|
|
440
|
+
warnings: problems.flatMap((problem, i) =>
|
|
441
|
+
problem
|
|
442
|
+
? [`navigationRules[${i}]: ${problem}; it blocks every navigation that reaches it`]
|
|
443
|
+
: []
|
|
444
|
+
),
|
|
445
|
+
};
|
|
446
|
+
}, [given]);
|
|
447
|
+
const json = JSON.stringify(warnings);
|
|
448
|
+
useEffect(() => {
|
|
449
|
+
if (!__DEV__) return;
|
|
450
|
+
for (const warning of JSON.parse(json) as string[])
|
|
451
|
+
console.warn(`[react-native-minimal-webview] ${warning}`);
|
|
452
|
+
}, [json]);
|
|
453
|
+
return checked as NavigationRule[];
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/** The `REQUESTS` with a prop set, as a new array only when that set changes. */
|
|
457
|
+
function useRequestHandlers(props: WebViewProps) {
|
|
458
|
+
const key = REQUESTS.filter((prop) => props[prop]).join();
|
|
459
|
+
return useMemo(() => (key ? key.split(',') : []), [key]);
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/**
|
|
463
|
+
* Native's `hookOptions`: each extension's `options` by its key, the later of two extensions with one key winning (a
|
|
464
|
+
* development warning). An off `options` leaves the key out. The same object while the JSON is the same, so a render
|
|
465
|
+
* with new handlers sends native nothing.
|
|
466
|
+
*/
|
|
467
|
+
function useHookOptions(extensions: WebViewProps['extensions']) {
|
|
468
|
+
const on = (extensions ?? []).filter((extension) => !!extension);
|
|
469
|
+
const keys = on.map(({ key }) => key);
|
|
470
|
+
const repeated = JSON.stringify([...new Set(keys.filter((key, i) => keys.indexOf(key) !== i))]);
|
|
471
|
+
useEffect(() => {
|
|
472
|
+
if (!__DEV__) return;
|
|
473
|
+
for (const key of JSON.parse(repeated) as string[])
|
|
474
|
+
console.warn(
|
|
475
|
+
`[react-native-minimal-webview] extensions: two extensions have the key ${key}; the later one wins`
|
|
476
|
+
);
|
|
477
|
+
}, [repeated]);
|
|
478
|
+
const json = JSON.stringify(
|
|
479
|
+
withoutOff(
|
|
480
|
+
Object.fromEntries(
|
|
481
|
+
// An unset `options` is `true` (HookExtension.options).
|
|
482
|
+
on.map(({ key, options = true }) => [key, options])
|
|
483
|
+
)
|
|
484
|
+
)
|
|
485
|
+
);
|
|
486
|
+
return useMemo(() => JSON.parse(json) as Record<string, unknown>, [json]);
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/** Bridges by identity, for the creation key. */
|
|
490
|
+
const bridgeIds = new WeakMap<object, number>();
|
|
491
|
+
let lastBridgeId = 0;
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* What native sets up once, at creation (the bridge, `ios.configuration`). As WebViewInstance's `key`, a change
|
|
495
|
+
* remounts it.
|
|
496
|
+
*/
|
|
497
|
+
function creationKey(props: WebViewProps) {
|
|
498
|
+
const bridge = props.bridge;
|
|
499
|
+
let id = bridge && bridgeIds.get(bridge);
|
|
500
|
+
if (bridge && id === undefined) bridgeIds.set(bridge, (id = ++lastBridgeId));
|
|
501
|
+
return JSON.stringify(
|
|
502
|
+
[id ?? 0, Platform.OS === 'ios' ? props.ios?.configuration : undefined],
|
|
503
|
+
sortedKeys
|
|
504
|
+
);
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/** A null or false value is off, and its key is left out: native treats a present key as on. */
|
|
508
|
+
const withoutOff = (options: Record<string, unknown>) =>
|
|
509
|
+
Object.fromEntries(
|
|
510
|
+
Object.entries(options).filter(([, value]) => value != null && value !== false)
|
|
511
|
+
);
|
|
512
|
+
|
|
513
|
+
/** A JSON.stringify replacer: the same options in another key order are the same key. */
|
|
514
|
+
const sortedKeys = (_: string, value: unknown) =>
|
|
515
|
+
value && typeof value === 'object' && !Array.isArray(value)
|
|
516
|
+
? Object.fromEntries(Object.entries(value).sort())
|
|
517
|
+
: value;
|
|
518
|
+
|
|
519
|
+
function viewPropsOf(props: WebViewProps): ViewProps {
|
|
520
|
+
return Object.fromEntries(Object.entries(props).filter(([key]) => !OWN_SET.has(key)));
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/** Each root's keys with its `other` ones among them, as native takes them; a generated key wins. */
|
|
524
|
+
const flattened = (
|
|
525
|
+
roots: Record<string, { other?: NativeSettings[string] } | undefined> = {}
|
|
526
|
+
): NativeSettings =>
|
|
527
|
+
Object.fromEntries(
|
|
528
|
+
Object.entries(roots).map(([name, { other, ...keys } = {}]) => [name, { ...other, ...keys }])
|
|
529
|
+
);
|
|
530
|
+
|
|
531
|
+
/** Each layer's roots over the earlier layers', key by key. */
|
|
532
|
+
const layered = (...layers: NativeSettings[]) =>
|
|
533
|
+
layers.reduce<NativeSettings>((out, layer) => {
|
|
534
|
+
for (const [root, keys] of Object.entries(layer)) out[root] = { ...out[root], ...keys };
|
|
535
|
+
return out;
|
|
536
|
+
}, {});
|
|
537
|
+
|
|
538
|
+
/**
|
|
539
|
+
* The platform's settings for native: the package's defaults, react-native-webview's over them, the app's `ios` or
|
|
540
|
+
* `android` roots over those, and `userAgent` on top. Native restores the key of a removed `userAgent`. Android's
|
|
541
|
+
* own defaults are written natively.
|
|
542
|
+
*/
|
|
543
|
+
function platformSettings(props: WebViewProps): NativeSettings {
|
|
544
|
+
const [defaults, rnw, app, userAgent] =
|
|
545
|
+
Platform.OS === 'ios'
|
|
546
|
+
? [
|
|
547
|
+
flattened(DEFAULTS.IOSSettings),
|
|
548
|
+
REACT_NATIVE_WEBVIEW_DEFAULTS.ios,
|
|
549
|
+
flattened(props.ios),
|
|
550
|
+
{ webView: { customUserAgent: props.userAgent } },
|
|
551
|
+
]
|
|
552
|
+
: [
|
|
553
|
+
{},
|
|
554
|
+
REACT_NATIVE_WEBVIEW_DEFAULTS.android,
|
|
555
|
+
flattened(props.android),
|
|
556
|
+
{ settings: { userAgentString: props.userAgent } },
|
|
557
|
+
];
|
|
558
|
+
return layered(defaults, rnw, app, props.userAgent === undefined ? {} : userAgent);
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/**
|
|
562
|
+
* Android's process-wide WebView functions, like the static methods of Android's `WebView`. On iOS they do nothing,
|
|
563
|
+
* and `defaultUserAgent` is null.
|
|
564
|
+
* @group WebView
|
|
565
|
+
* @android
|
|
566
|
+
* @namespace
|
|
567
|
+
*/
|
|
568
|
+
export const AndroidWebView = {
|
|
569
|
+
/**
|
|
570
|
+
* Android's default user agent, for `android.settings.userAgentString` with a suffix.
|
|
571
|
+
*
|
|
572
|
+
* The first read loads WebView's code, on the JS thread: read it once `warmUp()` has had time or a WebView is
|
|
573
|
+
* mounted.
|
|
574
|
+
* @android
|
|
575
|
+
*/
|
|
576
|
+
get defaultUserAgent(): string | null {
|
|
577
|
+
return Platform.OS === 'android' ? nativeModule().defaultUserAgent : null;
|
|
578
|
+
},
|
|
579
|
+
/**
|
|
580
|
+
* Starts WebView before any WebView mounts, so the first WebView mounts sooner.
|
|
581
|
+
*
|
|
582
|
+
* It helps only if it runs well before the first WebView mounts: at app start, or as the screen with the WebView is
|
|
583
|
+
* pushed. Calling it at mount gains nothing. WebView starts once per app, and React Native's first `fetch` starts
|
|
584
|
+
* it too.
|
|
585
|
+
* @android
|
|
586
|
+
*/
|
|
587
|
+
warmUp(): void {
|
|
588
|
+
if (Platform.OS === 'android') nativeModule().warmUp();
|
|
589
|
+
},
|
|
590
|
+
/**
|
|
591
|
+
* Opens a connection to `url`'s origin (DNS, TCP, TLS) in WebView's default profile, ahead of a load that comes
|
|
592
|
+
* later.
|
|
593
|
+
*
|
|
594
|
+
* Use it for a load that hasn't started yet: as the screen with the WebView is pushed, or for the next page a
|
|
595
|
+
* mounted WebView will go to. A WebView connects to its `source` itself as it mounts, so preconnecting `source` at
|
|
596
|
+
* mount gains nothing.
|
|
597
|
+
*
|
|
598
|
+
* It starts WebView on the UI thread if nothing has yet, so call it once `warmUp()` has had time or a WebView is
|
|
599
|
+
* mounted.
|
|
600
|
+
*
|
|
601
|
+
* Needs the androidx.webkit features `MULTI_PROFILE` and `ENQUEUE_PRECONNECT` or `PRECONNECT`; without them it does
|
|
602
|
+
* nothing. For prefetch and prerender, a native hook uses `ProfileStore`.
|
|
603
|
+
* @android
|
|
604
|
+
*/
|
|
605
|
+
preconnect(url: string): void {
|
|
606
|
+
if (Platform.OS === 'android') unawaited(nativeModule().preconnect(url), 'preconnect');
|
|
607
|
+
},
|
|
608
|
+
/**
|
|
609
|
+
* Turns remote debugging (`chrome://inspect`) of every WebView in the app on or off.
|
|
610
|
+
*
|
|
611
|
+
* Until it is called, it is on when the app is debuggable (a debug build) and off otherwise. Called before any
|
|
612
|
+
* WebView exists, it applies when the first one is made, so it doesn't start WebView. On iOS,
|
|
613
|
+
* `ios.webView.inspectable` sets it per WebView.
|
|
614
|
+
* @android
|
|
615
|
+
*/
|
|
616
|
+
setWebContentsDebuggingEnabled(enabled: boolean): void {
|
|
617
|
+
if (Platform.OS === 'android')
|
|
618
|
+
unawaited(
|
|
619
|
+
nativeModule().setWebContentsDebuggingEnabled(enabled),
|
|
620
|
+
'setWebContentsDebuggingEnabled'
|
|
621
|
+
);
|
|
622
|
+
},
|
|
623
|
+
};
|