react-native-minimal-webview 1.1.0 → 1.2.1
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/README.md +35 -31
- package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +1 -6
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +56 -31
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +3 -2
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +16 -4
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +3 -3
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +5 -7
- package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +47 -36
- package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +2 -2
- package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +7 -8
- package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +2 -2
- package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +4 -5
- package/build/WebView.d.ts +4 -10
- package/build/WebView.d.ts.map +1 -1
- package/build/WebView.js +60 -103
- package/build/WebView.js.map +1 -1
- package/build/bridge/createBridge.d.ts +17 -11
- package/build/bridge/createBridge.d.ts.map +1 -1
- package/build/bridge/createBridge.js +32 -44
- package/build/bridge/createBridge.js.map +1 -1
- package/build/bridge/endpoint.d.ts +1 -3
- package/build/bridge/endpoint.d.ts.map +1 -1
- package/build/bridge/endpoint.js +2 -2
- package/build/bridge/endpoint.js.map +1 -1
- package/build/bridge/origins.d.ts +5 -2
- package/build/bridge/origins.d.ts.map +1 -1
- package/build/bridge/origins.js +15 -4
- package/build/bridge/origins.js.map +1 -1
- package/build/bridge/pageClient.generated.d.ts +1 -1
- package/build/bridge/pageClient.generated.d.ts.map +1 -1
- package/build/bridge/pageClient.generated.js +1 -1
- package/build/bridge/pageClient.generated.js.map +1 -1
- package/build/index.d.ts +1 -1
- package/build/index.d.ts.map +1 -1
- package/build/index.js +1 -1
- package/build/index.js.map +1 -1
- package/build/{defaultNavigationRules.d.ts → navigationRules.d.ts} +10 -1
- package/build/navigationRules.d.ts.map +1 -0
- package/build/navigationRules.js +93 -0
- package/build/navigationRules.js.map +1 -0
- package/build/refStore.d.ts.map +1 -1
- package/build/refStore.js +13 -17
- package/build/refStore.js.map +1 -1
- package/build/types.d.ts +66 -40
- package/build/types.d.ts.map +1 -1
- package/ios/DelegateProxy.swift +35 -30
- package/ios/Loads.swift +4 -4
- package/ios/MRWInvoke.h +8 -0
- package/ios/MRWInvoke.m +39 -24
- package/ios/MinimalWebView+Dialogs.swift +4 -2
- package/ios/MinimalWebView+Navigation.swift +23 -13
- package/ios/MinimalWebView+Scripts.swift +6 -1
- package/ios/MinimalWebView.swift +78 -29
- package/ios/MinimalWebViewModule.swift +1 -0
- package/ios/NavigationRules.swift +15 -15
- package/ios/PlatformSettings.swift +2 -13
- package/ios/SharedCookies.swift +1 -2
- package/mocks/MinimalWebView.ts +5 -0
- package/package.json +9 -8
- package/src/WebView.tsx +74 -117
- package/src/bridge/createBridge.ts +45 -53
- package/src/bridge/endpoint.ts +3 -5
- package/src/bridge/origins.ts +18 -6
- package/src/bridge/pageClient.generated.ts +1 -1
- package/src/index.ts +1 -1
- package/src/navigationRules.ts +111 -0
- package/src/refStore.ts +15 -19
- package/src/types.ts +66 -40
- package/build/defaultNavigationRules.d.ts.map +0 -1
- package/build/defaultNavigationRules.js +0 -22
- package/build/defaultNavigationRules.js.map +0 -1
- package/ios/MRWExceptions.h +0 -9
- package/ios/MRWExceptions.m +0 -10
- package/src/defaultNavigationRules.ts +0 -24
package/src/WebView.tsx
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import { requireNativeModule, requireNativeView } from 'expo';
|
|
1
|
+
import { requireNativeModule, requireNativeView, requireOptionalNativeModule } from 'expo';
|
|
2
2
|
import { type Ref, useEffect, useMemo, useRef, useState } from 'react';
|
|
3
3
|
import { AppState, Platform, type ViewProps } from 'react-native';
|
|
4
4
|
|
|
5
|
-
import {
|
|
5
|
+
import { type BridgeEvent, CONNECTION } from './bridge/createBridge';
|
|
6
6
|
import { codedError } from './bridge/endpoint';
|
|
7
|
-
import {
|
|
7
|
+
import { originGuard } from './bridge/origins';
|
|
8
|
+
import { checkNavigationRules, defaultNavigationRules } from './navigationRules';
|
|
8
9
|
import { REACT_NATIVE_WEBVIEW_DEFAULTS } from './reactNativeWebViewDefaults';
|
|
9
10
|
import { useAttach } from './refStore';
|
|
10
11
|
import type {
|
|
@@ -12,7 +13,6 @@ import type {
|
|
|
12
13
|
InjectedScript,
|
|
13
14
|
LoadErrorEvent,
|
|
14
15
|
NavigationEvent,
|
|
15
|
-
NavigationRule,
|
|
16
16
|
NavigationState,
|
|
17
17
|
ProcessGoneEvent,
|
|
18
18
|
SettingValue,
|
|
@@ -27,10 +27,6 @@ type NativeHandlers<E> = { [K in keyof E]: (event: Native<E[K]>) => void };
|
|
|
27
27
|
/** The event without the `target` (the view's tag) React Native adds to every native event. */
|
|
28
28
|
const own = <T,>({ target: _, ...event }: T & { target?: unknown }) => event as T;
|
|
29
29
|
|
|
30
|
-
/** A page's message comes with its origin, as native verified it (`location.origin` form). */
|
|
31
|
-
export type BridgeEvent =
|
|
32
|
-
{ message: string; origin: string } | { navigated: true } | { unavailable: true };
|
|
33
|
-
|
|
34
30
|
/**
|
|
35
31
|
* 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
|
|
36
32
|
* the answer.
|
|
@@ -111,6 +107,7 @@ type NativeProps = ViewProps &
|
|
|
111
107
|
export type NativeMethods = {
|
|
112
108
|
goBack(): Promise<void>;
|
|
113
109
|
goForward(): Promise<void>;
|
|
110
|
+
load(url: string): Promise<void>;
|
|
114
111
|
reload(): Promise<void>;
|
|
115
112
|
stopLoading(): Promise<void>;
|
|
116
113
|
bridgePost(message: string): Promise<void>;
|
|
@@ -138,6 +135,18 @@ const nativeModule = () =>
|
|
|
138
135
|
setWebContentsDebuggingEnabled(enabled: boolean): Promise<void>;
|
|
139
136
|
}>('MinimalWebView');
|
|
140
137
|
|
|
138
|
+
let linked = false;
|
|
139
|
+
// pod install leaves the pod out below the iOS floor with only a warning, which `expo run:ios` hides; without this the
|
|
140
|
+
// view renders as React Native's "Unimplemented component".
|
|
141
|
+
function assertLinked() {
|
|
142
|
+
linked ||= requireOptionalNativeModule('MinimalWebView') != null;
|
|
143
|
+
if (!linked)
|
|
144
|
+
throw new Error(
|
|
145
|
+
'[react-native-minimal-webview] this build has no MinimalWebView native module. On iOS, pod install leaves ' +
|
|
146
|
+
'it out below the deployment target 17.0: set it to 17.0 or later, then rebuild. Otherwise, rebuild the app.'
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
|
|
141
150
|
/** Android rejects a view function with this until Expo has registered the view. */
|
|
142
151
|
const notRegistered = (error: unknown) =>
|
|
143
152
|
(error as { code?: string } | null)?.code === 'ERR_VIEW_NOT_FOUND';
|
|
@@ -149,12 +158,21 @@ const unawaited = (call: Promise<unknown> | undefined, name: string) =>
|
|
|
149
158
|
console.error(`[react-native-minimal-webview] ${name} failed`, error);
|
|
150
159
|
});
|
|
151
160
|
|
|
161
|
+
/**
|
|
162
|
+
* Whether `url` is a `javascript:` URL as a URL parser reads it (leading controls and spaces skipped, tabs and newlines
|
|
163
|
+
* dropped): Android's loadUrl would run its script.
|
|
164
|
+
*/
|
|
165
|
+
const isJavaScriptUrl = (url: string) => /^[\0- ]*javascript:/i.test(url.replace(/[\t\n\r]/g, ''));
|
|
166
|
+
|
|
152
167
|
/**
|
|
153
168
|
* A WebView whose core decides navigations and owns the navigation state: see {@link WebViewProps} and
|
|
154
169
|
* {@link WebViewRef}.
|
|
170
|
+
* @throws An `Error` as it renders when the app was built without the package's native module: on iOS, below the
|
|
171
|
+
* deployment target 17.0.
|
|
155
172
|
* @group WebView
|
|
156
173
|
*/
|
|
157
174
|
export function WebView(props: WebViewProps) {
|
|
175
|
+
assertLinked();
|
|
158
176
|
useBridgeChangeWarning(props.bridge);
|
|
159
177
|
return <WebViewInstance key={creationKey(props)} {...props} />;
|
|
160
178
|
}
|
|
@@ -223,6 +241,24 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
|
|
|
223
241
|
return {
|
|
224
242
|
goBack: () => unawaited(native.current?.goBack(), 'goBack'),
|
|
225
243
|
goForward: () => unawaited(native.current?.goForward(), 'goForward'),
|
|
244
|
+
load: (url) => {
|
|
245
|
+
if (isJavaScriptUrl(url)) {
|
|
246
|
+
if (__DEV__)
|
|
247
|
+
console.warn(
|
|
248
|
+
'[react-native-minimal-webview] load: a javascript: URL loads nothing; run a script with evaluate'
|
|
249
|
+
);
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
// mounted() parses a JSON result, and load has none. A view that went away or never came loads nothing, as
|
|
253
|
+
// a navigation method does after an unmount.
|
|
254
|
+
unawaited(
|
|
255
|
+
mounted(() => native.current?.load(url).then(() => 'null')).catch((error: unknown) => {
|
|
256
|
+
const code = (error as { code?: string } | null)?.code;
|
|
257
|
+
if (code !== 'unavailable' && code !== 'navigated') throw error;
|
|
258
|
+
}),
|
|
259
|
+
'load'
|
|
260
|
+
);
|
|
261
|
+
},
|
|
226
262
|
reload: () => unawaited(native.current?.reload(), 'reload'),
|
|
227
263
|
stopLoading: () => unawaited(native.current?.stopLoading(), 'stopLoading'),
|
|
228
264
|
evaluate: (script) => mounted(() => native.current?.evaluate(script)),
|
|
@@ -256,12 +292,6 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
|
|
|
256
292
|
return () => connection.detach();
|
|
257
293
|
}, [connection]);
|
|
258
294
|
|
|
259
|
-
const onBridge = ({ nativeEvent }: Native<BridgeEvent>) => {
|
|
260
|
-
if ('message' in nativeEvent) connection?.receive(nativeEvent.message, nativeEvent.origin);
|
|
261
|
-
else if ('navigated' in nativeEvent) connection?.navigated();
|
|
262
|
-
else connection?.markUnavailable();
|
|
263
|
-
};
|
|
264
|
-
|
|
265
295
|
const requestHandlers = useRequestHandlers(props);
|
|
266
296
|
const hookOptions = useHookOptions(props.extensions);
|
|
267
297
|
const navigationRules = useNavigationRules(props.navigationRules);
|
|
@@ -270,20 +300,14 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
|
|
|
270
300
|
const [asks] = useState(() => new Map<number, AbortController>());
|
|
271
301
|
useEffect(() => () => asks.forEach((controller) => controller.abort()), [asks]);
|
|
272
302
|
|
|
273
|
-
// The core's own events: a warning for the developer, and an ask native stopped waiting for.
|
|
274
|
-
const onCoreEvent = (name: string, payload: Record<string, unknown>) => {
|
|
275
|
-
if (name === 'warning')
|
|
276
|
-
console.warn(`[react-native-minimal-webview] ${String(payload['message'])}`);
|
|
277
|
-
else if (name === 'askCancelled') asks.get(payload['askId'] as number)?.abort();
|
|
278
|
-
else return false;
|
|
279
|
-
return true;
|
|
280
|
-
};
|
|
281
|
-
|
|
282
303
|
const onHookEvent = async ({
|
|
283
304
|
nativeEvent: { key, name, payload, askId },
|
|
284
305
|
}: Native<AskableEvent>) => {
|
|
285
306
|
const core = key === 'core';
|
|
286
|
-
|
|
307
|
+
// The core's own events: a warning for the developer, and an ask native stopped waiting for.
|
|
308
|
+
if (core && name === 'warning')
|
|
309
|
+
return console.warn(`[react-native-minimal-webview] ${String(payload['message'])}`);
|
|
310
|
+
if (core && name === 'askCancelled') return asks.get(payload['askId'] as number)?.abort();
|
|
287
311
|
const request = REQUESTS.find((prop) => core && prop === name);
|
|
288
312
|
// The later of two extensions with one key, as in useHookOptions. No hook is registered under `core`.
|
|
289
313
|
const owner = props.extensions?.findLast((e): e is HookExtension => !!e && e.key === key);
|
|
@@ -326,7 +350,7 @@ function WebViewInstance({ ref, ...props }: WebViewProps) {
|
|
|
326
350
|
requestHandlers={requestHandlers}
|
|
327
351
|
onNavigation={({ nativeEvent }) => props.onNavigation?.(own(nativeEvent))}
|
|
328
352
|
onNavigationState={onNavigationState}
|
|
329
|
-
onBridge={
|
|
353
|
+
onBridge={({ nativeEvent }) => connection?.receive(nativeEvent)}
|
|
330
354
|
onHookEvent={onHookEvent}
|
|
331
355
|
onError={({ nativeEvent }) => props.onError?.(own(nativeEvent))}
|
|
332
356
|
onProcessGone={({ nativeEvent }) => props.onProcessGone?.(own(nativeEvent))}
|
|
@@ -356,97 +380,27 @@ function nativeScripts(scripts: InjectedScript[] | undefined) {
|
|
|
356
380
|
});
|
|
357
381
|
}
|
|
358
382
|
|
|
359
|
-
/** Each rule field's kind, from its type, so that a field missing here, or not in the type, fails to compile. */
|
|
360
|
-
const RULE_FIELDS = new Map(
|
|
361
|
-
Object.entries({
|
|
362
|
-
scheme: 'list',
|
|
363
|
-
host: 'list',
|
|
364
|
-
path: 'list',
|
|
365
|
-
query: 'list',
|
|
366
|
-
mainFrame: 'flag',
|
|
367
|
-
newWindow: 'flag',
|
|
368
|
-
userInitiated: 'flag',
|
|
369
|
-
action: 'action',
|
|
370
|
-
} satisfies {
|
|
371
|
-
[K in keyof NavigationRule]-?: NonNullable<NavigationRule[K]> extends readonly string[]
|
|
372
|
-
? 'list'
|
|
373
|
-
: NonNullable<NavigationRule[K]> extends boolean
|
|
374
|
-
? 'flag'
|
|
375
|
-
: 'action';
|
|
376
|
-
})
|
|
377
|
-
);
|
|
378
|
-
const ACTIONS: unknown[] = Object.keys({
|
|
379
|
-
allow: 0,
|
|
380
|
-
block: 0,
|
|
381
|
-
external: 0,
|
|
382
|
-
ask: 0,
|
|
383
|
-
} satisfies Record<NavigationRule['action'], 0>);
|
|
384
|
-
|
|
385
|
-
/** A value as a warning shows it. */
|
|
386
|
-
const shown = (value: unknown) => {
|
|
387
|
-
try {
|
|
388
|
-
return JSON.stringify(value) ?? String(value);
|
|
389
|
-
} catch {
|
|
390
|
-
// A BigInt, a circular value or a throwing toJSON: the message runs in production too, so it must not throw.
|
|
391
|
-
return typeof value === 'bigint' ? String(value) : Object.prototype.toString.call(value);
|
|
392
|
-
}
|
|
393
|
-
};
|
|
394
|
-
|
|
395
|
-
/** What a field of each kind takes, as a warning says it, and the check. */
|
|
396
|
-
const FIELD_KINDS = {
|
|
397
|
-
list: {
|
|
398
|
-
takes: 'an array of strings',
|
|
399
|
-
ok: (value: unknown) =>
|
|
400
|
-
Array.isArray(value) && value.every((entry) => typeof entry === 'string'),
|
|
401
|
-
},
|
|
402
|
-
flag: { takes: 'true or false', ok: (value: unknown) => typeof value === 'boolean' },
|
|
403
|
-
action: { takes: `one of ${shown(ACTIONS)}`, ok: (value: unknown) => ACTIONS.includes(value) },
|
|
404
|
-
};
|
|
405
|
-
|
|
406
|
-
function ruleProblem(rule: unknown) {
|
|
407
|
-
if (typeof rule !== 'object' || rule === null) return `must be an object, not ${shown(rule)}`;
|
|
408
|
-
// A missing action is checked as an undefined one; any other field may be undefined (unset).
|
|
409
|
-
for (const [key, value] of Object.entries({ action: undefined, ...rule })) {
|
|
410
|
-
const kind = RULE_FIELDS.get(key);
|
|
411
|
-
if (!kind) return `unknown key ${shown(key)}`;
|
|
412
|
-
if ((value !== undefined || kind === 'action') && !FIELD_KINDS[kind].ok(value))
|
|
413
|
-
return `${key} must be ${FIELD_KINDS[kind].takes}, not ${shown(value)}`;
|
|
414
|
-
}
|
|
415
|
-
return undefined;
|
|
416
|
-
}
|
|
417
|
-
|
|
418
383
|
/**
|
|
419
|
-
* The rules as the core gets them
|
|
420
|
-
*
|
|
384
|
+
* The rules as the core gets them (`checkNavigationRules`), and a development warning for each malformed one. The same
|
|
385
|
+
* array when none is malformed.
|
|
421
386
|
*/
|
|
422
387
|
function useNavigationRules(rules: WebViewProps['navigationRules']) {
|
|
423
|
-
const
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
checked: problems.some(Boolean)
|
|
434
|
-
? Array.from(given, (rule: unknown, i) => (problems[i] ? { action: 'block' } : rule))
|
|
435
|
-
: given,
|
|
436
|
-
warnings: problems.flatMap((problem, i) =>
|
|
437
|
-
problem
|
|
438
|
-
? [`navigationRules[${i}]: ${problem}; it blocks every navigation that reaches it`]
|
|
439
|
-
: []
|
|
440
|
-
),
|
|
441
|
-
};
|
|
442
|
-
}, [given]);
|
|
388
|
+
const { checked, warnings } = useMemo(
|
|
389
|
+
() => checkNavigationRules(rules ?? defaultNavigationRules),
|
|
390
|
+
[rules]
|
|
391
|
+
);
|
|
392
|
+
useDevWarnings(warnings);
|
|
393
|
+
return checked;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** Logs each warning in development, again only when the list changes. */
|
|
397
|
+
function useDevWarnings(warnings: string[]) {
|
|
443
398
|
const json = JSON.stringify(warnings);
|
|
444
399
|
useEffect(() => {
|
|
445
400
|
if (!__DEV__) return;
|
|
446
401
|
for (const warning of JSON.parse(json) as string[])
|
|
447
402
|
console.warn(`[react-native-minimal-webview] ${warning}`);
|
|
448
403
|
}, [json]);
|
|
449
|
-
return checked as NavigationRule[];
|
|
450
404
|
}
|
|
451
405
|
|
|
452
406
|
/** The `REQUESTS` with a prop set, as a new array only when that set changes. */
|
|
@@ -463,14 +417,11 @@ function useRequestHandlers(props: WebViewProps) {
|
|
|
463
417
|
function useHookOptions(extensions: WebViewProps['extensions']) {
|
|
464
418
|
const on = (extensions ?? []).filter((extension) => !!extension);
|
|
465
419
|
const keys = on.map(({ key }) => key);
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
`[react-native-minimal-webview] extensions: two extensions have the key ${key}; the later one wins`
|
|
472
|
-
);
|
|
473
|
-
}, [repeated]);
|
|
420
|
+
useDevWarnings(
|
|
421
|
+
[...new Set(keys.filter((key, i) => keys.indexOf(key) !== i))].map(
|
|
422
|
+
(key) => `extensions: two extensions have the key ${key}; the later one wins`
|
|
423
|
+
)
|
|
424
|
+
);
|
|
474
425
|
const json = JSON.stringify(
|
|
475
426
|
withoutOff(
|
|
476
427
|
Object.fromEntries(
|
|
@@ -566,11 +517,17 @@ export const AndroidWebView = {
|
|
|
566
517
|
* Android's default user agent, for `android.settings.userAgentString` with a suffix.
|
|
567
518
|
*
|
|
568
519
|
* The first read loads WebView's code, on the JS thread: read it once `warmUp()` has had time or a WebView is
|
|
569
|
-
* mounted.
|
|
520
|
+
* mounted. It is null while Android System WebView is missing, disabled or updating, and a later read tries again.
|
|
570
521
|
* @android
|
|
571
522
|
*/
|
|
572
523
|
get defaultUserAgent(): string | null {
|
|
573
|
-
|
|
524
|
+
if (Platform.OS !== 'android') return null;
|
|
525
|
+
try {
|
|
526
|
+
return nativeModule().defaultUserAgent;
|
|
527
|
+
} catch {
|
|
528
|
+
// Caught here, not natively: Expo caches a value the native getter returns, a null too, but not a throw.
|
|
529
|
+
return null;
|
|
530
|
+
}
|
|
574
531
|
},
|
|
575
532
|
/**
|
|
576
533
|
* Starts WebView before any WebView mounts, so the first WebView mounts sooner.
|
|
@@ -1,10 +1,22 @@
|
|
|
1
1
|
import type { Bridge, BridgeOptions, BridgeSchema, BridgeSender, SchemaOf } from '../types';
|
|
2
2
|
import { DEFAULTS } from '../types.defaults';
|
|
3
3
|
import { codedError, createEndpoint } from './endpoint';
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
4
|
+
import { originGuard } from './origins';
|
|
5
|
+
import { PAGE_CLIENT } from './pageClient.generated';
|
|
6
6
|
import { type BridgeMessage, parseBridgeMessage } from './protocol';
|
|
7
7
|
|
|
8
|
+
/**
|
|
9
|
+
* What native reports to the bridge: a page's message with its origin as native verified it (`location.origin` form);
|
|
10
|
+
* a new document committed, so messages queue until its page client says `ready`; the renderer crashed, so no document
|
|
11
|
+
* is shown until the next commit; or the platform lacks the WebView features the bridge needs, so calls reject with
|
|
12
|
+
* `unavailable`.
|
|
13
|
+
*/
|
|
14
|
+
export type BridgeEvent =
|
|
15
|
+
| { message: string; origin: string }
|
|
16
|
+
| { navigated: true }
|
|
17
|
+
| { crashed: true }
|
|
18
|
+
| { unavailable: true };
|
|
19
|
+
|
|
8
20
|
/** What `<WebView>` needs from a bridge: `Bridge`'s `[CONNECTION]`, a key the package doesn't export. */
|
|
9
21
|
export type BridgeConnection = {
|
|
10
22
|
allowedOrigins: string[];
|
|
@@ -12,31 +24,11 @@ export type BridgeConnection = {
|
|
|
12
24
|
script: string;
|
|
13
25
|
attach(post: (message: string) => void): void;
|
|
14
26
|
detach(): void;
|
|
15
|
-
|
|
16
|
-
receive(message: string, origin: string): void;
|
|
17
|
-
/** The platform lacks the WebView features the bridge needs: calls reject with `unavailable`. */
|
|
18
|
-
markUnavailable(): void;
|
|
19
|
-
/** A new document committed: queue messages until its page client says `ready`. */
|
|
20
|
-
navigated(): void;
|
|
27
|
+
receive(event: BridgeEvent): void;
|
|
21
28
|
};
|
|
22
29
|
|
|
23
30
|
export const CONNECTION = Symbol('bridgeConnection');
|
|
24
31
|
|
|
25
|
-
/**
|
|
26
|
-
* A page-side expression true where `location.origin` matches `origins`, or null when they include `*`. Throws an
|
|
27
|
-
* `Error` starting with `what` for a rule that is neither `*` nor what `parseOrigin` takes.
|
|
28
|
-
*/
|
|
29
|
-
export function originGuard(what: string, origins: string[]): string | null {
|
|
30
|
-
const invalid = invalidOrigins(origins);
|
|
31
|
-
if (invalid.length) {
|
|
32
|
-
throw new Error(
|
|
33
|
-
`${what} ${JSON.stringify(invalid)} (use https://example.com or https://*.example.com, no path)`
|
|
34
|
-
);
|
|
35
|
-
}
|
|
36
|
-
const forms = originForms(origins);
|
|
37
|
-
return forms.any ? null : `(${MATCHES_ORIGIN})(${JSON.stringify(forms)}, location.origin)`;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
32
|
const MAX_QUEUE = 1000;
|
|
41
33
|
|
|
42
34
|
/**
|
|
@@ -60,21 +52,15 @@ export function createBridge<Schema extends SchemaOf<Schema> = BridgeSchema>(
|
|
|
60
52
|
);
|
|
61
53
|
}
|
|
62
54
|
let post: ((message: string) => void) | null = null;
|
|
63
|
-
// idle: no document committed since attach. loading: one committed and hasn't said `ready` yet.
|
|
55
|
+
// idle: no document shown (none committed since attach, or it crashed). loading: one committed and hasn't said `ready` yet.
|
|
64
56
|
let phase: 'idle' | 'loading' | 'ready' = 'idle';
|
|
65
57
|
// The token of the document that last said `ready` (protocol.ts `doc`).
|
|
66
58
|
let doc: string | undefined;
|
|
67
|
-
// Messages for the next document that says `ready`. Only the latest document's: see
|
|
59
|
+
// Messages for the next document that says `ready`. Only the latest document's: see `receive`.
|
|
68
60
|
let queue: BridgeMessage[] = [];
|
|
69
61
|
let unavailable = false;
|
|
70
62
|
|
|
71
|
-
const deliver = (message: BridgeMessage) => {
|
|
72
|
-
post?.(JSON.stringify({ ...message, doc }));
|
|
73
|
-
if (message.kind === 'call') {
|
|
74
|
-
const call = endpoint.pending.get(message.id);
|
|
75
|
-
if (call) call.sent = true;
|
|
76
|
-
}
|
|
77
|
-
};
|
|
63
|
+
const deliver = (message: BridgeMessage) => post?.(JSON.stringify({ ...message, doc }));
|
|
78
64
|
|
|
79
65
|
const endpoint = createEndpoint<BridgeSender>(
|
|
80
66
|
(message) => {
|
|
@@ -84,26 +70,29 @@ export function createBridge<Schema extends SchemaOf<Schema> = BridgeSchema>(
|
|
|
84
70
|
JSON.stringify(message);
|
|
85
71
|
queue.push(message);
|
|
86
72
|
const dropped = queue.length > MAX_QUEUE ? queue.shift() : undefined;
|
|
87
|
-
if (dropped?.kind === 'call')
|
|
88
|
-
const call = endpoint.pending.get(dropped.id);
|
|
73
|
+
if (dropped?.kind === 'call')
|
|
89
74
|
endpoint.rejectPending(
|
|
90
75
|
'unavailable',
|
|
91
76
|
'the bridge queue was full',
|
|
92
|
-
(
|
|
77
|
+
(id) => id === dropped.id
|
|
93
78
|
);
|
|
94
|
-
}
|
|
95
79
|
}
|
|
96
80
|
},
|
|
97
81
|
timeoutMs,
|
|
98
82
|
'n'
|
|
99
83
|
);
|
|
100
84
|
|
|
101
|
-
|
|
102
|
-
|
|
85
|
+
// A pending call not in the queue was posted to a document.
|
|
86
|
+
const rejectSent = (message: string) => {
|
|
87
|
+
const queued = new Set(
|
|
88
|
+
queue.map((queuedMessage) => queuedMessage.kind === 'call' && queuedMessage.id)
|
|
89
|
+
);
|
|
90
|
+
endpoint.rejectPending('navigated', message, (id) => !queued.has(id));
|
|
91
|
+
};
|
|
103
92
|
const unavailableMessage =
|
|
104
93
|
'this WebView lacks the features the bridge needs; update Android System WebView';
|
|
105
94
|
|
|
106
|
-
const
|
|
95
|
+
const receiveMessage = (text: string, origin: string) => {
|
|
107
96
|
const message = parseBridgeMessage(text);
|
|
108
97
|
if (typeof message === 'string') {
|
|
109
98
|
if (__DEV__)
|
|
@@ -143,24 +132,27 @@ export function createBridge<Schema extends SchemaOf<Schema> = BridgeSchema>(
|
|
|
143
132
|
detach() {
|
|
144
133
|
post = null;
|
|
145
134
|
phase = 'idle';
|
|
135
|
+
rejectSent('the WebView went away');
|
|
146
136
|
queue = [];
|
|
147
|
-
endpoint.rejectPending('
|
|
137
|
+
endpoint.rejectPending('unavailable', 'the WebView went away');
|
|
148
138
|
},
|
|
149
|
-
receive
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
// carry over to an unrelated next one.
|
|
154
|
-
if (phase === 'loading') {
|
|
155
|
-
endpoint.rejectPending('navigated', 'the page navigated before the bridge was ready');
|
|
139
|
+
receive(event) {
|
|
140
|
+
if ('message' in event) receiveMessage(event.message, event.origin);
|
|
141
|
+
else if ('unavailable' in event) {
|
|
142
|
+
unavailable = true;
|
|
156
143
|
queue = [];
|
|
144
|
+
endpoint.rejectPending('unavailable', unavailableMessage);
|
|
145
|
+
} else {
|
|
146
|
+
rejectSent('the page navigated');
|
|
147
|
+
// The previous document never said `ready` (a page outside allowedOrigins): what was queued for it does not
|
|
148
|
+
// carry over to an unrelated next one.
|
|
149
|
+
if (phase === 'loading') {
|
|
150
|
+
endpoint.rejectPending('unavailable', 'the page navigated before the bridge was ready');
|
|
151
|
+
queue = [];
|
|
152
|
+
}
|
|
153
|
+
// What is queued after a crash is for the reload.
|
|
154
|
+
phase = 'crashed' in event ? 'idle' : 'loading';
|
|
157
155
|
}
|
|
158
|
-
phase = 'loading';
|
|
159
|
-
},
|
|
160
|
-
markUnavailable() {
|
|
161
|
-
unavailable = true;
|
|
162
|
-
queue = [];
|
|
163
|
-
endpoint.rejectPending('unavailable', unavailableMessage);
|
|
164
156
|
},
|
|
165
157
|
};
|
|
166
158
|
|
package/src/bridge/endpoint.ts
CHANGED
|
@@ -8,8 +8,6 @@ type Pending = {
|
|
|
8
8
|
resolve(value: unknown): void;
|
|
9
9
|
reject(error: Error): void;
|
|
10
10
|
timer: ReturnType<typeof setTimeout> | undefined;
|
|
11
|
-
/** Posted to a document, not just queued for the next one (RN). */
|
|
12
|
-
sent: boolean;
|
|
13
11
|
};
|
|
14
12
|
|
|
15
13
|
export const codedError = ({ code, message }: { code: ErrorCode; message: string }): CodedError =>
|
|
@@ -50,7 +48,7 @@ export function createEndpoint<Sender = void>(
|
|
|
50
48
|
Math.min(ms, 2 ** 31 - 1)
|
|
51
49
|
)
|
|
52
50
|
: undefined;
|
|
53
|
-
pending.set(id, { resolve, reject, timer
|
|
51
|
+
pending.set(id, { resolve, reject, timer });
|
|
54
52
|
try {
|
|
55
53
|
send({ id, kind: 'call', method, params });
|
|
56
54
|
} catch (error) {
|
|
@@ -74,9 +72,9 @@ export function createEndpoint<Sender = void>(
|
|
|
74
72
|
listeners.set(event, set.add(listener));
|
|
75
73
|
return () => set.delete(listener);
|
|
76
74
|
},
|
|
77
|
-
rejectPending(code: BridgeErrorCode, message: string, only?: (
|
|
75
|
+
rejectPending(code: BridgeErrorCode, message: string, only?: (id: string) => boolean) {
|
|
78
76
|
for (const [id, call] of pending) {
|
|
79
|
-
if (only && !only(
|
|
77
|
+
if (only && !only(id)) continue;
|
|
80
78
|
clearTimeout(call.timer);
|
|
81
79
|
call.reject(codedError({ code, message }));
|
|
82
80
|
pending.delete(id);
|
package/src/bridge/origins.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
// The origin rules in RN: parser,
|
|
2
|
-
//
|
|
1
|
+
// The origin rules in RN: parser, the guard that createBridge and injectedScripts put around page code, and the
|
|
2
|
+
// matcher whose text build-page-client.mts cuts out as MATCHES_ORIGIN for that guard.
|
|
3
|
+
import { MATCHES_ORIGIN } from './pageClient.generated';
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* An origin rule (`http(s)://host[:port]`, `http(s)://*.host[:port]`) or a `location.origin`, parsed; null for anything
|
|
@@ -18,10 +19,6 @@ export const parseOrigin = (text: string) => {
|
|
|
18
19
|
return { scheme, wildcard: !!wildcard, hostPort: `${host}${portSuffix}` };
|
|
19
20
|
};
|
|
20
21
|
|
|
21
|
-
/** The rules that are neither `*` nor what `parseOrigin` takes. */
|
|
22
|
-
export const invalidOrigins = (rules: string[]) =>
|
|
23
|
-
rules.filter((rule) => rule !== '*' && !parseOrigin(rule));
|
|
24
|
-
|
|
25
22
|
/** Origin rules in `location.origin` form, for `matchesOrigin`: exact origins, and wildcards as prefix and suffix. */
|
|
26
23
|
export type OriginForms = { any: boolean; exact: string[]; wild: [string, string][] };
|
|
27
24
|
|
|
@@ -59,3 +56,18 @@ export function matchesOrigin(forms: OriginForms, origin: string) {
|
|
|
59
56
|
}
|
|
60
57
|
return false;
|
|
61
58
|
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* A page-side expression true where `location.origin` matches `origins`, or null when they include `*`. Throws an
|
|
62
|
+
* `Error` starting with `what` for a rule that is neither `*` nor what `parseOrigin` takes.
|
|
63
|
+
*/
|
|
64
|
+
export function originGuard(what: string, origins: string[]): string | null {
|
|
65
|
+
const invalid = origins.filter((rule) => rule !== '*' && !parseOrigin(rule));
|
|
66
|
+
if (invalid.length) {
|
|
67
|
+
throw new Error(
|
|
68
|
+
`${what} ${JSON.stringify(invalid)} (use https://example.com or https://*.example.com, no path)`
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
const forms = originForms(origins);
|
|
72
|
+
return forms.any ? null : `(${MATCHES_ORIGIN})(${JSON.stringify(forms)}, location.origin)`;
|
|
73
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Generated by .github/scripts/build-page-client.mts from pageClient.ts, endpoint.ts and origins.ts. Do not edit.
|
|
2
2
|
export const PAGE_CLIENT =
|
|
3
|
-
"function (w, timeoutMs) {\nconst codedError = ({ code, message }) => Object.assign(new Error(message), { code });\nfunction createEndpoint(send, timeoutMs, idPrefix) {\n const handlers = new Map();\n const listeners = new Map();\n const pending = new Map();\n let nextId = 0;\n return {\n pending,\n call(method, params, options) {\n const ms = options?.timeoutMs ?? timeoutMs;\n if (!(ms >= 0))\n return Promise.reject(new RangeError(`${method}: timeoutMs must be 0 or more, not ${ms}`));\n const id = `${idPrefix}${++nextId}`;\n return new Promise((resolve, reject) => {\n const timer = ms > 0 && ms < Infinity\n ? setTimeout(() => {\n pending.delete(id);\n reject(codedError({ code: 'timeout', message: `${method} timed out after ${ms} ms` }));\n }, Math.min(ms, 2 ** 31 - 1))\n : undefined;\n pending.set(id, { resolve, reject, timer
|
|
3
|
+
"function (w, timeoutMs) {\nconst codedError = ({ code, message }) => Object.assign(new Error(message), { code });\nfunction createEndpoint(send, timeoutMs, idPrefix) {\n const handlers = new Map();\n const listeners = new Map();\n const pending = new Map();\n let nextId = 0;\n return {\n pending,\n call(method, params, options) {\n const ms = options?.timeoutMs ?? timeoutMs;\n if (!(ms >= 0))\n return Promise.reject(new RangeError(`${method}: timeoutMs must be 0 or more, not ${ms}`));\n const id = `${idPrefix}${++nextId}`;\n return new Promise((resolve, reject) => {\n const timer = ms > 0 && ms < Infinity\n ? setTimeout(() => {\n pending.delete(id);\n reject(codedError({ code: 'timeout', message: `${method} timed out after ${ms} ms` }));\n }, Math.min(ms, 2 ** 31 - 1))\n : undefined;\n pending.set(id, { resolve, reject, timer });\n try {\n send({ id, kind: 'call', method, params });\n }\n catch (error) {\n clearTimeout(timer);\n pending.delete(id);\n throw error;\n }\n });\n },\n emit(event, payload) {\n send({ kind: 'event', method: event, params: payload });\n },\n handle(method, handler) {\n handlers.set(method, handler);\n return () => {\n if (handlers.get(method) === handler)\n handlers.delete(method);\n };\n },\n on(event, listener) {\n const set = listeners.get(event) ?? new Set();\n listeners.set(event, set.add(listener));\n return () => set.delete(listener);\n },\n rejectPending(code, message, only) {\n for (const [id, call] of pending) {\n if (only && !only(id))\n continue;\n clearTimeout(call.timer);\n call.reject(codedError({ code, message }));\n pending.delete(id);\n }\n },\n async receive(message, reply, sender) {\n switch (message.kind) {\n case 'call': {\n const { id, method } = message;\n const fail = (code, text) => reply({ id, kind: 'error', error: { code, message: text } });\n const handler = handlers.get(method);\n if (!handler)\n return fail('not_found', `no handler for ${method}`);\n try {\n reply({ id, kind: 'result', value: await handler(message.params, sender) });\n }\n catch (error) {\n fail('handler_error', error instanceof Error ? error.message : String(error));\n }\n return;\n }\n case 'event':\n listeners.get(message.method)?.forEach((listener) => {\n try {\n listener(message.params, sender);\n }\n catch (error) {\n void Promise.reject(error);\n }\n });\n return;\n case 'result':\n case 'error': {\n const call = pending.get(message.id);\n if (!call)\n return;\n pending.delete(message.id);\n clearTimeout(call.timer);\n if (message.kind === 'result')\n call.resolve(message.value);\n else\n call.reject(codedError(message.error));\n }\n }\n },\n };\n}\nfunction installPageClient(w, timeoutMs) {\n if (w.nativeBridge || w !== w.top)\n return;\n const doc = Math.random().toString(36).slice(2, 10);\n const ios = w.webkit?.messageHandlers?.nativeBridge;\n const android = w.nativeBridgeTransport;\n const send = (message) => {\n const text = JSON.stringify({ ...message, doc });\n (ios ?? android)?.postMessage(text);\n };\n const endpoint = createEndpoint(send, timeoutMs, 'p');\n const receive = async (text) => {\n const message = JSON.parse(text);\n if (message.doc === doc)\n await endpoint.receive(message, send);\n };\n if (android)\n android.onmessage = (event) => void receive(event.data);\n w.nativeBridge = Object.freeze({\n call: endpoint.call,\n emit: endpoint.emit,\n handle: endpoint.handle,\n on: endpoint.on,\n __receive: receive,\n });\n if (w.document.readyState === 'loading') {\n w.document.addEventListener('DOMContentLoaded', () => send({ kind: 'ready' }), {\n once: true,\n });\n }\n else {\n send({ kind: 'ready' });\n }\n w.addEventListener('pageshow', (event) => {\n if (!event.persisted)\n return;\n endpoint.rejectPending('navigated', 'the page was left before the call was answered');\n send({ kind: 'ready' });\n });\n}\nreturn installPageClient(w, timeoutMs);\n}";
|
|
4
4
|
export const MATCHES_ORIGIN =
|
|
5
5
|
"(() => {\nfunction hasAt(text, part, at) {\n for (let k = 0; k < part.length; k++)\n if (text[at + k] !== part[k])\n return false;\n return true;\n}\nfunction matchesOrigin(forms, origin) {\n if (forms.any)\n return true;\n for (let i = 0; i < forms.exact.length; i++)\n if (forms.exact[i] === origin)\n return true;\n for (let i = 0; i < forms.wild.length; i++) {\n const prefix = forms.wild[i][0];\n const suffix = forms.wild[i][1];\n const start = origin.length - suffix.length;\n if (start > prefix.length && hasAt(origin, prefix, 0) && hasAt(origin, suffix, start))\n return true;\n }\n return false;\n}\nreturn matchesOrigin;\n})()";
|
package/src/index.ts
CHANGED
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
export { AndroidWebView, WebView } from './WebView';
|
|
24
24
|
export { createWebViewRef, useWebViewState } from './refStore';
|
|
25
25
|
export { createBridge } from './bridge/createBridge';
|
|
26
|
-
export { defaultNavigationRules } from './
|
|
26
|
+
export { defaultNavigationRules } from './navigationRules';
|
|
27
27
|
export { reactNativeWebViewMessages } from './reactNativeWebViewMessages';
|
|
28
28
|
export { AndroidConstants, IOSConstants } from './platform.generated';
|
|
29
29
|
export type {
|