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
package/README.md CHANGED
@@ -5,11 +5,16 @@ A React Native WebView that hands you the iOS and Android WebView APIs, instead
5
5
  It runs on iOS and Android as an Expo module.
6
6
 
7
7
  [Install](#install) ·
8
+ [npm](https://www.npmjs.com/package/react-native-minimal-webview) ·
8
9
  [API reference](https://rasmuskard.github.io/react-native-minimal-webview/typescript/react-native-minimal-webview/) ·
10
+ [How it works](guides/how-it-works.md) ·
9
11
  [Examples](guides/examples.md) ·
12
+ [Use a platform API](guides/platform-apis.md) ·
10
13
  [Native hooks](guides/native-hooks.md) ·
11
14
  [Migrating from react-native-webview](guides/migrating-from-react-native-webview.md) ·
15
+ [Troubleshooting](guides/troubleshooting.md) ·
12
16
  [Extensions](https://rasmuskard.github.io/react-native-minimal-webview/typescript/extensions/) ·
17
+ [Changelog](https://github.com/RasmusKard/react-native-minimal-webview/blob/main/CHANGELOG.md) ·
13
18
  [MIT license](https://github.com/RasmusKard/react-native-minimal-webview/blob/main/LICENSE)
14
19
 
15
20
  ## Why it exists
@@ -54,25 +59,22 @@ A setting or method a newer SDK adds works without a release of this package: se
54
59
  [`android`](https://rasmuskard.github.io/react-native-minimal-webview/typescript/react-native-minimal-webview/interfaces/WebViewProps/#android) and
55
60
  [`call`](https://rasmuskard.github.io/react-native-minimal-webview/typescript/react-native-minimal-webview/type-aliases/WebViewRef/#call).
56
61
 
57
- ## What it changes from react-native-webview
62
+ ## What the core adds
58
63
 
59
- ![The app sends rules and settings to the native WebView core and gets state and events back; the core answers the page's navigations; the bridge links the app and allowed origins](guides/how-it-works.svg)
64
+ [How it works](guides/how-it-works.md) explains the parts. The core adds only what the platform APIs lack:
60
65
 
61
- The core adds only what the platform APIs lack:
62
-
63
- | | react-native-webview | react-native-minimal-webview |
64
- | -------------------------- | ---------------------------------------------------- | ------------------------------------------- |
65
- | Navigation decisions | `onShouldStartLoadWithRequest`, a JS round trip each | `navigationRules`, matched natively |
66
- | Page messaging | `postMessage` strings, any page | Typed promise bridge, `allowedOrigins` only |
67
- | Navigation state | `onNavigationStateChange` events you keep in state | `useWebViewState(ref)` |
68
- | Page camera and microphone | Granted to any page on Android, after asking the OS | Your app answers `onPermissionRequest` |
66
+ - `navigationRules`: navigations decided natively, with a JS round trip only for an `ask` rule.
67
+ - A typed promise bridge, open only to the bridge's `allowedOrigins`.
68
+ - `useWebViewState(ref)`: the navigation state, kept natively.
69
+ - `onPermissionRequest`: your app answers the page's permission requests (camera, microphone, location).
69
70
 
70
71
  The [migration guide](guides/migrating-from-react-native-webview.md) covers each react-native-webview prop that works differently here.
71
72
 
72
73
  ## When to use something else
73
74
 
74
75
  - Old architecture, Windows or macOS: react-native-webview supports them, this package doesn't. Neither runs on web.
75
- - Expo Go: the package has native code, so it needs a development build.
76
+ - Expo Go: the package has native code, so it needs a
77
+ [development build](https://docs.expo.dev/develop/development-builds/introduction/).
76
78
 
77
79
  ## Install
78
80
 
@@ -92,12 +94,27 @@ npx pod-install
92
94
 
93
95
  ### Requirements
94
96
 
95
- | Platform | Minimum |
96
- | ------------ | ------------------------------------------------------------------------------ |
97
- | iOS | 17.0: `ios.deploymentTarget: '17.0'`, for example with `expo-build-properties` |
98
- | Android | API 29: `android.minSdkVersion: 29`, for example with `expo-build-properties` |
99
- | Expo SDK | 53 (React Native 0.79, React 19) |
100
- | Architecture | New architecture only |
97
+ | Platform | Minimum |
98
+ | ------------ | -------------------------------------------------------------------------- |
99
+ | iOS | 17.0 |
100
+ | Android | API 29 |
101
+ | Expo SDK | 53 (React Native 0.79, React 19) |
102
+ | Architecture | [New architecture](https://reactnative.dev/architecture/landing-page) only |
103
+
104
+ An Expo app sets the two minimums with expo-build-properties (`npx expo install expo-build-properties`) in `app.json`:
105
+
106
+ ```json
107
+ {
108
+ "expo": {
109
+ "plugins": [
110
+ [
111
+ "expo-build-properties",
112
+ { "ios": { "deploymentTarget": "17.0" }, "android": { "minSdkVersion": 29 } }
113
+ ]
114
+ ]
115
+ }
116
+ }
117
+ ```
101
118
 
102
119
  Some features need a newer Android System WebView: [which ones](guides/android-system-webview.md).
103
120
 
@@ -116,15 +133,18 @@ Then pick what you need:
116
133
  | To | See |
117
134
  | --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
118
135
  | Show the URL, progress or a back button | [Navigation state](guides/examples.md#navigation-state) |
136
+ | Show a spinner and your own error screen | [Loading and error screens](guides/examples.md#loading-and-error-screens) |
119
137
  | Keep the WebView on your sites, open the rest externally | [Navigation rules](guides/examples.md#navigation-rules) |
120
138
  | Call the page from the app, and the app from the page | [The bridge](guides/examples.md#the-bridge) |
121
- | Change a WebView setting | [Platform settings](guides/examples.md#platform-settings) |
139
+ | Change a WebView setting, or call a platform method | [Use a platform API](guides/platform-apis.md) |
122
140
  | Share cookies with native requests | [Cookies](guides/examples.md#cookies) |
123
141
  | Run a script on every page | [Scripts](guides/examples.md#scripts) |
124
142
  | Load bundled HTML | [Local files](guides/examples.md#local-files) |
125
143
  | Answer file pickers, permissions and downloads | [Page requests](guides/examples.md#page-requests) |
144
+ | Inspect the page's DOM and console | [Debugging the page](guides/examples.md#debugging-the-page) |
126
145
  | Use the native `WKWebView` or `WebView` | [Native hooks](guides/native-hooks.md) |
127
146
  | Bring back `basicAuthCredential`, `onScroll` and other react-native-webview props | [@react-native-minimal-webview/extensions](https://rasmuskard.github.io/react-native-minimal-webview/typescript/extensions/) |
147
+ | Find out why something doesn't work | [Troubleshooting](guides/troubleshooting.md) |
128
148
 
129
149
  ## Contributing
130
150
 
@@ -13,7 +13,7 @@ android {
13
13
  versionName project.version // Expo SDK 53's module plugin requires it
14
14
  consumerProguardFiles 'consumer-rules.pro'
15
15
  }
16
- // -PmrwCoverage: JaCoCo for the unit tests (.github/CONTRIBUTING.md); without it, the build is unchanged
16
+ // -PmrwCoverage: JaCoCo for the unit tests (.github/CONTRIBUTING.md)
17
17
  if (providers.gradleProperty('mrwCoverage').present) buildTypes.debug.enableUnitTestCoverage = true
18
18
  }
19
19
 
@@ -1,4 +1,4 @@
1
- # The `android` settings prop finds androidx.webkit's compat setters and getters by name (PlatformSettings.kt).
1
+ # The `android` settings prop, `get` and `call` find androidx.webkit's compat methods by name (PlatformSettings.kt).
2
2
  # R8 would otherwise strip or rename the ones the app's own code never calls.
3
3
  -keep class androidx.webkit.WebSettingsCompat { public static *; }
4
4
  -keep class androidx.webkit.WebViewCompat { public static *; }
@@ -3,8 +3,8 @@ package expo.modules.minimalwebview
3
3
  /**
4
4
  * Why a Document ended, as [WebViewContext.onDocumentEnd] and [WebViewContext.onDestroyed] report it.
5
5
  *
6
- * A Document is the main-frame page a WebView shows now: from a navigation's commit, a back-forward-cache restore or a
7
- * failed load's error page included, to the next commit, a renderer crash or the view closing.
6
+ * A Document is the main-frame page a WebView shows now: from a navigation's commit to the next commit, a renderer
7
+ * crash or the view closing.
8
8
  *
9
9
  * The first commit after a WebView is made, at mount or after a crash, opens one and ends nothing.
10
10
  *
@@ -22,7 +22,7 @@ enum class DocumentEnd {
22
22
 
23
23
  /**
24
24
  * The renderer died: this WebView goes, its hooks detach (their [WebViewContext.onDestroyed] handlers run), and
25
- * they attach again to the one that replaces it, with a new context. Its first commit opens the next Document.
25
+ * they attach again to the one that replaces it, with a new context.
26
26
  */
27
27
  CRASHED,
28
28
 
@@ -23,13 +23,11 @@ import java.util.concurrent.atomic.AtomicBoolean
23
23
  * Native hooks: Kotlin in an app's or a package's own Expo module that gets the real [WebView] behind this package's
24
24
  * WebViews and chains its own clients to it, with no protocol to implement.
25
25
  *
26
- * The [native hooks guide](https://rasmuskard.github.io/react-native-minimal-webview/guides/native-hooks/)
27
- * walks through one.
28
- *
29
- * Leave alone what the core owns: the WebView's own client slots (add to [WebViewContext.clients] and
26
+ * **Important:** leave alone what the core owns: the WebView's own client slots (add to [WebViewContext.clients] and
30
27
  * [WebViewContext.chromeClients] instead), its touch and scroll-change listeners ([WebViewContext.touchListeners] and
31
28
  * [WebViewContext.scrollListeners]), the bridge's web message listener and document-start scripts, and the download
32
29
  * listener ([WebViewContext.onDownloadStart]).
30
+ * @see [Native hooks guide](https://rasmuskard.github.io/react-native-minimal-webview/guides/native-hooks/)
33
31
  */
34
32
  object MinimalWebViewHooks {
35
33
  internal class Hook(
@@ -42,11 +40,14 @@ object MinimalWebViewHooks {
42
40
  internal val hooks = mutableListOf<Hook>()
43
41
 
44
42
  /**
45
- * Registers the hook for [key]. Call it from your module's `OnCreate`, before the first WebView.
43
+ * Registers the hook for [key].
44
+ *
45
+ * Call it from your module's `OnCreate`, before the first WebView.
46
46
  *
47
47
  * The same `register` call running again replaces its hook: a JS reload creates the modules anew and runs their
48
- * `OnCreate` again. A helper that calls `register` for other code is one call, so a second hook through it replaces
49
- * the first silently.
48
+ * `OnCreate` again. The call is told apart by where its [attach] lambda is written, so a helper that wraps its
49
+ * caller's `attach` in a lambda of its own is one call, and a second hook through it replaces the first silently; a
50
+ * helper that passes the caller's lambda on keeps them apart.
50
51
  *
51
52
  * The hook attaches to each WebView whose `extensions` prop has an extension with [key] that is on;
52
53
  * [HookExtension.options](https://rasmuskard.github.io/react-native-minimal-webview/typescript/react-native-minimal-webview/type-aliases/HookExtension/#options)
@@ -100,10 +101,7 @@ object MinimalWebViewHooks {
100
101
  }
101
102
  }
102
103
 
103
- /**
104
- * Which [hooks] attach to a WebView created with the enabled `hookOptions` [keys]: the ones registered under them, in
105
- * registration order. Second, the keys no hook is registered under.
106
- */
104
+ /** Splits [keys] into the [hooks] registered under them, in registration order, and the keys no hook is registered under. */
107
105
  internal fun selectHooks(
108
106
  hooks: List<MinimalWebViewHooks.Hook>,
109
107
  keys: Set<String>
@@ -112,14 +110,11 @@ internal fun selectHooks(
112
110
  return attaching to keys - attaching.map { it.key }.toSet()
113
111
  }
114
112
 
115
- /** [keys] in the order of the [registered] hook keys, then the keys no hook is registered under, sorted. */
113
+ /** Hooks whose keys turn on together attach in registration order, which orders their clients. */
116
114
  internal fun inRegistrationOrder(keys: Set<String>, registered: List<String>) =
117
115
  registered.filter { it in keys } + (keys - registered.toSet()).sorted()
118
116
 
119
- /**
120
- * Which of [attaching] makes the WebView: the first with a factory, or null for a plain WebView. Second, the keys of the
121
- * others whose factory is a different object.
122
- */
117
+ /** Picks the hook that makes the WebView from [attaching] (the first with a factory, null for a plain WebView), and the keys of the others whose factory is a different object. */
123
118
  internal fun pickFactory(attaching: List<MinimalWebViewHooks.Hook>): Pair<MinimalWebViewHooks.Hook?, List<String>> {
124
119
  val named = attaching.filter { it.webViewFactory != null }
125
120
  val maker = named.firstOrNull()
@@ -127,10 +122,9 @@ internal fun pickFactory(attaching: List<MinimalWebViewHooks.Hook>): Pair<Minima
127
122
  }
128
123
 
129
124
  /**
130
- * Picks the hook client that gets a decision callback: the first of the clients that override it. It calls [warn] with
131
- * a warning naming the callback, once per callback and reason: when more than one client overrides it,
132
- * and, when the caller passes `lost` (what stops applying once a client takes the decision: the app's props or their
133
- * defaults that would decide it otherwise), when one client takes it.
125
+ * Picks the first of the clients that override a decision callback, or null. Calls [warn] once per callback and reason:
126
+ * - more than one client overrides the callback;
127
+ * - a client takes it, when the caller passes `lost`: what stops applying, the app's props or their defaults that would decide it otherwise.
134
128
  */
135
129
  internal class Deciders(private val warn: (String) -> Unit) {
136
130
  // Concurrent: shouldInterceptRequest decides on Chromium's IO thread.
@@ -166,8 +160,8 @@ internal class Deciders(private val warn: (String) -> Unit) {
166
160
  * turns on.
167
161
  *
168
162
  * A context kept after its attach ended (the view closed, or a renderer crash replaced the WebView) does nothing and
169
- * holds nothing of the WebView: its lists are emptied and reach no WebView, its handlers are dropped once the
170
- * [onDestroyed] ones ran, its [url] is empty and its [emit] reaches nothing.
163
+ * holds nothing of the WebView.
164
+ * @see [Native hooks guide](https://rasmuskard.github.io/react-native-minimal-webview/guides/native-hooks/)
171
165
  */
172
166
  interface WebViewContext {
173
167
  /**
@@ -186,12 +180,15 @@ interface WebViewContext {
186
180
  val url: String
187
181
 
188
182
  /**
189
- * The hook clients, in order; add yours in `attach`. While the hook is off, none of them gets a callback.
183
+ * Your clients, in order; add them in `attach`. While the hook is off, none of them gets a callback.
190
184
  *
191
185
  * Each callback reaches the clients by one of these rules:
192
- * - A callback that returns a decision goes to the first client that overrides it, instead of the core and the
193
- * app's props.
186
+ * - A callback that decides something, by its return value or through the handler, request or callback it gets
187
+ * (`onReceivedSslError`, `onReceivedHttpAuthRequest`, `onReceivedClientCertRequest`), goes to the first client
188
+ * that overrides it, instead of the core and the app's props.
194
189
  * - Every other callback reaches the core first, then each client that overrides it.
190
+ * - `onRenderProcessGone` is the exception: it reaches every client that overrides it, and the core returns true and
191
+ * replaces the WebView, so a client's return value is ignored.
195
192
  *
196
193
  * Taking a decision the core makes from the app's props or their defaults switches them off, the default navigation
197
194
  * rules' security checks included, and a warning names the callback and what stops applying.
@@ -203,17 +200,16 @@ interface WebViewContext {
203
200
  * A decision more than one client overrides still goes only to the first, and a warning names it. Each warning
204
201
  * comes once per WebView, when its decision first comes.
205
202
  *
206
- * Overriding a variant the base class forwards to counts as overriding the callback: [WebViewClientCompat]'s
207
- * `onReceivedError`, `onSafeBrowsingHit` and `shouldOverrideUrlLoading(WebView, String)`, and the platform's
208
- * deprecated `shouldOverrideUrlLoading(WebView, String)`, `shouldInterceptRequest(WebView, String)` and 4-argument
209
- * `onReceivedError`.
203
+ * Overriding a variant the base class forwards to counts as overriding the callback. The variants are:
204
+ * - [WebViewClientCompat]'s `onReceivedError`, `onSafeBrowsingHit` and `shouldOverrideUrlLoading(WebView, String)`.
205
+ * - The platform's deprecated `shouldOverrideUrlLoading(WebView, String)`, `shouldInterceptRequest(WebView, String)` and 4-argument `onReceivedError`.
210
206
  *
211
207
  * `shouldInterceptRequest` runs on a background thread.
212
208
  */
213
209
  val clients: MutableList<WebViewClient>
214
210
 
215
211
  /**
216
- * The hook chrome clients, routed as [clients] are.
212
+ * Your chrome clients, routed as [clients] are.
217
213
  *
218
214
  * Overriding the deprecated `onConsoleMessage(String, Int, String)` counts as overriding `onConsoleMessage`.
219
215
  * Favicon downloads are off, so `onReceivedIcon` gets no icon until the hook's `attach` turns `downloadFaviconsEnabled`
@@ -222,12 +218,12 @@ interface WebViewContext {
222
218
  val chromeClients: MutableList<WebChromeClient>
223
219
 
224
220
  /**
225
- * The hooks' touch listeners, in order, called until one returns true: that one consumes the touch, which neither the
221
+ * Your touch listeners, in order, called until one returns true: that one consumes the touch, which neither the
226
222
  * later listeners nor the WebView get.
227
223
  */
228
224
  val touchListeners: MutableList<View.OnTouchListener>
229
225
 
230
- /** The hooks' scroll listeners: each one gets every scroll change, in order. */
226
+ /** Your scroll listeners: each one gets every scroll change, in order. */
231
227
  val scrollListeners: MutableList<View.OnScrollChangeListener>
232
228
 
233
229
  /**
@@ -250,8 +246,7 @@ interface WebViewContext {
250
246
  * Runs [handler] at once with this hook's extension's `options`, then with the new ones each time they change, live
251
247
  * on the same WebView; null while the hook is off.
252
248
  *
253
- * The hook turns off when the extension is removed, or its `options` become null or false. A change from one off
254
- * value to another doesn't run it, and a context kept after its attach ended never does.
249
+ * A change from one off value to another doesn't run it, and a context kept after its attach ended never does.
255
250
  */
256
251
  fun onOptions(handler: (options: Any?) -> Unit)
257
252
 
@@ -276,8 +271,8 @@ interface WebViewContext {
276
271
  * arguments (an unknown disposition or MIME type is empty), before the `onDownload` prop and the core's opening it
277
272
  * externally.
278
273
  *
279
- * Return true to take it: neither of those gets it then. The hooks that are on are offered it in registration order,
280
- * and the first that takes it ends the round.
274
+ * Return true to take it: neither of those gets it then. The hooks that are on are offered it in the order they
275
+ * attached (registration order, then those attached later), and the first that takes it ends the round.
281
276
  */
282
277
  fun onDownloadStart(
283
278
  handler: (url: String, userAgent: String, contentDisposition: String, mimeType: String, contentLength: Long) -> Boolean
@@ -308,7 +303,7 @@ class HookReply internal constructor(
308
303
  ) : (Any?) -> Unit {
309
304
  private val settled = AtomicBoolean()
310
305
 
311
- /** Resolves the JS call with [value]. A value JSON can't encode rejects it with `native_error` instead. */
306
+ /** Resolves the JS call with [value]: strings, booleans, numbers, and `Map`s, `Collection`s and `Array`s of them cross as JSON; any other object, a primitive array such as `IntArray` included, arrives as null, and a non-finite number rejects the call with `native_error` instead. */
312
307
  override fun invoke(value: Any?) {
313
308
  if (settled.compareAndSet(false, true)) resolve(value)
314
309
  }
@@ -322,7 +317,7 @@ class HookReply internal constructor(
322
317
  /**
323
318
  * [HookContext]'s base: the hook's `hookOptions` value (null while its key is absent), its lists, and whether the core
324
319
  * routes them. Chromium's IO thread reads [routed] and [clients] (shouldInterceptRequest), so [options] and the detach
325
- * are volatile; the rest is main thread only. [detach] empties the lists and drops the handlers.
320
+ * are volatile; the rest is main thread only.
326
321
  */
327
322
  internal open class Attachment(value: Any?) {
328
323
  @Volatile var options: Any? = value
@@ -342,7 +337,6 @@ internal open class Attachment(value: Any?) {
342
337
  /** Whether the hook is on and the attach is still there: the core routes the lists and passes events and asks. */
343
338
  val routed get() = options != null && !detached
344
339
 
345
- /** Runs [handler] with the options now and after each change; never once detached. */
346
340
  fun onOptions(handler: (Any?) -> Unit) {
347
341
  if (detached) return
348
342
  optionsHandlers += handler
@@ -370,7 +364,6 @@ internal open class Attachment(value: Any?) {
370
364
  downloadHandlers += handler
371
365
  }
372
366
 
373
- /** Whether one of the download handlers took the download; none is offered it while the hook is off or detached. */
374
367
  fun downloadStarted(url: String, userAgent: String, contentDisposition: String, mimeType: String, contentLength: Long) =
375
368
  routed && downloadHandlers.any { it(url, userAgent, contentDisposition, mimeType, contentLength) }
376
369
 
@@ -383,7 +376,6 @@ internal open class Attachment(value: Any?) {
383
376
  }
384
377
  }
385
378
 
386
- /** The lists [pick] takes from the [attachments] that are [routed][Attachment.routed], one after the other. */
387
379
  internal fun <T> routed(attachments: List<Attachment>, pick: (Attachment) -> List<T>) =
388
380
  attachments.filter { it.routed }.flatMap(pick)
389
381
 
@@ -430,7 +422,6 @@ internal class HookContext(val hook: MinimalWebViewHooks.Hook, view: MinimalWebV
430
422
 
431
423
  fun documentEnded(reason: DocumentEnd) = documentEndHandlers.forEach { it(reason) }
432
424
 
433
- /** The attach's WebView is destroyed: the handlers run once, and the context drops them. */
434
425
  fun destroyed(reason: DocumentEnd) {
435
426
  val handlers = destroyedHandlers.toList()
436
427
  destroyedHandlers.clear()
@@ -41,7 +41,7 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
41
41
  private val navigation = MinimalWebViewNavigation(this) { onNavigation(it) }
42
42
  private val scripts = MinimalWebViewScripts(this) { onBridge(it) }
43
43
 
44
- /** Set by the first prop batch and replaced after a renderer crash; while [recovering] it is the destroyed one. */
44
+ /** Set by the first prop batch and replaced after a renderer crash; see [recovering]. */
45
45
  internal lateinit var webView: WebView
46
46
  private set
47
47
  private val hasWebView get() = ::webView.isInitialized
@@ -79,7 +79,7 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
79
79
  internal val fullscreen = FullscreenVideo(this)
80
80
  internal val permissions = Permissions(this)
81
81
  private val downloads = Downloads(this)
82
- /** The keys of the extensions that are on (`hookOptions`) the first WebView was made with, and those attached later: they pick the hooks, also for one after a crash. */
82
+ /** Keys of the extensions that are on in `hookOptions` when the first WebView is made, plus those attached later. They pick the hooks again for the WebView built after a crash. */
83
83
  private var hookKeys: Set<String> = emptySet()
84
84
  /** The hooks' contexts for the current WebView, in attach order. Chromium's IO thread reads it (shouldInterceptRequest). */
85
85
  @Volatile private var hookContexts: List<HookContext> = emptyList()
@@ -98,7 +98,7 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
98
98
  private var lastEmitted: Map<String, Any?>? = null
99
99
  private var emitScheduled = false
100
100
 
101
- /** From a render process death until [recover] builds the new WebView: whether it loads, and the dead one's history. */
101
+ /** From a renderer death until [recover] builds the new WebView: whether it loads, and the dead one's history. */
102
102
  private var pendingRecovery: Recovery? = null
103
103
  private class Recovery(val reload: Boolean, val history: Bundle?)
104
104
  private var destroyed = false
@@ -333,7 +333,7 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
333
333
  if (recovering) onResult(Result.failure(EvaluateError("unavailable", RECOVERING))) else scripts.evaluate(script, onResult)
334
334
 
335
335
  /**
336
- * The render process died. The WebView can't be reused: it goes now, after saving its history. The new one is built
336
+ * The renderer died. The WebView can't be reused: it goes now, after saving its history. The new one is built
337
337
  * at once if the view can be seen, else once it can (Android's guidance: not in the background).
338
338
  */
339
339
  internal fun processGone(cause: String, at: Long) {
@@ -395,10 +395,7 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
395
395
  tearDown(DocumentEnd.CLOSING)
396
396
  }
397
397
 
398
- /**
399
- * Ends the Document with [reason] and destroys the WebView: the hooks detach, the WebView leaves the layout and is
400
- * destroyed, and then the detached hooks' onDestroyed handlers run.
401
- */
398
+ /** Ends the Document with [reason] and destroys the WebView. The detached hooks' onDestroyed handlers run after it is destroyed. */
402
399
  private fun tearDown(reason: DocumentEnd) {
403
400
  endDocument(reason)
404
401
  val detached = hookContexts
@@ -462,7 +459,7 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
462
459
  internal const val TAG = "MinimalWebView"
463
460
  internal const val RECOVERING = "the WebView is being rebuilt after its renderer died"
464
461
 
465
- /** Whether this process has made a WebView, so WebView is started. */
462
+ /** Whether this process has made a WebView; until then WebView isn't started. */
466
463
  @Volatile internal var webViewCreated = false
467
464
 
468
465
  /** What `setWebContentsDebuggingEnabled` set; null until it is called. */
@@ -493,7 +490,7 @@ internal fun showsSource(source: WebViewSource?, url: String): Boolean {
493
490
  }
494
491
 
495
492
  /**
496
- * Records a render process death at [now] in [times] and says whether to reload after it: not after more than
493
+ * Records a renderer death at [now] in [times] and says whether to reload after it: not after more than
497
494
  * [MAX_CRASHES_PER_WINDOW] in [CRASH_WINDOW_MS]. Every WebView on the renderer hears of its death, so one within
498
495
  * [SAME_CRASH_MS] of the last is that same death.
499
496
  */
@@ -30,7 +30,7 @@ import androidx.webkit.NavigationListener
30
30
  import androidx.webkit.Page
31
31
 
32
32
  // WebView's callbacks, a new set for each WebView. Each one routes by the rule on WebViewContext.clients: a decision
33
- // callback through `deciding` (with no hook client, the core or WebView's default decides), the rest through `observing`.
33
+ // callback through `deciding`, the rest through `observing`.
34
34
 
35
35
  internal class Listener(private val owner: MinimalWebView) : NavigationListener {
36
36
  /** Pages that fired their load event and are still alive (current or in the back-forward cache). */
@@ -94,8 +94,8 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
94
94
  private inline fun observing(name: String, vararg types: Class<*>, block: (WebViewClient) -> Unit) =
95
95
  owner.clients.forEach { if (it.overrides(name, *types)) block(it) }
96
96
 
97
- // Without NavigationListener: the last main-frame URL allowed to load (a page's navigation or a redirect), which
98
- // onReceivedSslError can't otherwise tell from a subresource.
97
+ // Without NavigationListener: the last main-frame URL allowed to load (a page's navigation or a redirect), for
98
+ // onReceivedSslError.
99
99
  private var allowedMainFrameUrl: String? = null
100
100
 
101
101
  // Not called for POST, the initial loadUrl, or reissued loads; called again for their redirects.
@@ -139,7 +139,7 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
139
139
  override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? =
140
140
  deciding("shouldInterceptRequest", WEB_VIEW, WebResourceRequest::class.java)?.shouldInterceptRequest(view, request)
141
141
 
142
- // Main frame only: subresource failures (an ad's 404) are the page's business.
142
+ // Main frame only: a subresource that fails to load (an ad) is the page's business.
143
143
  override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) {
144
144
  val description = error.description.toString()
145
145
  if (request.isForMainFrame && !description.contains("ERR_ABORTED")) {
@@ -158,7 +158,7 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
158
158
  if (hook != null) hook.onFormResubmission(view, dontResend, resend) else super.onFormResubmission(view, dontResend, resend)
159
159
  }
160
160
 
161
- // Best-effort URL tracking when WebView updates are disabled and NAVIGATION_LISTENER is missing.
161
+ // Without NavigationListener (WebView older than 146): best-effort URL tracking.
162
162
  override fun doUpdateVisitedHistory(view: WebView, url: String?, isReload: Boolean) {
163
163
  if (!owner.hasNavigationListener && url != null) {
164
164
  owner.url = url
@@ -238,7 +238,6 @@ internal class ChromeClient(private val owner: MinimalWebView, private val navig
238
238
  )?.onCreateWindow(view, isDialog, isUserGesture, resultMsg)
239
239
  ?: navigation.createWindow(isUserGesture, resultMsg)
240
240
 
241
- // A hook client, else the app's prop (onFileRequest), else the system chooser (its intent ignores `capture`).
242
241
  override fun onShowFileChooser(view: WebView, callback: ValueCallback<Array<Uri>>, params: FileChooserParams): Boolean {
243
242
  val once = owner.fileUpload.hold(callback) // before the hook branch: a hook's chooser is held too
244
243
  val hook = deciding(
@@ -40,9 +40,9 @@ class MinimalWebViewModule : Module() {
40
40
  private var chooserOpen = false
41
41
 
42
42
  /**
43
- * The system file chooser (ChromeClient.onShowFileChooser), one at a time app-wide: the launcher keeps one callback,
44
- * so a request while one is open gets null at once, as does one before the launcher is registered or without an
45
- * activity. Otherwise [onResult] gets the picked URIs, or null on cancel.
43
+ * Opens the system file chooser (from ChromeClient.onShowFileChooser) and calls [onResult] with the picked URIs, or
44
+ * null on cancel. One chooser is open app-wide: the launcher keeps one callback, so [onResult] gets null at once
45
+ * while one is open, before the launcher is registered, or without an activity.
46
46
  */
47
47
  internal fun openFileChooser(intent: Intent, onResult: (Array<Uri>?) -> Unit) {
48
48
  val launcher = fileChooser
@@ -154,7 +154,7 @@ private fun flushCookies() {
154
154
  store.allProfileNames.forEach { store.getProfile(it)?.cookieManager?.flush() }
155
155
  }
156
156
 
157
- /** Before the first WebView only stored, for each new WebView to apply: setting it now would start WebView. */
157
+ /** Before the first WebView exists, only stores `enabled` for each new WebView to apply: setting it now would start WebView. */
158
158
  private fun setWebContentsDebugging(enabled: Boolean) {
159
159
  webContentsDebugging = enabled
160
160
  if (webViewCreated) WebView.setWebContentsDebuggingEnabled(enabled)
@@ -45,7 +45,7 @@ internal class MinimalWebViewScripts(private val owner: MinimalWebView, private
45
45
  // JS learns of it: calls reject with `unavailable`.
46
46
  try {
47
47
  WebViewCompat.addWebMessageListener(webView, "nativeBridgeTransport", origins) { _, message, sourceOrigin, isMainFrame, proxy ->
48
- // Main frame only, like iOS. The origin rules already filtered the sender; its origin goes to the handlers.
48
+ // Main frame only, like iOS. The origin rules already filtered the sender.
49
49
  if (!isMainFrame) return@addWebMessageListener
50
50
  // An ArrayBuffer has no string data (`data` throws); iOS drops a non-string message too.
51
51
  if (message.type != WebMessageCompat.TYPE_STRING) return@addWebMessageListener
@@ -81,8 +81,10 @@ internal class MinimalWebViewScripts(private val owner: MinimalWebView, private
81
81
  replyProxy?.postMessage(message)
82
82
  }
83
83
 
84
- /** The Document ended: its evaluations fail and its reply proxy is gone. JS queues bridge messages until the next
85
- * page is ready; at unmount it rejects what is in flight itself. */
84
+ /**
85
+ * The Document ended: its evaluations fail and its reply proxy is gone. JS queues bridge messages until the next
86
+ * page is ready; at unmount it rejects what is in flight itself.
87
+ */
86
88
  fun documentEnded(reason: DocumentEnd) {
87
89
  evaluations.failAll()
88
90
  // At a commit this runs one main-thread hop after Chromium's (the NavigationListener's executor posts it), and
@@ -91,18 +93,22 @@ internal class MinimalWebViewScripts(private val owner: MinimalWebView, private
91
93
  if (reason != DocumentEnd.CLOSING && owner.bridgeScript != null) onBridge(mapOf("navigated" to true))
92
94
  }
93
95
 
94
- /** `evaluate` results come back through one global in every frame (`*`, before the first document); only the main
95
- * frame's replies count. A page can forge them, as it can already shape any value its own world returns. */
96
+ /**
97
+ * `evaluate` results come back through one global in every frame (`*`, before the first document). A page can forge
98
+ * them, as it can already shape any value its own world returns.
99
+ */
96
100
  private fun installEvaluate() {
97
101
  if (!WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) return
98
102
  WebViewCompat.addWebMessageListener(webView, EVALUATE, setOf("*")) { _, message, _, isMainFrame, _ ->
99
- // An ArrayBuffer has no string data (`data` throws).
103
+ // As in installBridge: only string messages.
100
104
  if (message.type == WebMessageCompat.TYPE_STRING) evaluations.settle(message.data, isMainFrame)
101
105
  }
102
106
  }
103
107
 
104
- /** The `evaluate` ref method. A new document rejects what is still waiting: WebView drops the callback when the
105
- * document is replaced first. */
108
+ /**
109
+ * The `evaluate` ref method. A new Document rejects what is still waiting: WebView drops the callback when the
110
+ * document is replaced first.
111
+ */
106
112
  fun evaluate(script: String, onResult: (Result<String>) -> Unit) {
107
113
  if (!WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) {
108
114
  return onResult(failure("unavailable", "evaluate needs WEB_MESSAGE_LISTENER; update Android System WebView"))
@@ -22,9 +22,9 @@ import kotlin.math.truncate
22
22
  * `CookieManager.set…(webView, …)`. [get] reads through the matching getter and [call] invokes a method; for those two,
23
23
  * `cookieManager` and `webStorage`, the WebView profile's, are roots as well.
24
24
  *
25
- * Only public SDK methods: `getMethods()` returns nothing else, and reflection on them is allowed. A key with no public
26
- * setter for the value's type, a feature this device's WebView lacks (`UnsupportedOperationException`) or a method the
27
- * core owns is reported and skipped; nothing here throws at the caller except [get] and [call], which reject.
25
+ * Only public SDK methods are reached: `getMethods()` returns nothing else. A key that can't be applied (no public
26
+ * setter for the value's type, a feature this device's WebView lacks, a method the core owns) is skipped and returned
27
+ * by [apply].
28
28
  */
29
29
  internal class PlatformSettings(private val targets: (root: String) -> List<Target>?) {
30
30
  /** `root.key` -> the last value applied or rejected, so an unchanged value is neither applied nor reported again. */
@@ -108,10 +108,10 @@ internal class PlatformSettings(private val targets: (root: String) -> List<Targ
108
108
  }
109
109
 
110
110
  /**
111
- * `root.method` with [args], a public method the core doesn't own. [reply] gets the result as JSON: the method's
112
- * return value, or, when no overload takes just [args], the value that the first overload with a trailing
113
- * `ValueCallback` reports later. [reply] gets the JSON as a function that throws a [PlatformException] for a value
114
- * JSON can't carry. Throws a [PlatformException].
111
+ * `root.method` with [args], a public method the core doesn't own. [reply] gets a function that returns the result as
112
+ * JSON, or throws a [PlatformException] for a value JSON can't carry. The result is the method's return value or, when
113
+ * no overload takes just [args], the value that the first overload with a trailing `ValueCallback` reports later.
114
+ * Throws a [PlatformException].
115
115
  */
116
116
  fun call(path: String, args: List<Any?>, reply: (() -> String) -> Unit) {
117
117
  val (targets, name) = resolve(path)
@@ -134,10 +134,7 @@ internal class PlatformSettings(private val targets: (root: String) -> List<Targ
134
134
  internal companion object {
135
135
  private val NONE = Any()
136
136
 
137
- /**
138
- * The targets of [root] on [webView], or null for an unknown root. `cookieManager` and `webStorage` are the WebView
139
- * profile's ([profileOf]).
140
- */
137
+ /** The targets of [root] on [webView], or null for an unknown root. */
141
138
  fun targets(webView: WebView, root: String): List<Target>? = when (root) {
142
139
  "settings" -> listOf(
143
140
  Target(WebSettings::class.java, webView.settings, null),
@@ -211,7 +208,7 @@ internal class PlatformSettings(private val targets: (root: String) -> List<Targ
211
208
  return if (seen) "no public setter takes a ${value?.javaClass?.simpleName ?: "null"}" else "no public setter"
212
209
  }
213
210
 
214
- /** [key]'s getter value (`getKey`, `isKey` or a non-void `key()`) on the first target that has one, or [NONE]. */
211
+ /** The value of [key]'s getter on the first target that has one, or [NONE]. */
215
212
  private fun read(targets: List<Target>, key: String): Any? {
216
213
  val capital = key.replaceFirstChar { it.uppercaseChar() }
217
214
  for (target in targets) {
@@ -285,8 +282,8 @@ internal class PlatformSettings(private val targets: (root: String) -> List<Targ
285
282
  private fun notFound(reason: String) = PlatformException("not_found", reason)
286
283
 
287
284
  /**
288
- * A getter's or method's result as JSON: primitives, strings, lists and maps of them; anything else is null. A
289
- * non-finite number throws: JSON has none.
285
+ * A getter's or method's result as JSON: primitives, strings, collections and maps of them; anything else is null.
286
+ * A non-finite number throws: JSON has none.
290
287
  */
291
288
  fun toJson(value: Any?): String = jsonable(value).let { if (it is String) JSONObject.quote(it) else it.toString() }
292
289
 
@@ -295,12 +292,12 @@ internal class PlatformSettings(private val targets: (root: String) -> List<Targ
295
292
  is Double, is Float -> if ((value as Number).toDouble().isFinite()) value else throw problem("$value is not JSON")
296
293
  is Boolean, is Number, is String -> value
297
294
  is Map<*, *> -> JSONObject(value.mapKeys { it.key.toString() }.mapValues { jsonable(it.value) })
298
- is List<*> -> JSONArray(value.map(::jsonable))
295
+ is Collection<*> -> JSONArray(value.map(::jsonable))
299
296
  is Array<*> -> JSONArray(value.map(::jsonable))
300
297
  else -> JSONObject.NULL
301
298
  }
302
299
  }
303
300
  }
304
301
 
305
- /** Why [PlatformSettings.get] or [PlatformSettings.call] failed; [code] is the JS error code. */
302
+ /** Why [PlatformSettings.get] or [PlatformSettings.call] failed; [code] is the JS error code (`not_found`, `native_error` or `unavailable`). */
306
303
  internal class PlatformException(val code: String, message: String) : IllegalArgumentException(message)