react-native-minimal-webview 1.0.0 → 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.
Files changed (84) hide show
  1. package/README.md +38 -18
  2. package/android/build.gradle +1 -1
  3. package/android/consumer-rules.pro +1 -1
  4. package/android/src/main/java/expo/modules/minimalwebview/DocumentEnd.kt +3 -3
  5. package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +33 -42
  6. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +7 -10
  7. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +5 -6
  8. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +4 -4
  9. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +14 -8
  10. package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +13 -16
  11. package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +1 -1
  12. package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +6 -5
  13. package/android/src/main/java/expo/modules/minimalwebview/requests/FileUpload.kt +1 -1
  14. package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +1 -1
  15. package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +3 -3
  16. package/build/WebView.d.ts +6 -9
  17. package/build/WebView.d.ts.map +1 -1
  18. package/build/WebView.js +23 -18
  19. package/build/WebView.js.map +1 -1
  20. package/build/bridge/createBridge.d.ts +3 -3
  21. package/build/bridge/createBridge.d.ts.map +1 -1
  22. package/build/bridge/createBridge.js +5 -3
  23. package/build/bridge/createBridge.js.map +1 -1
  24. package/build/bridge/endpoint.d.ts +0 -2
  25. package/build/bridge/endpoint.d.ts.map +1 -1
  26. package/build/bridge/endpoint.js +8 -3
  27. package/build/bridge/endpoint.js.map +1 -1
  28. package/build/bridge/origins.d.ts.map +1 -1
  29. package/build/bridge/origins.js +0 -1
  30. package/build/bridge/origins.js.map +1 -1
  31. package/build/bridge/pageClient.generated.d.ts +1 -1
  32. package/build/bridge/pageClient.generated.d.ts.map +1 -1
  33. package/build/bridge/pageClient.generated.js +1 -1
  34. package/build/bridge/pageClient.generated.js.map +1 -1
  35. package/build/defaultNavigationRules.d.ts +4 -5
  36. package/build/defaultNavigationRules.d.ts.map +1 -1
  37. package/build/defaultNavigationRules.js +4 -5
  38. package/build/defaultNavigationRules.js.map +1 -1
  39. package/build/index.d.ts +1 -1
  40. package/build/index.js +1 -1
  41. package/build/platform.generated.d.ts +14 -15
  42. package/build/platform.generated.d.ts.map +1 -1
  43. package/build/platform.generated.js +5 -3
  44. package/build/platform.generated.js.map +1 -1
  45. package/build/reactNativeWebViewDefaults.d.ts +2 -2
  46. package/build/reactNativeWebViewDefaults.js +2 -2
  47. package/build/reactNativeWebViewMessages.d.ts +8 -14
  48. package/build/reactNativeWebViewMessages.d.ts.map +1 -1
  49. package/build/reactNativeWebViewMessages.js +8 -14
  50. package/build/reactNativeWebViewMessages.js.map +1 -1
  51. package/build/refStore.d.ts +11 -10
  52. package/build/refStore.d.ts.map +1 -1
  53. package/build/refStore.js +7 -5
  54. package/build/refStore.js.map +1 -1
  55. package/build/types.d.ts +328 -282
  56. package/build/types.d.ts.map +1 -1
  57. package/ios/DelegateProxy.swift +2 -6
  58. package/ios/DocumentEnd.swift +7 -8
  59. package/ios/DownloadName.swift +1 -3
  60. package/ios/Hooks.swift +23 -21
  61. package/ios/MRWExceptions.h +1 -1
  62. package/ios/MRWInvoke.h +25 -10
  63. package/ios/MinimalWebView+Dialogs.swift +4 -7
  64. package/ios/MinimalWebView+Navigation.swift +25 -26
  65. package/ios/MinimalWebView+Scripts.swift +3 -3
  66. package/ios/MinimalWebView.swift +12 -11
  67. package/ios/NavigationRules.swift +1 -1
  68. package/ios/OriginRules.swift +3 -2
  69. package/ios/PlatformSettings.swift +14 -9
  70. package/ios/Recovery.swift +3 -3
  71. package/package.json +9 -4
  72. package/src/WebView.tsx +22 -19
  73. package/src/bridge/createBridge.ts +5 -3
  74. package/src/bridge/endpoint.ts +7 -3
  75. package/src/bridge/origins.ts +0 -1
  76. package/src/bridge/pageClient.generated.ts +1 -1
  77. package/src/bridge/pageClient.ts +1 -2
  78. package/src/defaultNavigationRules.ts +4 -5
  79. package/src/index.ts +1 -1
  80. package/src/platform.generated.ts +14 -15
  81. package/src/reactNativeWebViewDefaults.ts +2 -2
  82. package/src/reactNativeWebViewMessages.ts +8 -14
  83. package/src/refStore.ts +12 -11
  84. package/src/types.ts +328 -282
