react-native-minimal-webview 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.md +150 -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 +487 -0
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +507 -0
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +358 -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 +197 -0
- package/android/src/main/java/expo/modules/minimalwebview/NavigationRules.kt +113 -0
- package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +303 -0
- package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +76 -0
- package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +259 -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 +96 -0
- package/build/WebView.d.ts.map +1 -0
- package/build/WebView.js +453 -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 +137 -0
- package/build/bridge/createBridge.js.map +1 -0
- package/build/bridge/endpoint.d.ts +33 -0
- package/build/bridge/endpoint.d.ts.map +1 -0
- package/build/bridge/endpoint.js +105 -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 +59 -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 +15 -0
- package/build/defaultNavigationRules.d.ts.map +1 -0
- package/build/defaultNavigationRules.js +22 -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 +701 -0
- package/build/platform.generated.d.ts.map +1 -0
- package/build/platform.generated.js +201 -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 +16 -0
- package/build/reactNativeWebViewMessages.d.ts.map +1 -0
- package/build/reactNativeWebViewMessages.js +24 -0
- package/build/reactNativeWebViewMessages.js.map +1 -0
- package/build/refStore.d.ts +32 -0
- package/build/refStore.d.ts.map +1 -0
- package/build/refStore.js +115 -0
- package/build/refStore.js.map +1 -0
- package/build/types.d.ts +1173 -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 +158 -0
- package/ios/DocumentEnd.swift +22 -0
- package/ios/DownloadName.swift +10 -0
- package/ios/Downloads.swift +51 -0
- package/ios/Hooks.swift +310 -0
- package/ios/Loads.swift +44 -0
- package/ios/MRWExceptions.h +9 -0
- package/ios/MRWExceptions.m +10 -0
- package/ios/MRWInvoke.h +38 -0
- package/ios/MRWInvoke.m +187 -0
- package/ios/MinimalWebView+Dialogs.swift +96 -0
- package/ios/MinimalWebView+Navigation.swift +243 -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 +513 -0
- package/ios/MinimalWebViewModule.swift +110 -0
- package/ios/NavigationRules.swift +123 -0
- package/ios/OriginRules.swift +36 -0
- package/ios/PlatformCompletions.generated.swift +39 -0
- package/ios/PlatformSettings.swift +252 -0
- package/ios/ReadAccess.swift +19 -0
- package/ios/Recovery.swift +25 -0
- package/ios/SharedCookies.swift +59 -0
- package/package.json +99 -4
- package/src/WebView.tsx +626 -0
- package/src/bridge/createBridge.ts +178 -0
- package/src/bridge/endpoint.ts +123 -0
- package/src/bridge/origins.ts +61 -0
- package/src/bridge/pageClient.generated.ts +5 -0
- package/src/bridge/pageClient.ts +67 -0
- package/src/bridge/protocol.ts +78 -0
- package/src/defaultNavigationRules.ts +24 -0
- package/src/index.ts +37 -0
- package/src/platform.generated.ts +693 -0
- package/src/reactNativeWebViewDefaults.ts +13 -0
- package/src/reactNativeWebViewMessages.ts +26 -0
- package/src/refStore.ts +165 -0
- package/src/types.defaults.ts +24 -0
- package/src/types.ts +1240 -0
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import type { Bridge, BridgeOptions, BridgeSchema, BridgeSender } from '../types';
|
|
2
|
+
import { DEFAULTS } from '../types.defaults';
|
|
3
|
+
import { codedError, createEndpoint } from './endpoint';
|
|
4
|
+
import { invalidOrigins, originForms } from './origins';
|
|
5
|
+
import { MATCHES_ORIGIN, PAGE_CLIENT } from './pageClient.generated';
|
|
6
|
+
import { type BridgeMessage, parseBridgeMessage } from './protocol';
|
|
7
|
+
|
|
8
|
+
/** What `<WebView>` needs from a bridge: `Bridge`'s `[CONNECTION]`, a key the package doesn't export. */
|
|
9
|
+
export type BridgeConnection = {
|
|
10
|
+
allowedOrigins: string[];
|
|
11
|
+
/** The page client to inject at document start. */
|
|
12
|
+
script: string;
|
|
13
|
+
attach(post: (message: string) => void): void;
|
|
14
|
+
detach(): void;
|
|
15
|
+
/** A message from the page, and its origin as native verified it. */
|
|
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;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export const CONNECTION = Symbol('bridgeConnection');
|
|
24
|
+
|
|
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
|
+
const MAX_QUEUE = 1000;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Creates a {@link Bridge} to the pages of `allowedOrigins`, for one WebView's `bridge` prop.
|
|
44
|
+
*
|
|
45
|
+
* The type argument, a {@link BridgeSchema}, types the methods and events of `handle`, `call`, `emit` and `on`.
|
|
46
|
+
* Nothing checks them at runtime, so a handler still validates what an untrusted page sends. Throws an `Error` for an
|
|
47
|
+
* invalid origin rule or timeout.
|
|
48
|
+
* @see [Bridge example](https://rasmuskard.github.io/react-native-minimal-webview/guides/examples/#the-bridge)
|
|
49
|
+
* @group Bridge
|
|
50
|
+
*/
|
|
51
|
+
export function createBridge<Schema extends BridgeSchema = BridgeSchema>(
|
|
52
|
+
options: BridgeOptions
|
|
53
|
+
): Bridge<Schema> {
|
|
54
|
+
// `*` or what origins.ts parses: addWebMessageListener's rules minus custom schemes.
|
|
55
|
+
const guard = originGuard('createBridge: invalid allowedOrigins', options.allowedOrigins);
|
|
56
|
+
const timeoutMs = options.timeoutMs ?? DEFAULTS.BridgeOptions.timeoutMs;
|
|
57
|
+
if (!(timeoutMs >= 0)) {
|
|
58
|
+
throw new Error(
|
|
59
|
+
`createBridge: timeoutMs must be 0 or more (0 or Infinity for none), not ${timeoutMs}`
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
let post: ((message: string) => void) | null = null;
|
|
63
|
+
// idle: no document committed since attach. loading: one committed and hasn't said `ready` yet.
|
|
64
|
+
let phase: 'idle' | 'loading' | 'ready' = 'idle';
|
|
65
|
+
// The token of the document that last said `ready` (protocol.ts `doc`).
|
|
66
|
+
let doc: string | undefined;
|
|
67
|
+
// Messages for the next document that says `ready`. Only the latest document's: see navigated().
|
|
68
|
+
let queue: BridgeMessage[] = [];
|
|
69
|
+
let unavailable = false;
|
|
70
|
+
|
|
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
|
+
};
|
|
78
|
+
|
|
79
|
+
const endpoint = createEndpoint<BridgeSender>(
|
|
80
|
+
(message) => {
|
|
81
|
+
if (post && phase === 'ready') deliver(message);
|
|
82
|
+
else {
|
|
83
|
+
// Throws now, at the caller, for what JSON can't encode, rather than in the flush, losing the rest of the queue.
|
|
84
|
+
JSON.stringify(message);
|
|
85
|
+
queue.push(message);
|
|
86
|
+
const dropped = queue.length > MAX_QUEUE ? queue.shift() : undefined;
|
|
87
|
+
if (dropped?.kind === 'call') {
|
|
88
|
+
const call = endpoint.pending.get(dropped.id);
|
|
89
|
+
endpoint.rejectPending(
|
|
90
|
+
'unavailable',
|
|
91
|
+
'the bridge queue was full',
|
|
92
|
+
(pending) => pending === call
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
},
|
|
97
|
+
timeoutMs,
|
|
98
|
+
'n'
|
|
99
|
+
);
|
|
100
|
+
|
|
101
|
+
const rejectSent = (message: string) =>
|
|
102
|
+
endpoint.rejectPending('navigated', message, (call) => call.sent);
|
|
103
|
+
const unavailableMessage =
|
|
104
|
+
'this WebView lacks the features the bridge needs; update Android System WebView';
|
|
105
|
+
|
|
106
|
+
const receive = (text: string, origin: string) => {
|
|
107
|
+
const message = parseBridgeMessage(text);
|
|
108
|
+
if (typeof message === 'string') {
|
|
109
|
+
if (__DEV__)
|
|
110
|
+
console.warn(`[react-native-minimal-webview] dropped a bridge message: ${message}`);
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
if (message.kind !== 'ready') {
|
|
114
|
+
// Answers skip the ready queue: a module script may await one before DOMContentLoaded, and native can deliver
|
|
115
|
+
// it, as the page has posted.
|
|
116
|
+
const reply = (answer: BridgeMessage) =>
|
|
117
|
+
post?.(JSON.stringify({ ...answer, doc: message.doc }));
|
|
118
|
+
void endpoint.receive(message, reply, { origin });
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
// A new document: calls posted to the previous one can no longer be answered. Queued ones are for this one.
|
|
122
|
+
rejectSent('the page navigated');
|
|
123
|
+
phase = 'ready';
|
|
124
|
+
doc = message.doc;
|
|
125
|
+
const flushing = queue;
|
|
126
|
+
queue = [];
|
|
127
|
+
// A queued call that already timed out is not sent: nobody waits for its answer.
|
|
128
|
+
for (const queued of flushing)
|
|
129
|
+
if (queued.kind !== 'call' || endpoint.pending.has(queued.id)) deliver(queued);
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
const connection: BridgeConnection = {
|
|
133
|
+
allowedOrigins: options.allowedOrigins,
|
|
134
|
+
script: `${guard ? `if (${guard}) ` : ''}(${PAGE_CLIENT})(window, ${Number(timeoutMs)});`,
|
|
135
|
+
attach(next) {
|
|
136
|
+
// Two WebViews would steal each other's replies, and either one's detach would cut off the other.
|
|
137
|
+
if (post)
|
|
138
|
+
throw new Error(
|
|
139
|
+
'createBridge: this bridge is already attached to a mounted WebView; give each WebView its own bridge'
|
|
140
|
+
);
|
|
141
|
+
post = next;
|
|
142
|
+
},
|
|
143
|
+
detach() {
|
|
144
|
+
post = null;
|
|
145
|
+
phase = 'idle';
|
|
146
|
+
queue = [];
|
|
147
|
+
endpoint.rejectPending('navigated', 'the WebView went away');
|
|
148
|
+
},
|
|
149
|
+
receive,
|
|
150
|
+
navigated() {
|
|
151
|
+
rejectSent('the page navigated');
|
|
152
|
+
// The previous document never said `ready` (a page outside allowedOrigins): what was queued for it does not
|
|
153
|
+
// carry over to an unrelated next one.
|
|
154
|
+
if (phase === 'loading') {
|
|
155
|
+
endpoint.rejectPending('navigated', 'the page navigated before the bridge was ready');
|
|
156
|
+
queue = [];
|
|
157
|
+
}
|
|
158
|
+
phase = 'loading';
|
|
159
|
+
},
|
|
160
|
+
markUnavailable() {
|
|
161
|
+
unavailable = true;
|
|
162
|
+
queue = [];
|
|
163
|
+
endpoint.rejectPending('unavailable', unavailableMessage);
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
return {
|
|
168
|
+
handle: endpoint.handle,
|
|
169
|
+
call(method, params, callOptions) {
|
|
170
|
+
if (unavailable)
|
|
171
|
+
return Promise.reject(codedError({ code: 'unavailable', message: unavailableMessage }));
|
|
172
|
+
return endpoint.call(method, params, callOptions);
|
|
173
|
+
},
|
|
174
|
+
emit: endpoint.emit,
|
|
175
|
+
on: endpoint.on,
|
|
176
|
+
[CONNECTION]: connection,
|
|
177
|
+
} as Bridge as unknown as Bridge<Schema>; // the schema types only what callers pass
|
|
178
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// One side of the bridge, the same in RN (createBridge.ts) and in the page (pageClient.ts): calls with timeouts,
|
|
2
|
+
// handlers and events. The transport, the `ready` handshake and the document tokens are each side's own. The page
|
|
3
|
+
// client is compiled with this file into one script (.github/scripts/build-page-client.mts), so it imports only types.
|
|
4
|
+
import type { ErrorCode } from '../types';
|
|
5
|
+
import type { BridgeErrorCode, BridgeMessage } from './protocol';
|
|
6
|
+
|
|
7
|
+
type Pending = {
|
|
8
|
+
resolve(value: unknown): void;
|
|
9
|
+
reject(error: Error): void;
|
|
10
|
+
timer: ReturnType<typeof setTimeout> | undefined;
|
|
11
|
+
/** Posted to a document, not just queued for the next one (RN). */
|
|
12
|
+
sent: boolean;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/** A `CodedError` (types.ts): what a ref method or bridge call rejects with. */
|
|
16
|
+
export const codedError = ({ code, message }: { code: ErrorCode; message: string }) =>
|
|
17
|
+
Object.assign(new Error(message), { code });
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* `send` posts a message to the other side; ids get `idPrefix`, so the two sides' calls never share an id. `Sender` is
|
|
21
|
+
* what handlers and listeners get beside the params: RN's `{ origin }`, nothing in the page.
|
|
22
|
+
*/
|
|
23
|
+
export function createEndpoint<Sender = void>(
|
|
24
|
+
send: (message: BridgeMessage) => void,
|
|
25
|
+
timeoutMs: number,
|
|
26
|
+
idPrefix: string
|
|
27
|
+
) {
|
|
28
|
+
const handlers = new Map<string, (params: unknown, sender: Sender) => unknown>();
|
|
29
|
+
const listeners = new Map<string, Set<(payload: unknown, sender: Sender) => void>>();
|
|
30
|
+
const pending = new Map<string, Pending>();
|
|
31
|
+
let nextId = 0;
|
|
32
|
+
|
|
33
|
+
return {
|
|
34
|
+
pending,
|
|
35
|
+
call(method: string, params?: unknown, options?: { timeoutMs?: number }) {
|
|
36
|
+
const ms = options?.timeoutMs ?? timeoutMs;
|
|
37
|
+
if (!(ms >= 0))
|
|
38
|
+
return Promise.reject(new RangeError(`${method}: timeoutMs must be 0 or more, not ${ms}`));
|
|
39
|
+
const id = `${idPrefix}${++nextId}`;
|
|
40
|
+
return new Promise<unknown>((resolve, reject) => {
|
|
41
|
+
// Clamped: setTimeout fires at once for a delay above 2^31-1.
|
|
42
|
+
const timer =
|
|
43
|
+
ms > 0 && ms < Infinity
|
|
44
|
+
? setTimeout(
|
|
45
|
+
() => {
|
|
46
|
+
pending.delete(id);
|
|
47
|
+
reject(
|
|
48
|
+
codedError({ code: 'timeout', message: `${method} timed out after ${ms} ms` })
|
|
49
|
+
);
|
|
50
|
+
},
|
|
51
|
+
Math.min(ms, 2 ** 31 - 1)
|
|
52
|
+
)
|
|
53
|
+
: undefined;
|
|
54
|
+
pending.set(id, { resolve, reject, timer, sent: false });
|
|
55
|
+
try {
|
|
56
|
+
send({ id, kind: 'call', method, params });
|
|
57
|
+
} catch (error) {
|
|
58
|
+
clearTimeout(timer);
|
|
59
|
+
pending.delete(id);
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
},
|
|
64
|
+
emit(event: string, payload?: unknown) {
|
|
65
|
+
send({ kind: 'event', method: event, params: payload });
|
|
66
|
+
},
|
|
67
|
+
handle(method: string, handler: (params: unknown, sender: Sender) => unknown) {
|
|
68
|
+
handlers.set(method, handler);
|
|
69
|
+
return () => {
|
|
70
|
+
if (handlers.get(method) === handler) handlers.delete(method);
|
|
71
|
+
};
|
|
72
|
+
},
|
|
73
|
+
on(event: string, listener: (payload: unknown, sender: Sender) => void) {
|
|
74
|
+
const set = listeners.get(event) ?? new Set();
|
|
75
|
+
listeners.set(event, set.add(listener));
|
|
76
|
+
return () => set.delete(listener);
|
|
77
|
+
},
|
|
78
|
+
rejectPending(code: BridgeErrorCode, message: string, only?: (call: Pending) => boolean) {
|
|
79
|
+
for (const [id, call] of pending) {
|
|
80
|
+
if (only && !only(call)) continue;
|
|
81
|
+
clearTimeout(call.timer);
|
|
82
|
+
call.reject(codedError({ code, message }));
|
|
83
|
+
pending.delete(id);
|
|
84
|
+
}
|
|
85
|
+
},
|
|
86
|
+
async receive(message: BridgeMessage, reply: (message: BridgeMessage) => void, sender: Sender) {
|
|
87
|
+
switch (message.kind) {
|
|
88
|
+
case 'call': {
|
|
89
|
+
const { id, method } = message;
|
|
90
|
+
const fail = (code: BridgeErrorCode, text: string) =>
|
|
91
|
+
reply({ id, kind: 'error', error: { code, message: text } });
|
|
92
|
+
const handler = handlers.get(method);
|
|
93
|
+
if (!handler) return fail('not_found', `no handler for ${method}`);
|
|
94
|
+
try {
|
|
95
|
+
reply({ id, kind: 'result', value: await handler(message.params, sender) });
|
|
96
|
+
} catch (error) {
|
|
97
|
+
fail('handler_error', error instanceof Error ? error.message : String(error));
|
|
98
|
+
}
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
case 'event':
|
|
102
|
+
listeners.get(message.method)?.forEach((listener) => {
|
|
103
|
+
// An unhandled rejection reports the error without stopping the other listeners.
|
|
104
|
+
try {
|
|
105
|
+
listener(message.params, sender);
|
|
106
|
+
} catch (error) {
|
|
107
|
+
void Promise.reject(error);
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
return;
|
|
111
|
+
case 'result':
|
|
112
|
+
case 'error': {
|
|
113
|
+
const call = pending.get(message.id);
|
|
114
|
+
if (!call) return;
|
|
115
|
+
pending.delete(message.id);
|
|
116
|
+
clearTimeout(call.timer);
|
|
117
|
+
if (message.kind === 'result') call.resolve(message.value);
|
|
118
|
+
else call.reject(codedError(message.error));
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
},
|
|
122
|
+
};
|
|
123
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// The origin rules in RN: parser, validator, and the matcher whose text build-page-client.mts cuts out as MATCHES_ORIGIN
|
|
2
|
+
// for the guards that createBridge and injectedScripts put around page code.
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* An origin rule (`http(s)://host[:port]`, `http(s)://*.host[:port]`) or a `location.origin`, parsed; null for anything
|
|
6
|
+
* else, `*` included. OriginRules.swift matches the same way: both run src/__tests__/vectors/origin-rules.json.
|
|
7
|
+
*/
|
|
8
|
+
export const parseOrigin = (text: string) => {
|
|
9
|
+
const m =
|
|
10
|
+
/^(https?):\/\/(\*\.(?!\[))?([a-z0-9_-]+(?:\.[a-z0-9_-]+)*|\[[0-9a-f:.]+\])(?::(\d{1,5}))?$/.exec(
|
|
11
|
+
text.toLowerCase()
|
|
12
|
+
);
|
|
13
|
+
if (!m) return null;
|
|
14
|
+
const [, scheme, wildcard, host, port] = m;
|
|
15
|
+
// `location.origin` leaves out the scheme's default port.
|
|
16
|
+
const isDefaultPort = port === undefined || +port === (scheme === 'https' ? 443 : 80);
|
|
17
|
+
const portSuffix = isDefaultPort ? '' : `:${+port!}`;
|
|
18
|
+
return { scheme, wildcard: !!wildcard, hostPort: `${host}${portSuffix}` };
|
|
19
|
+
};
|
|
20
|
+
|
|
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
|
+
/** Origin rules in `location.origin` form, for `matchesOrigin`: exact origins, and wildcards as prefix and suffix. */
|
|
26
|
+
export type OriginForms = { any: boolean; exact: string[]; wild: [string, string][] };
|
|
27
|
+
|
|
28
|
+
/** `rules` in the form `matchesOrigin` compares; a rule `parseOrigin` rejects is left out, so it matches nothing. */
|
|
29
|
+
export const originForms = (rules: string[]): OriginForms => {
|
|
30
|
+
const forms: OriginForms = { any: rules.includes('*'), exact: [], wild: [] };
|
|
31
|
+
for (const rule of rules) {
|
|
32
|
+
const r = parseOrigin(rule);
|
|
33
|
+
if (!r) continue;
|
|
34
|
+
if (r.wildcard) forms.wild.push([`${r.scheme}://`, `.${r.hostPort}`]);
|
|
35
|
+
else forms.exact.push(`${r.scheme}://${r.hostPort}`);
|
|
36
|
+
}
|
|
37
|
+
return forms;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
function hasAt(text: string, part: string, at: number) {
|
|
41
|
+
for (let k = 0; k < part.length; k++) if (text[at + k] !== part[k]) return false;
|
|
42
|
+
return true;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Whether `origin`, as `location.origin` serializes it, matches `forms`. Only `===`, indexing and `length`, no
|
|
47
|
+
* built-in method: it runs at document start in frames whose built-ins another same-origin frame may have patched.
|
|
48
|
+
*/
|
|
49
|
+
export function matchesOrigin(forms: OriginForms, origin: string) {
|
|
50
|
+
if (forms.any) return true;
|
|
51
|
+
for (let i = 0; i < forms.exact.length; i++) if (forms.exact[i] === origin) return true;
|
|
52
|
+
for (let i = 0; i < forms.wild.length; i++) {
|
|
53
|
+
const prefix = forms.wild[i]![0];
|
|
54
|
+
const suffix = forms.wild[i]![1];
|
|
55
|
+
const start = origin.length - suffix.length;
|
|
56
|
+
// At least one character of subdomain between the two.
|
|
57
|
+
if (start > prefix.length && hasAt(origin, prefix, 0) && hasAt(origin, suffix, start))
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// Generated by .github/scripts/build-page-client.mts from pageClient.ts, endpoint.ts and origins.ts. Do not edit.
|
|
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, sent: false });\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(call))\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
|
+
export const MATCHES_ORIGIN =
|
|
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})()";
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// The page side of the bridge: installs `window.nativeBridge`. It runs inside the web page, so
|
|
2
|
+
// .github/scripts/build-page-client.mts compiles it, with ./endpoint.ts, into the PAGE_CLIENT string that native
|
|
3
|
+
// injects at document start. Each direction is a plain pipe: page -> native through `postMessage` (iOS
|
|
4
|
+
// WKScriptMessageHandler at `webkit.messageHandlers.nativeBridge`, Android addWebMessageListener at
|
|
5
|
+
// `window.nativeBridgeTransport`), native -> page through `__receive` (iOS callAsyncJavaScript) or the transport's
|
|
6
|
+
// `onmessage` (Android). Messages follow ./protocol.ts; answers to either side's calls travel as ordinary messages.
|
|
7
|
+
import type { PageBridge } from '../types';
|
|
8
|
+
import { createEndpoint } from './endpoint';
|
|
9
|
+
import type { BridgeMessage as Message } from './protocol';
|
|
10
|
+
|
|
11
|
+
type PageWindow = Window & {
|
|
12
|
+
nativeBridge?: PageBridge & { __receive(text: string): Promise<void> };
|
|
13
|
+
nativeBridgeTransport?: {
|
|
14
|
+
postMessage(message: string): void;
|
|
15
|
+
onmessage: ((event: { data: string }) => void) | null;
|
|
16
|
+
};
|
|
17
|
+
webkit?: {
|
|
18
|
+
messageHandlers?: { nativeBridge?: { postMessage(message: string): void } };
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export function installPageClient(w: PageWindow, timeoutMs: number) {
|
|
23
|
+
// Main frame only (Android injects into allowed-origin iframes too, but only the main frame's messages are taken).
|
|
24
|
+
if (w.nativeBridge || w !== w.top) return;
|
|
25
|
+
// This document's token (protocol.ts `doc`).
|
|
26
|
+
const doc = Math.random().toString(36).slice(2, 10);
|
|
27
|
+
|
|
28
|
+
const ios = w.webkit?.messageHandlers?.nativeBridge;
|
|
29
|
+
const android = w.nativeBridgeTransport;
|
|
30
|
+
|
|
31
|
+
const send = (message: Message) => {
|
|
32
|
+
const text = JSON.stringify({ ...message, doc });
|
|
33
|
+
(ios ?? android)?.postMessage(text);
|
|
34
|
+
};
|
|
35
|
+
const endpoint = createEndpoint(send, timeoutMs, 'p');
|
|
36
|
+
|
|
37
|
+
const receive = async (text: string) => {
|
|
38
|
+
const message = JSON.parse(text) as Message;
|
|
39
|
+
if (message.doc === doc) await endpoint.receive(message, send);
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
if (android) android.onmessage = (event) => void receive(event.data);
|
|
43
|
+
|
|
44
|
+
w.nativeBridge = Object.freeze({
|
|
45
|
+
call: endpoint.call,
|
|
46
|
+
emit: endpoint.emit,
|
|
47
|
+
handle: endpoint.handle,
|
|
48
|
+
on: endpoint.on,
|
|
49
|
+
/** iOS's entry point, origin-checked there. */
|
|
50
|
+
__receive: receive,
|
|
51
|
+
});
|
|
52
|
+
// `ready` (protocol.ts) waits for DOMContentLoaded: a call delivered earlier would get `not_found`.
|
|
53
|
+
if (w.document.readyState === 'loading') {
|
|
54
|
+
w.document.addEventListener('DOMContentLoaded', () => send({ kind: 'ready' }), {
|
|
55
|
+
once: true,
|
|
56
|
+
});
|
|
57
|
+
} else {
|
|
58
|
+
send({ kind: 'ready' });
|
|
59
|
+
}
|
|
60
|
+
// Back from the back-forward cache: scripts don't run again, but native reset the bridge when the page was left, and
|
|
61
|
+
// answers to this page's calls went to the page shown meanwhile. Fail those calls and announce the page again.
|
|
62
|
+
w.addEventListener('pageshow', (event) => {
|
|
63
|
+
if (!event.persisted) return;
|
|
64
|
+
endpoint.rejectPending('navigated', 'the page was left before the call was answered');
|
|
65
|
+
send({ kind: 'ready' });
|
|
66
|
+
});
|
|
67
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// The bridge wire format. The RN side parses with it; the page client imports only its types.
|
|
2
|
+
import type { ErrorCode } from '../types';
|
|
3
|
+
|
|
4
|
+
/** The codes a bridge call rejects with: the page may send only these. */
|
|
5
|
+
const ERROR_CODES = [
|
|
6
|
+
'timeout',
|
|
7
|
+
'not_found',
|
|
8
|
+
'handler_error',
|
|
9
|
+
'navigated',
|
|
10
|
+
'unavailable',
|
|
11
|
+
] as const satisfies readonly ErrorCode[];
|
|
12
|
+
export type BridgeErrorCode = (typeof ERROR_CODES)[number];
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* `ready`: the page's DOM is parsed (DOMContentLoaded), so its scripts have registered handlers. RN holds its calls and
|
|
16
|
+
* events for the page until then (native can't deliver before the page has posted). A page's own calls and their
|
|
17
|
+
* answers don't wait for it.
|
|
18
|
+
* `call` / `result` / `error`: a request and its answer, matched by `id`.
|
|
19
|
+
* `event`: fire-and-forget, `method` is the event name.
|
|
20
|
+
*
|
|
21
|
+
* `doc` is the page document's random token. Each side puts a token on every message (RN the token of the document it
|
|
22
|
+
* means), and the page drops any message that isn't for it: native delivers to whatever document is current (iOS
|
|
23
|
+
* checks only the origin), so a message posted as a same-origin navigation commits would otherwise reach the new page.
|
|
24
|
+
* It is for correctness, not security: an allowed page can rebind its own client. Messages are built without it;
|
|
25
|
+
* `send` adds it.
|
|
26
|
+
*/
|
|
27
|
+
export type BridgeMessage = { doc?: string } & (
|
|
28
|
+
| { kind: 'ready' }
|
|
29
|
+
| { kind: 'call'; id: string; method: string; params?: unknown }
|
|
30
|
+
| { kind: 'result'; id: string; value?: unknown }
|
|
31
|
+
| { kind: 'error'; id: string; error: { code: BridgeErrorCode; message: string } }
|
|
32
|
+
| { kind: 'event'; method: string; params?: unknown }
|
|
33
|
+
);
|
|
34
|
+
|
|
35
|
+
const isObject = (value: unknown): value is Record<string, unknown> =>
|
|
36
|
+
typeof value === 'object' && value !== null;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Parses a message from the page, which always carries `doc`. Returns it, or the reason it was rejected. Never throws.
|
|
40
|
+
* An error `code` that isn't a `BridgeErrorCode` becomes `handler_error`: the page's handler failed somehow.
|
|
41
|
+
*/
|
|
42
|
+
export function parseBridgeMessage(raw: string): (BridgeMessage & { doc: string }) | string {
|
|
43
|
+
let value: unknown;
|
|
44
|
+
try {
|
|
45
|
+
value = JSON.parse(raw);
|
|
46
|
+
} catch {
|
|
47
|
+
return 'not JSON';
|
|
48
|
+
}
|
|
49
|
+
if (!isObject(value) || typeof value['doc'] !== 'string') return 'missing doc';
|
|
50
|
+
return kindProblem(value) ?? (value as BridgeMessage & { doc: string });
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function kindProblem(value: Record<string, unknown>): string | null {
|
|
54
|
+
const hasId = typeof value['id'] === 'string';
|
|
55
|
+
const hasMethod = typeof value['method'] === 'string' && value['method'] !== '';
|
|
56
|
+
switch (value['kind']) {
|
|
57
|
+
case 'ready':
|
|
58
|
+
return null;
|
|
59
|
+
case 'event':
|
|
60
|
+
return hasMethod ? null : 'missing method';
|
|
61
|
+
case 'call':
|
|
62
|
+
return hasId && hasMethod ? null : 'missing id or method';
|
|
63
|
+
case 'result':
|
|
64
|
+
return hasId ? null : 'missing id';
|
|
65
|
+
case 'error':
|
|
66
|
+
return !hasId ? 'missing id' : normalizeError(value['error']) ? null : 'malformed error';
|
|
67
|
+
default:
|
|
68
|
+
return 'unknown kind';
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Whether `error` is `{ code, message }`, both strings; an unlisted code is replaced in place. */
|
|
73
|
+
function normalizeError(error: unknown) {
|
|
74
|
+
if (!isObject(error) || typeof error['code'] !== 'string' || typeof error['message'] !== 'string')
|
|
75
|
+
return false;
|
|
76
|
+
if (!(ERROR_CODES as readonly string[]).includes(error['code'])) error['code'] = 'handler_error';
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { NavigationRule } from './types';
|
|
2
|
+
|
|
3
|
+
const freeze = <T extends object>(value: T): T => {
|
|
4
|
+
Object.values(value).forEach((field) => typeof field === 'object' && freeze(field as object));
|
|
5
|
+
return Object.freeze(value);
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The rules `navigationRules` has when it is unset: `file:` is blocked, http(s) loads in place, and any other scheme
|
|
10
|
+
* opens externally from the main frame when a user gesture started it ({@link NavigationRule.userInitiated}).
|
|
11
|
+
*
|
|
12
|
+
* Anything else, an iframe's or one without a gesture, is blocked, so a page opens an app only right after the user's
|
|
13
|
+
* tap, click or key press, as each platform counts them. On iOS that leaves out the redirect after a form POST, such
|
|
14
|
+
* as an OAuth `myapp://callback`: an `external` rule for its scheme before these opens it.
|
|
15
|
+
*
|
|
16
|
+
* Frozen; spread it after your own rules to keep it.
|
|
17
|
+
* @see [Navigation rules example](https://rasmuskard.github.io/react-native-minimal-webview/guides/examples/#navigation-rules)
|
|
18
|
+
* @group Navigation
|
|
19
|
+
*/
|
|
20
|
+
export const defaultNavigationRules: readonly NavigationRule[] = freeze<NavigationRule[]>([
|
|
21
|
+
{ scheme: ['file'], action: 'block' },
|
|
22
|
+
{ scheme: ['http', 'https'], action: 'allow' },
|
|
23
|
+
{ mainFrame: true, userInitiated: true, action: 'external' },
|
|
24
|
+
]);
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The WebView component, with navigation rules, a bridge to the page and native hooks.
|
|
3
|
+
*
|
|
4
|
+
* @groupDescription WebView
|
|
5
|
+
* The component, its props and its ref.
|
|
6
|
+
* @groupDescription Navigation
|
|
7
|
+
* The navigation state, and the rules that decide what each navigation does.
|
|
8
|
+
* @groupDescription Events
|
|
9
|
+
* What `onError`, `onProcessGone` and `onFullscreenChange` receive.
|
|
10
|
+
* @groupDescription Bridge
|
|
11
|
+
* Calls and events between React Native and the page's `window.nativeBridge`.
|
|
12
|
+
* @groupDescription Scripts
|
|
13
|
+
* Scripts for `injectedScripts`, which run at document start.
|
|
14
|
+
* @groupDescription Page requests
|
|
15
|
+
* File pickers, permission prompts and downloads the page starts.
|
|
16
|
+
* @groupDescription Native hooks
|
|
17
|
+
* Turning native hooks on with the `extensions` prop, and what they send to each extension's `onEvent`.
|
|
18
|
+
* @groupDescription Platform settings
|
|
19
|
+
* WebKit, UIScrollView and Android WebView settings, set by their platform names through the `ios` and `android` props.
|
|
20
|
+
* @module react-native-minimal-webview
|
|
21
|
+
* @packageDocumentation
|
|
22
|
+
*/
|
|
23
|
+
export { AndroidWebView, WebView } from './WebView';
|
|
24
|
+
export { createWebViewRef, useWebViewState } from './refStore';
|
|
25
|
+
export { createBridge } from './bridge/createBridge';
|
|
26
|
+
export { defaultNavigationRules } from './defaultNavigationRules';
|
|
27
|
+
export { reactNativeWebViewMessages } from './reactNativeWebViewMessages';
|
|
28
|
+
export { AndroidConstants, IOSConstants } from './platform.generated';
|
|
29
|
+
export type {
|
|
30
|
+
AndroidSettingKeys,
|
|
31
|
+
CGPoint,
|
|
32
|
+
CGRect,
|
|
33
|
+
CGSize,
|
|
34
|
+
IOSSettingKeys,
|
|
35
|
+
UIEdgeInsets,
|
|
36
|
+
} from './platform.generated';
|
|
37
|
+
export * from './types';
|