@@ -8,12 +8,18 @@ import WebKit
8
8
  /// is created; the other roots apply live, to `webView.configuration.preferences`,
9
9
  /// `webView.configuration.defaultWebpagePreferences`, the WKWebView and its scroll view.
10
10
  ///
11
- /// A value must fit the property's type: BOOL; integers, enums and option sets by raw value; floats; NSString; NSURL
12
- /// from a string; UIColor from `#rrggbb` or `#rrggbbaa`; UIEdgeInsets, CGPoint, CGSize and CGRect from an object; and
13
- /// `websiteDataStore` from `"default"` or `"nonPersistent"`. Anything else is rejected before KVC runs: a wrong value
14
- /// in an object-typed property can take the process down (WebKit asserts), and an unknown key raises an Objective-C
15
- /// exception Swift can't catch. Underscore (private) properties are refused, and the only private keys accepted are the
16
- /// two react-native-webview sets by KVC (`privateBools`).
11
+ /// A value must fit the property's type:
12
+ /// - BOOL, floats and NSString as themselves
13
+ /// - integers, enums and option sets by raw value
14
+ /// - NSURL from a string
15
+ /// - UIColor from `#rrggbb` or `#rrggbbaa`
16
+ /// - UIEdgeInsets, CGPoint, CGSize and CGRect from an object
17
+ /// - `websiteDataStore` from `"default"` or `"nonPersistent"`
18
+ ///
19
+ /// Anything else is rejected before KVC runs: a wrong value in an object-typed property can take the process down
20
+ /// (WebKit asserts), and an unknown key raises an Objective-C exception Swift can't catch. Underscore (private)
21
+ /// properties are refused, and the only private keys accepted are the two react-native-webview sets by KVC
22
+ /// (`privateBools`).
17
23
  ///
18
24
  /// `get` reads a property of a root and `call` invokes a method on one by selector, through MRWInvoke (MRWInvoke.h),
19
25
  /// which sets the arguments by the method's signature. For those two, `websiteDataStore` and `httpCookieStore` are
@@ -176,8 +182,8 @@ final class PlatformSettings {
176
182
  return String(cString: property_getAttributes(property)!).split(separator: ",")
177
183
  }
178
184
 
179
- /// The private BOOLs react-native-webview sets by KVC, which reaches WebKit's `_set…` accessors: they declare no
180
- /// property by these names. They widen what `file:` pages read: other `file:` URLs, and any URL.
185
+ /// KVC reaches these through WebKit's `_set…` accessors: WebKit declares no property by these names. They widen what
186
+ /// `file:` pages read: other `file:` URLs, and any URL.
181
187
  private static let privateBools: [String: AnyClass] = [
182
188
  "allowFileAccessFromFileURLs": WKPreferences.self,
183
189
  "allowUniversalAccessFromFileURLs": WKWebViewConfiguration.self,
@@ -226,7 +232,6 @@ final class PlatformSettings {
226
232
  }
227
233
  }
228
234
 
229
- /// `#rrggbb` or `#rrggbbaa`.
230
235
  private static func color(_ text: String) -> UIColor? {
231
236
  let hex = text.hasPrefix("#") ? String(text.dropFirst()) : text
232
237
  guard hex.count == 6 || hex.count == 8, let bits = UInt32(hex, radix: 16) else { return nil }
@@ -11,9 +11,9 @@ enum Recovery {
11
11
  return trimmed(uri) == trimmed(url)
12
12
  }
13
13
 
14
- /// Records a web content process death at `now`, in seconds of a clock the device time doesn't move
15
- /// (`ProcessInfo.systemUptime`), in `times` and says whether to reload after it: not after more than 3 in 60 s, a
16
- /// crash exactly 60 s back included.
14
+ /// Records a web content process death at `now` in `times`, and says whether to reload after it: not after more than
15
+ /// `maxCrashesPerWindow` in `crashWindow`, a death exactly `crashWindow` back included. `now` is in seconds of
16
+ /// `ProcessInfo.systemUptime`, which a change of device time doesn't move.
17
17
  static func crashAllowsReload(_ times: inout [TimeInterval], now: TimeInterval) -> Bool {
18
18
  times = times.filter { now - $0 <= crashWindow } + [now]
19
19
  return times.count <= maxCrashesPerWindow
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "react-native-minimal-webview",
3
- "version": "1.0.0",
4
- "description": "A minimal, extensible WebView for React Native (Expo Modules)",
3
+ "version": "1.0.1",
4
+ "description": "A React Native WebView that hands you the iOS and Android WebView APIs, instead of wrapping each one in a prop",
5
5
  "main": "build/index.js",
6
6
  "types": "build/index.d.ts",
7
7
  "exports": {
@@ -41,6 +41,11 @@
41
41
  "keywords": [
42
42
  "react-native",
43
43
  "expo",
44
+ "webview",
45
+ "wkwebview",
46
+ "android-webview",
47
+ "ios",
48
+ "android",
44
49
  "react-native-minimal-webview",
45
50
  "MinimalWebView"
46
51
  ],
@@ -53,8 +58,8 @@
53
58
  "homepage": "https://github.com/RasmusKard/react-native-minimal-webview#readme",
54
59
  "devDependencies": {
55
60
  "@babel/core": "^7.29.13",
56
- "@rn-cross-platform-docs/cli": "1.3.0",
57
- "@rn-cross-platform-docs/zensical": "1.3.0",
61
+ "@rn-cross-platform-docs/cli": "2.0.0",
62
+ "@rn-cross-platform-docs/zensical": "2.0.0",
58
63
  "@stryker-mutator/core": "10.1.1",
59
64
  "@stryker-mutator/jest-runner": "10.1.1",
60
65
  "@types/jest": "^30.0.0",
package/src/WebView.tsx CHANGED
@@ -110,7 +110,6 @@ type NativeProps = ViewProps &
110
110
  onProcessGone: ProcessGoneEvent;
111
111
  }>;
112
112
 
113
- /** The native view's methods, on its ref. */
114
113
  export type NativeMethods = {
115
114
  goBack(): Promise<void>;
116
115
  goForward(): Promise<void>;
@@ -153,7 +152,7 @@ const unawaited = (call: Promise<unknown> | undefined, name: string) =>
153
152
  });
154
153
 
155
154
  /**
156
- * A WebView whose native side decides navigations and owns the navigation state: see {@link WebViewProps} and
155
+ * A WebView whose core decides navigations and owns the navigation state: see {@link WebViewProps} and
157
156
  * {@link WebViewRef}.
158
157
  * @group WebView
159
158
  */
@@ -393,7 +392,14 @@ const ACTIONS: unknown[] = Object.keys({
393
392
  } satisfies Record<NavigationRule['action'], 0>);
394
393
 
395
394
  /** A value as a warning shows it. */
396
- const shown = (value: unknown) => JSON.stringify(value) ?? String(value);
395
+ const shown = (value: unknown) => {
396
+ try {
397
+ return JSON.stringify(value) ?? String(value);
398
+ } catch {
399
+ // A BigInt, a circular value or a throwing toJSON: the message runs in production too, so it must not throw.
400
+ return typeof value === 'bigint' ? String(value) : Object.prototype.toString.call(value);
401
+ }
402
+ };
397
403
 
398
404
  /** What a field of each kind takes, as a warning says it, and the check. */
399
405
  const FIELD_KINDS = {
@@ -406,7 +412,6 @@ const FIELD_KINDS = {
406
412
  action: { takes: `one of ${shown(ACTIONS)}`, ok: (value: unknown) => ACTIONS.includes(value) },
407
413
  };
408
414
 
409
- /** What is wrong with a rule, if anything. */
410
415
  function ruleProblem(rule: unknown) {
411
416
  if (typeof rule !== 'object' || rule === null) return `must be an object, not ${shown(rule)}`;
412
417
  // A missing action is checked as an undefined one; any other field may be undefined (unset).
@@ -420,9 +425,8 @@ function ruleProblem(rule: unknown) {
420
425
  }
421
426
 
422
427
  /**
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.
428
+ * The rules as the core gets them. The core skips an unknown key and a non-boolean flag, which would widen a rule
429
+ * (`hosts` would match every host), so a malformed rule becomes a `block` one. The same array when none is malformed.
426
430
  */
427
431
  function useNavigationRules(rules: WebViewProps['navigationRules']) {
428
432
  const given: unknown = rules ?? defaultNavigationRules;
@@ -432,10 +436,11 @@ function useNavigationRules(rules: WebViewProps['navigationRules']) {
432
436
  checked: [],
433
437
  warnings: [`navigationRules: must be an array, not ${shown(given)}; treated as []`],
434
438
  };
435
- const problems = given.map(ruleProblem);
439
+ // Array.from, not map: map skips a sparse array's holes, which would reach native unchecked.
440
+ const problems = Array.from(given, ruleProblem);
436
441
  return {
437
442
  checked: problems.some(Boolean)
438
- ? given.map((rule: unknown, i) => (problems[i] ? { action: 'block' } : rule))
443
+ ? Array.from(given, (rule: unknown, i) => (problems[i] ? { action: 'block' } : rule))
439
444
  : given,
440
445
  warnings: problems.flatMap((problem, i) =>
441
446
  problem
@@ -460,9 +465,9 @@ function useRequestHandlers(props: WebViewProps) {
460
465
  }
461
466
 
462
467
  /**
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.
468
+ * The core's `hookOptions`: each extension's `options` by its key, the later of two extensions with one key winning (a
469
+ * development warning). The same object while the JSON is the same, so a render with new handlers sends the core
470
+ * nothing.
466
471
  */
467
472
  function useHookOptions(extensions: WebViewProps['extensions']) {
468
473
  const on = (extensions ?? []).filter((extension) => !!extension);
@@ -580,20 +585,17 @@ export const AndroidWebView = {
580
585
  * Starts WebView before any WebView mounts, so the first WebView mounts sooner.
581
586
  *
582
587
  * 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.
588
+ * pushed. WebView starts once per app, and React Native's first `fetch` starts it too.
585
589
  * @android
586
590
  */
587
591
  warmUp(): void {
588
592
  if (Platform.OS === 'android') nativeModule().warmUp();
589
593
  },
590
594
  /**
591
- * Opens a connection to `url`'s origin (DNS, TCP, TLS) in WebView's default profile, ahead of a load that comes
592
- * later.
595
+ * Opens a connection to `url`'s origin (DNS, TCP, TLS) in WebView's default profile, ahead of a load.
593
596
  *
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
+ * Call it before the load starts: as the screen with the WebView is pushed, or for the next page a mounted WebView
598
+ * will go to. A WebView connects to its `source` itself as it mounts.
597
599
  *
598
600
  * It starts WebView on the UI thread if nothing has yet, so call it once `warmUp()` has had time or a WebView is
599
601
  * mounted.
@@ -612,6 +614,7 @@ export const AndroidWebView = {
612
614
  * WebView exists, it applies when the first one is made, so it doesn't start WebView. On iOS,
613
615
  * `ios.webView.inspectable` sets it per WebView.
614
616
  * @android
617
+ * @see [Debugging the page example](https://rasmuskard.github.io/react-native-minimal-webview/guides/examples/#debugging-the-page)
615
618
  */
616
619
  setWebContentsDebuggingEnabled(enabled: boolean): void {
617
620
  if (Platform.OS === 'android')
@@ -42,9 +42,9 @@ const MAX_QUEUE = 1000;
42
42
  /**
43
43
  * Creates a {@link Bridge} to the pages of `allowedOrigins`, for one WebView's `bridge` prop.
44
44
  *
45
- * The type argument, a {@link BridgeSchema}, types the method names, params, results and event payloads of `handle`,
46
- * `call`, `emit` and `on`, each side's apart; nothing checks them at runtime, so a handler still validates what an
47
- * untrusted page sends. Throws an `Error` for an invalid origin rule or timeout.
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
48
  * @see [Bridge example](https://rasmuskard.github.io/react-native-minimal-webview/guides/examples/#the-bridge)
49
49
  * @group Bridge
50
50
  */
@@ -80,6 +80,8 @@ export function createBridge<Schema extends BridgeSchema = BridgeSchema>(
80
80
  (message) => {
81
81
  if (post && phase === 'ready') deliver(message);
82
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);
83
85
  queue.push(message);
84
86
  const dropped = queue.length > MAX_QUEUE ? queue.shift() : undefined;
85
87
  if (dropped?.kind === 'call') {
@@ -52,7 +52,13 @@ export function createEndpoint<Sender = void>(
52
52
  )
53
53
  : undefined;
54
54
  pending.set(id, { resolve, reject, timer, sent: false });
55
- send({ id, kind: 'call', method, params });
55
+ try {
56
+ send({ id, kind: 'call', method, params });
57
+ } catch (error) {
58
+ clearTimeout(timer);
59
+ pending.delete(id);
60
+ throw error;
61
+ }
56
62
  });
57
63
  },
58
64
  emit(event: string, payload?: unknown) {
@@ -69,7 +75,6 @@ export function createEndpoint<Sender = void>(
69
75
  listeners.set(event, set.add(listener));
70
76
  return () => set.delete(listener);
71
77
  },
72
- /** Rejects the calls in flight, or only those `only` picks. */
73
78
  rejectPending(code: BridgeErrorCode, message: string, only?: (call: Pending) => boolean) {
74
79
  for (const [id, call] of pending) {
75
80
  if (only && !only(call)) continue;
@@ -78,7 +83,6 @@ export function createEndpoint<Sender = void>(
78
83
  pending.delete(id);
79
84
  }
80
85
  },
81
- /** A message from the other side: settles a call, fires an event, or answers a call through `reply`. */
82
86
  async receive(message: BridgeMessage, reply: (message: BridgeMessage) => void, sender: Sender) {
83
87
  switch (message.kind) {
84
88
  case 'call': {
@@ -37,7 +37,6 @@ export const originForms = (rules: string[]): OriginForms => {
37
37
  return forms;
38
38
  };
39
39
 
40
- /** Whether `text` holds `part` at index `at`, compared character by character. */
41
40
  function hasAt(text: string, part: string, at: number) {
42
41
  for (let k = 0; k < part.length; k++) if (text[at + k] !== part[k]) return false;
43
42
  return true;
@@ -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, sent: false });\n send({ id, kind: 'call', method, params });\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}";
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
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})()";
@@ -34,7 +34,6 @@ export function installPageClient(w: PageWindow, timeoutMs: number) {
34
34
  };
35
35
  const endpoint = createEndpoint(send, timeoutMs, 'p');
36
36
 
37
- /** Answers to native's calls go back through `send`, as messages. */
38
37
  const receive = async (text: string) => {
39
38
  const message = JSON.parse(text) as Message;
40
39
  if (message.doc === doc) await endpoint.receive(message, send);
@@ -47,7 +46,7 @@ export function installPageClient(w: PageWindow, timeoutMs: number) {
47
46
  emit: endpoint.emit,
48
47
  handle: endpoint.handle,
49
48
  on: endpoint.on,
50
- /** iOS's entry point (callAsyncJavaScript, origin-checked there); Android uses the transport's onmessage. */
49
+ /** iOS's entry point, origin-checked there. */
51
50
  __receive: receive,
52
51
  });
53
52
  // `ready` (protocol.ts) waits for DOMContentLoaded: a call delivered earlier would get `not_found`.
@@ -9,13 +9,12 @@ const freeze = <T extends object>(value: T): T => {
9
9
  * The rules `navigationRules` has when it is unset: `file:` is blocked, http(s) loads in place, and any other scheme
10
10
  * opens externally from the main frame when a user gesture started it ({@link NavigationRule.userInitiated}).
11
11
  *
12
- * Anything else, a subframe'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: on Android within the up to 5 s of user activation Chromium gives the page, on iOS through a
14
- * link activated within 1 s after a tap (or any link activation while VoiceOver or Switch Control runs). A page's
15
- * script or timer can't on its own, a link it clicks included; on iOS neither can a click handler's `location.href`, a
16
- * link activated from a hardware keyboard, or a redirect after a form POST (an OAuth `myapp://callback`).
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.
17
15
  *
18
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)
19
18
  * @group Navigation
20
19
  */
21
20
  export const defaultNavigationRules: readonly NavigationRule[] = freeze<NavigationRule[]>([
package/src/index.ts CHANGED
@@ -16,7 +16,7 @@
16
16
  * @groupDescription Native hooks
17
17
  * Turning native hooks on with the `extensions` prop, and what they send to each extension's `onEvent`.
18
18
  * @groupDescription Platform settings
19
- * WebKit and Android WebView properties, set by name through the `ios` and `android` props.
19
+ * WebKit, UIScrollView and Android WebView settings, set by their platform names through the `ios` and `android` props.
20
20
  * @module react-native-minimal-webview
21
21
  * @packageDocumentation
22
22
  */
@@ -1,38 +1,36 @@
1
1
  // Generated by .github/scripts/gen-platform-types.mts from .github/scripts/platform-headers/. Do not edit.
2
2
 
3
3
  /**
4
- * An iOS struct the settings channel carries as an object.
4
+ * Insets from each edge, in points, as in `scrollView.contentInset`.
5
5
  * @group Platform settings
6
6
  * @ios
7
7
  */
8
8
  export type UIEdgeInsets = { top: number; left: number; bottom: number; right: number };
9
9
 
10
10
  /**
11
- * An iOS struct the settings channel carries as an object.
11
+ * A point, as in `scrollView.contentOffset`.
12
12
  * @group Platform settings
13
13
  * @ios
14
14
  */
15
15
  export type CGPoint = { x: number; y: number };
16
16
 
17
17
  /**
18
- * An iOS struct the settings channel carries as an object.
18
+ * A size, as in `scrollView.contentSize`.
19
19
  * @group Platform settings
20
20
  * @ios
21
21
  */
22
22
  export type CGSize = { width: number; height: number };
23
23
 
24
24
  /**
25
- * An iOS struct the settings channel carries as an object.
25
+ * A rectangle. No generated key takes one; it fits a setting under `other` and a `call` argument.
26
26
  * @group Platform settings
27
27
  * @ios
28
28
  */
29
29
  export type CGRect = { x: number; y: number; width: number; height: number };
30
30
 
31
31
  /**
32
- * The iOS settings keys by root: the writable WebKit and UIScrollView properties the settings channel can carry, from
33
- * the SDK headers.
34
- *
35
- * A key a newer SDK adds goes under the root's `other`.
32
+ * The iOS settings keys by root: the writable WebKit and UIScrollView properties from the SDK headers whose type is a
33
+ * `SettingValue`.
36
34
  * @group Platform settings
37
35
  * @ios
38
36
  */
@@ -226,10 +224,9 @@ export type IOSSettingKeys = {
226
224
  };
227
225
 
228
226
  /**
229
- * The Android settings keys by root: the one-argument `WebSettings`, `WebView` and `CookieManager` setters, then
230
- * `WebSettingsCompat`'s and `WebViewCompat`'s statics, then the scroll setters `WebView` inherits from `View`.
231
- *
232
- * A key a newer SDK or androidx.webkit adds goes under the root's `other`.
227
+ * The Android settings keys by root: the one-argument setters of `WebSettings` and `WebView`, `CookieManager`'s
228
+ * `(WebView, value)` setter, the `WebSettingsCompat` and `WebViewCompat` statics, and the scroll setters `WebView`
229
+ * inherits from `View`.
233
230
  * @group Platform settings
234
231
  * @android
235
232
  */
@@ -499,9 +496,11 @@ export type AndroidSettingKeys = {
499
496
  * `configuration: { dataDetectorTypes: IOSConstants.DataDetectorTypes.link }`.
500
497
  *
501
498
  * An option set's `all` is the OR of its listed bits, not `NSUIntegerMax`, which JSON can't carry.
502
- * `WebsiteDataType` has the data type names the `websiteDataStore` methods take, for `call`; `WebViewDataType` is
503
- * the option set `webView.fetchDataOfTypes:` takes, and `CookiePolicy` the value
504
- * `httpCookieStore.setCookiePolicy:completionHandler:` takes.
499
+ * These three are for `call`, not for keys:
500
+ *
501
+ * - `WebsiteDataType`: the data type names the `websiteDataStore` methods take.
502
+ * - `WebViewDataType`: the option set `webView.fetchDataOfTypes:` takes.
503
+ * - `CookiePolicy`: the value `httpCookieStore.setCookiePolicy:completionHandler:` takes.
505
504
  * @group Platform settings
506
505
  * @ios
507
506
  * @namespace
@@ -1,8 +1,8 @@
1
1
  import type { AndroidSettings, IOSSettings } from './types';
2
2
 
3
3
  /**
4
- * Defaults taken from react-native-webview, so that an app migrated from it behaves as before. Each is a plain boolean
5
- * an app sets back through `ios` or `android`, not a design decision of this package.
4
+ * react-native-webview's defaults, so that an app migrated from it behaves as before. An app sets any back through
5
+ * `ios` or `android`.
6
6
  */
7
7
  export const REACT_NATIVE_WEBVIEW_DEFAULTS = {
8
8
  ios: { scrollView: { directionalLockEnabled: true } },
@@ -3,22 +3,16 @@ import { Platform } from 'react-native';
3
3
  import type { InjectedScript } from './types';
4
4
 
5
5
  /**
6
- * react-native-webview's messaging, for `injectedScripts`, carried by the bridge event `rnw`.
6
+ * Gives pages react-native-webview's messaging over the bridge event `rnw`; pass it in `injectedScripts`.
7
7
  *
8
- * The page's `window.ReactNativeWebView.postMessage(data)` arrives as `String(data)`, and what you emit reaches the
9
- * page as a `message` event on `window` on iOS and on `document` on Android, as react-native-webview does.
8
+ * - The page's `window.ReactNativeWebView.postMessage(data)` arrives as `String(data)`.
9
+ * - What you emit as `rnw` reaches the page as a `message` event on `window` on iOS and on `document` on Android, as
10
+ * react-native-webview does.
11
+ * - There is no `injectedObjectJson`: `window.ReactNativeWebView` has `postMessage` only.
10
12
  *
11
- * It needs the `bridge` prop: only the main frame of the pages in `allowedOrigins` gets `window.ReactNativeWebView`,
12
- * and only `postMessage`: there is no `injectedObjectJson`. Its `origins` are `['*']`, since the bridge already scopes
13
- * it.
14
- * @example
15
- * ```tsx
16
- * const bridge = createBridge({ allowedOrigins: ['https://example.com'] });
17
- * bridge.on('rnw', (data) => console.log(data)); // the page called ReactNativeWebView.postMessage(data)
18
- * bridge.emit('rnw', 'hello'); // the page gets a message event whose data is 'hello'
19
- *
20
- * <WebView source={{ uri: 'https://example.com' }} bridge={bridge} injectedScripts={[reactNativeWebViewMessages]} />;
21
- * ```
13
+ * It needs the `bridge` prop: only the main frame of the pages in `allowedOrigins` gets `window.ReactNativeWebView`.
14
+ * Its `origins` are `['*']`, since the bridge already scopes it.
15
+ * @see [Messaging example](https://rasmuskard.github.io/react-native-minimal-webview/guides/migrating-from-react-native-webview/#postmessage-and-onmessage)
22
16
  * @group Scripts
23
17
  */
24
18
  export const reactNativeWebViewMessages: InjectedScript = {
package/src/refStore.ts CHANGED
@@ -12,7 +12,7 @@ import {
12
12
 
13
13
  import type { NavigationState, WebViewRef, WebViewRefObject } from './types';
14
14
 
15
- /** The state while no WebView is mounted with a ref: an empty `url`, so a stale URL never looks valid. */
15
+ /** An empty `url`, so a stale URL never looks valid while no WebView is mounted. */
16
16
  const INITIAL_STATE: NavigationState = {
17
17
  url: '',
18
18
  pendingUrl: null,
@@ -82,7 +82,9 @@ function createAdapter(): Adapter {
82
82
  }
83
83
 
84
84
  /**
85
- * A ref to pass as a WebView's `ref`, made outside React (a module, a store) so code outside React can use it.
85
+ * A ref to pass as a WebView's `ref`, which a module or a store can hold, so code outside React can read the state and
86
+ * call the WebView.
87
+ * @see [Outside React example](https://rasmuskard.github.io/react-native-minimal-webview/guides/examples/#outside-react)
86
88
  * @group WebView
87
89
  */
88
90
  export function createWebViewRef(): WebViewRefObject {
@@ -92,9 +94,9 @@ export function createWebViewRef(): WebViewRefObject {
92
94
  }
93
95
 
94
96
  /**
95
- * Puts `handle` in a callback or plain ref. Any ref object also gets the navigation state through its adapter, which a
96
- * createWebViewRef one is, so its `current` comes from the adapter too. Returns a function that records a new state,
97
- * passes it to the attached ref and returns the previous state.
97
+ * Attaches `handle` to `ref`. A callback or plain ref gets it through `useImperativeHandle`; a `createWebViewRef` ref
98
+ * serves it as its own `current`. Any ref object also gets the navigation state through its adapter.
99
+ * Returns a function that records a new state, passes it to the attached ref and returns the previous state.
98
100
  */
99
101
  export function useAttach(
100
102
  ref: Ref<WebViewRef> | undefined,
@@ -123,19 +125,18 @@ export function useAttach(
123
125
 
124
126
  /**
125
127
  * The navigation state of the WebView mounted with `ref` (a `useRef`, `createRef` or `createWebViewRef` one);
126
- * re-renders on every change, `progress` included, and follows a remount. With `select`, it re-renders only when what
127
- * `select` picks changes.
128
+ * re-renders on every change, `progress` included, and follows a remount.
128
129
  * @see [Navigation state example](https://rasmuskard.github.io/react-native-minimal-webview/guides/examples/#navigation-state)
129
130
  * @group Navigation
130
131
  */
131
132
  export function useWebViewState(ref: RefObject<WebViewRef | null>): NavigationState;
132
133
  /**
133
134
  * What `select` returns for the navigation state of the WebView mounted with `ref`; re-renders only when that changes
134
- * (by `Object.is`), and follows a remount. `useWebViewState(ref, (state) => state.canGoBack)` doesn't re-render as a
135
- * page loads.
135
+ * (by `Object.is`), and follows a remount.
136
136
  *
137
- * `select` must be pure: it can run more than once for a state, and it can be a new function at each render. A new
138
- * object or array from it is never the last one, so it re-renders on every change.
137
+ * `select` must be pure: it can run more than once for a state, and it can be a new function at each render. A
138
+ * `select` that returns a new object or array each time re-renders on every state change, because `Object.is` never
139
+ * matches it.
139
140
  */
140
141
  export function useWebViewState<T>(
141
142
  ref: RefObject<WebViewRef | null>,