react-native-minimal-webview 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/README.md +35 -31
  2. package/android/build.gradle +1 -1
  3. package/android/src/main/java/expo/modules/minimalwebview/Asks.kt +5 -11
  4. package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +17 -11
  5. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +83 -125
  6. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +16 -31
  7. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +18 -19
  8. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +24 -38
  9. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +24 -36
  10. package/android/src/main/java/expo/modules/minimalwebview/NavigationRules.kt +19 -20
  11. package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +41 -37
  12. package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +14 -18
  13. package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +12 -23
  14. package/android/src/main/java/expo/modules/minimalwebview/requests/FileUpload.kt +0 -1
  15. package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +1 -4
  16. package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +34 -24
  17. package/build/WebView.d.ts +11 -2
  18. package/build/WebView.d.ts.map +1 -1
  19. package/build/WebView.js +45 -71
  20. package/build/WebView.js.map +1 -1
  21. package/build/bridge/createBridge.d.ts +1 -5
  22. package/build/bridge/createBridge.d.ts.map +1 -1
  23. package/build/bridge/createBridge.js +3 -15
  24. package/build/bridge/createBridge.js.map +1 -1
  25. package/build/bridge/endpoint.d.ts +1 -2
  26. package/build/bridge/endpoint.d.ts.map +1 -1
  27. package/build/bridge/endpoint.js +5 -6
  28. package/build/bridge/endpoint.js.map +1 -1
  29. package/build/bridge/matchesOrigin.d.ts +11 -0
  30. package/build/bridge/matchesOrigin.d.ts.map +1 -0
  31. package/build/bridge/matchesOrigin.js +26 -0
  32. package/build/bridge/matchesOrigin.js.map +1 -0
  33. package/build/bridge/origins.d.ts +2 -13
  34. package/build/bridge/origins.d.ts.map +1 -1
  35. package/build/bridge/origins.js +1 -30
  36. package/build/bridge/origins.js.map +1 -1
  37. package/build/bridge/pageClient.generated.d.ts +1 -1
  38. package/build/bridge/pageClient.generated.d.ts.map +1 -1
  39. package/build/bridge/pageClient.generated.js +2 -2
  40. package/build/bridge/pageClient.generated.js.map +1 -1
  41. package/build/bridge/protocol.d.ts +3 -5
  42. package/build/bridge/protocol.d.ts.map +1 -1
  43. package/build/bridge/protocol.js +12 -14
  44. package/build/bridge/protocol.js.map +1 -1
  45. package/build/index.d.ts +1 -1
  46. package/build/index.js +1 -1
  47. package/build/navigationRules.d.ts +0 -5
  48. package/build/navigationRules.d.ts.map +1 -1
  49. package/build/navigationRules.js +3 -12
  50. package/build/navigationRules.js.map +1 -1
  51. package/build/reactNativeWebViewDefaults.d.ts +0 -4
  52. package/build/reactNativeWebViewDefaults.d.ts.map +1 -1
  53. package/build/reactNativeWebViewDefaults.js +0 -4
  54. package/build/reactNativeWebViewDefaults.js.map +1 -1
  55. package/build/reactNativeWebViewMessages.d.ts.map +1 -1
  56. package/build/reactNativeWebViewMessages.js +0 -1
  57. package/build/reactNativeWebViewMessages.js.map +1 -1
  58. package/build/refStore.d.ts +0 -2
  59. package/build/refStore.d.ts.map +1 -1
  60. package/build/refStore.js +0 -6
  61. package/build/refStore.js.map +1 -1
  62. package/build/types.d.ts +55 -39
  63. package/build/types.d.ts.map +1 -1
  64. package/ios/Asks.swift +6 -9
  65. package/ios/DelegateProxy.swift +4 -18
  66. package/ios/DownloadName.swift +0 -2
  67. package/ios/Downloads.swift +0 -2
  68. package/ios/Hooks.swift +4 -6
  69. package/ios/Loads.swift +37 -19
  70. package/ios/MinimalWebView+Dialogs.swift +5 -7
  71. package/ios/MinimalWebView+Navigation.swift +23 -49
  72. package/ios/MinimalWebView+Scripts.swift +10 -17
  73. package/ios/MinimalWebView.podspec +1 -2
  74. package/ios/MinimalWebView.swift +63 -128
  75. package/ios/MinimalWebViewModule.swift +1 -18
  76. package/ios/NavigationRules.swift +2 -9
  77. package/ios/OriginRules.swift +4 -13
  78. package/ios/PlatformSettings.swift +9 -30
  79. package/ios/ReadAccess.swift +0 -2
  80. package/ios/Records.swift +18 -0
  81. package/ios/Recovery.swift +2 -8
  82. package/ios/SharedCookies.swift +10 -25
  83. package/mocks/MinimalWebView.ts +5 -0
  84. package/package.json +11 -10
  85. package/src/WebView.tsx +58 -80
  86. package/src/bridge/createBridge.ts +5 -20
  87. package/src/bridge/endpoint.ts +6 -9
  88. package/src/bridge/matchesOrigin.ts +27 -0
  89. package/src/bridge/origins.ts +2 -30
  90. package/src/bridge/pageClient.generated.ts +2 -2
  91. package/src/bridge/pageClient.ts +1 -7
  92. package/src/bridge/protocol.ts +16 -18
  93. package/src/index.ts +1 -1
  94. package/src/navigationRules.ts +6 -12
  95. package/src/reactNativeWebViewDefaults.ts +0 -4
  96. package/src/reactNativeWebViewMessages.ts +0 -1
  97. package/src/refStore.ts +0 -7
  98. package/src/types.ts +55 -39
@@ -6,6 +6,7 @@ import android.content.pm.ApplicationInfo
6
6
  import android.os.Bundle
7
7
  import android.os.Handler
8
8
  import android.os.Looper
9
+ import android.util.AndroidRuntimeException
9
10
  import android.util.Log
10
11
  import android.view.MotionEvent
11
12
  import android.view.View
@@ -36,21 +37,19 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
36
37
  private val onProcessGone by EventDispatcher<Map<String, Any?>>()
37
38
  private val onNavigation by EventDispatcher<Map<String, Any?>>()
38
39
 
39
- internal val hasNavigationListener = WebViewFeature.isFeatureSupported(WebViewFeature.NAVIGATION_LISTENER)
40
+ // Lazy: it loads the WebView provider, which throws without one, and createWebView() reports that.
41
+ internal val hasNavigationListener by lazy { WebViewFeature.isFeatureSupported(WebViewFeature.NAVIGATION_LISTENER) }
40
42
  private val navigation = MinimalWebViewNavigation(this) { onNavigation(it) }
41
43
  internal val scripts = MinimalWebViewScripts(this) { onBridge(it) }
42
44
 
43
- /** Set by the first prop batch and replaced after a renderer crash; see [recovering]. */
44
45
  internal lateinit var webView: WebView
45
46
  private set
46
47
  private val hasWebView get() = ::webView.isInitialized
47
48
 
48
- // Props, applied together in applyProps()
49
49
  internal var source: WebViewSource? = null
50
50
  internal var navigationRules: List<Map<String, Any?>>? = null
51
51
  internal var bridgeScript: String? = null
52
52
  internal var bridgeOrigins: List<String>? = null
53
- /** The `hookOptions` prop, made from the `extensions` prop's options: each hook's value by key. A change reaches the attached hooks (onOptions). */
54
53
  internal var hookOptions: Map<String, Any?> = emptyMap()
55
54
  set(value) {
56
55
  val old = field
@@ -58,69 +57,55 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
58
57
  if (hasWebView) optionsChanged(old)
59
58
  }
60
59
  internal var injectedScripts: List<InjectedScript>? = null
61
- /** The `android` prop: WebSettings and WebView setters by name, applied by [PlatformSettings]. */
62
60
  internal var settings: Map<String, Any?>? = null
63
- internal val platformSettings = PlatformSettings { PlatformSettings.targets(webView, it) }
61
+ internal val platformSettings = PlatformSettings({ hasNavigationListener }) { PlatformSettings.targets(webView, it) }
64
62
  private val refresher = PullToRefresh(this)
65
63
  internal var pullToRefresh = false
66
64
  set(value) {
67
65
  field = value
68
66
  refresher.layout.isEnabled = value
69
67
  }
70
- /**
71
- * The page requests JS has a prop for, by prop name (`onFileRequest`, `onDownload`, ...), and `onNavigation`, read when a
72
- * request comes or a decision is reported.
73
- */
68
+ /** The page requests JS has a prop for, by prop name (`onFileRequest`, `onDownload`, ...), and `onNavigation`. */
74
69
  internal var requestHandlers: Set<String> = emptySet()
75
70
  private var loadedSource: WebViewSource? = null
76
71
 
77
- // The hooks' lists: each context owns its own, and the core routes those of the hooks that are on, in attach order.
78
72
  val clients: List<WebViewClient> get() = routed(hookContexts) { it.clients }
79
73
  val chromeClients: List<WebChromeClient> get() = routed(hookContexts) { it.chromeClients }
80
74
  internal val fileUpload = FileUpload(this)
81
75
  internal val fullscreen = FullscreenVideo(this)
82
76
  internal val permissions = Permissions(this)
83
77
  private val downloads = Downloads(this)
84
- /** 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. */
85
- private var hookKeys: Set<String> = emptySet()
86
- /** The hooks' contexts for the current WebView, in attach order. Chromium's IO thread reads it (shouldInterceptRequest). */
78
+ private var keysToAttach: Set<String> = emptySet()
79
+ /** Chromium's IO thread reads it (shouldInterceptRequest). */
87
80
  @Volatile private var hookContexts: List<HookContext> = emptyList()
88
81
 
89
82
  internal val asks = Asks { onHookEvent(it) }
90
83
  internal val deciders = Deciders { message -> mainHandler.post { warn(message) } }
91
84
 
92
- // Navigation state: native owns it and tells JS. The clients (MinimalWebViewClients.kt) write it.
93
85
  internal var url = ""
94
86
  internal var pendingUrl: String? = null
95
87
  internal var title = ""
96
88
  internal var loading = false
97
89
  internal var progress = 0.0
98
- /** How the current load ends so far, "finished", "failed" or "cancelled"; JS sees it only once `loading` is false. */
99
- internal var outcome: String? = null
90
+ private var outcome: LoadOutcome? = null
100
91
  private var lastEmitted: Map<String, Any?>? = null
101
92
  private var emitScheduled = false
102
93
 
103
- /** From a renderer death until [recover] builds the new WebView: whether it loads, and the dead one's history. */
104
94
  private var pendingRecovery: Recovery? = null
105
- private class Recovery(val reload: Boolean, val history: Bundle?)
106
- /** The ref's `load` while a recovery waits: [recover] loads it instead of the dead WebView's page. */
95
+ private class Recovery(val reload: Boolean, val history: Bundle?, val restorable: Boolean)
107
96
  private var pendingLoad: String? = null
108
97
  private var destroyed = false
109
98
 
110
99
  init {
111
- // The WebView goes into the layout in setUp(); the prop only turns the pull on and off.
112
100
  addView(refresher.layout, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
113
101
  }
114
102
 
115
- private fun createWebView(): WebView {
116
- // recover() calls this while the dead WebView is still set: the keys and the one-time warnings carry over.
117
- val first = !hasWebView
118
- if (first) hookKeys = hookOptions.keys
119
- val (attaching, unregistered) = selectHooks(MinimalWebViewHooks.hooks, hookKeys)
103
+ private fun createWebView(first: Boolean): WebView {
104
+ if (first) keysToAttach = hookOptions.keys
105
+ val (attaching, unregistered) = selectHooks(MinimalWebViewHooks.hooks, keysToAttach)
120
106
  val (maker, unused) = pickFactory(attaching)
121
107
  val view = maker?.webViewFactory?.invoke(context) ?: WebView(context)
122
108
  hookContexts = attaching.map { HookContext(it, this) }
123
- // A typo, or a hook's module not linked or not rebuilt. Once: the WebView after a crash has the same keys.
124
109
  if (first) unregistered.forEach { warn("extension $it: no hook is registered under this key") }
125
110
  if (first) unused.forEach { warn("extension $it: its webViewFactory is not used, ${maker?.key}'s is") }
126
111
  // Before the package touches the WebView: some calls (WebViewCompat.setProfile) must come first.
@@ -138,14 +123,12 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
138
123
  }
139
124
  if (!taken && !downloads.onDownloadStart(download)) navigation.openDownload(url)
140
125
  }
141
- // View's slots hold one listener each: the hooks share them through their lists.
142
126
  view.setOnTouchListener(::touched)
143
127
  view.setOnScrollChangeListener(::scrolled)
144
128
  if (hasNavigationListener) WebViewCompat.addNavigationListener(view, context.mainExecutor, Listener(this))
145
129
  return view
146
130
  }
147
131
 
148
- // The on hooks' own lists, not copies: this runs for every touch event and scroll change.
149
132
  private fun touched(view: View, event: MotionEvent) =
150
133
  hookContexts.any { c -> c.routed && c.touchListeners.any { it.onTouch(view, event) } }
151
134
 
@@ -158,52 +141,45 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
158
141
  @SuppressLint("SetJavaScriptEnabled") // because a browser-tab WebView needs JS; no addJavascriptInterface is used
159
142
  private fun configure(settings: WebSettings) {
160
143
  settings.javaScriptEnabled = true
161
- // A tap's window.open and target=_blank reach onCreateWindow; the navigation rules decide (newWindow: true).
162
- // Without a gesture only when the app opts in (javaScriptCanOpenWindowsAutomatically, in applySettings).
163
144
  settings.setSupportMultipleWindows(true)
164
145
  settings.domStorageEnabled = true
165
146
  settings.allowFileAccess = false
166
147
  settings.allowContentAccess = false
167
148
  settings.mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
168
- // Pinch-zoom (an accessibility basic; pages opt out with a viewport meta), without the legacy +/- buttons.
169
149
  settings.builtInZoomControls = true
170
150
  settings.displayZoomControls = false
171
- // Back and forward restore the page instead of reloading it, as WebKit does. `android.settings` applies after this.
172
151
  // Not without NavigationListener: WebView 133 sends onPageStarted for a restored page but no onPageFinished.
173
152
  if (hasNavigationListener && WebViewFeature.isFeatureSupported(WebViewFeature.BACK_FORWARD_CACHE)) {
174
153
  WebSettingsCompat.setBackForwardCacheEnabled(settings, true)
175
154
  }
176
- // No favicon requests: nothing shows them.
177
155
  if (WebViewFeature.isFeatureSupported(WebViewFeature.DOWNLOAD_FAVICONS_ENABLED)) {
178
156
  WebSettingsCompat.setDownloadFaviconsEnabled(settings, false)
179
157
  }
180
158
  }
181
159
 
182
- /** Called once per prop batch. `source` loads last so everything else is ready first. */
183
160
  internal fun applyProps() {
184
- // The dead WebView after a crash takes nothing: recover() applies the props to the new one.
185
161
  if (recovering) return
186
- // The first prop batch sets up the first WebView: the hooks get their options with it.
187
162
  if (hasWebView) {
188
163
  applySettings()
189
164
  scripts.update()
190
165
  } else {
191
- webView = createWebView()
166
+ webView = try {
167
+ createWebView(first = true)
168
+ } catch (e: AndroidRuntimeException) { // no WebView provider: missing, disabled or updating
169
+ return reportError("network", source?.uri.orEmpty(), WebViewClient.ERROR_UNKNOWN, "Android System WebView is unavailable: ${e.message}")
170
+ }
192
171
  setUp()
193
172
  }
194
173
  loadNewSource()
195
174
  }
196
175
 
197
- /** Loads `source` if it isn't the one loaded yet; returns whether it did. */
198
- private fun loadNewSource(): Boolean {
199
- val next = source ?: return false
200
- if (next == loadedSource) return false
176
+ private fun loadNewSource() {
177
+ val next = source ?: return
178
+ if (next == loadedSource) return
201
179
  loadedSource = next
202
180
  load(next)
203
- return true
204
181
  }
205
182
 
206
- /** Readies a new WebView, the first or the one after a crash, in one order: settings, layout, hooks, scripts. */
207
183
  private fun setUp() {
208
184
  applySettings(force = true)
209
185
  // addView(view) alone would give the view WRAP_CONTENT, and Chromium then resolves CSS vh to 0.
@@ -218,7 +194,7 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
218
194
  if (source.uri == null) {
219
195
  webView.loadDataWithBaseURL(source.baseUrl, source.html ?: "", "text/html", "utf-8", null)
220
196
  } else if (source.body != null) {
221
- webView.postUrl(source.uri, source.body.toByteArray()) // form-urlencoded; postUrl takes no headers
197
+ webView.postUrl(source.uri, source.body.toByteArray())
222
198
  } else {
223
199
  webView.loadUrl(source.uri, source.headers.orEmpty())
224
200
  }
@@ -230,15 +206,11 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
230
206
  if (recovering) pendingLoad = url else webView.loadUrl(url)
231
207
  }
232
208
 
233
- /** Loads the page on screen again: the `source` when that is the page (its headers, html or POST), else its URL. */
234
209
  private fun loadAgain() {
235
210
  if (showsSource(source, url)) source?.let(::load) else if (url.isNotEmpty()) webView.loadUrl(url)
236
211
  }
237
212
 
238
- /**
239
- * The ref's reload: the app's retry starts the crash-loop guard over. Only this and [load] clear it: the guard counts
240
- * the process's renderer deaths, so another view's new source or pull-to-refresh mustn't end a crash loop's count.
241
- */
213
+ /** The ref's reload: the app's retry starts the crash-loop guard over. */
242
214
  internal fun retry() {
243
215
  crashTimes.clear()
244
216
  reload()
@@ -246,10 +218,9 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
246
218
 
247
219
  internal fun reload() {
248
220
  when {
249
- // The renderer died and the new WebView isn't built yet: build it now, and load.
250
- recovering -> recover(reload = true)
251
- // Nothing loaded: the crash-loop guard gave up (processGone), and this is the app's retry. Or a POST source:
252
- // WebView's reload declines its form resubmission.
221
+ recovering -> recover(forceLoad = true)
222
+ !hasWebView -> applyProps()
223
+ // A POST source: WebView's reload declines its form resubmission.
253
224
  webView.url == null || showingPost -> loadAgain()
254
225
  else -> webView.reload()
255
226
  }
@@ -257,18 +228,12 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
257
228
 
258
229
  private val showingPost get() = source?.body != null && showsSource(source, url)
259
230
 
260
- /**
261
- * The `android` settings, applied from each prop batch (only the keys that changed) and all again to a new WebView
262
- * after a crash. A key that can't be applied is reported to JS, which warns.
263
- */
264
231
  private fun applySettings(force: Boolean = false) {
265
232
  platformSettings.apply(settings, force).forEach { warn("android.${it["key"]}: ${it["reason"]}") }
266
233
  }
267
234
 
268
- /** A warning for the app's developer, which JS logs with console.warn. */
269
235
  internal fun warn(message: String) = emit("core", "warning", mapOf("message" to message))
270
236
 
271
- /** Tells each attached hook whose value changed, and attaches a hook without `configure` or `webViewFactory` whose key turns on. */
272
237
  private fun optionsChanged(old: Map<String, Any?>) {
273
238
  for (key in inRegistrationOrder(old.keys + hookOptions.keys, MinimalWebViewHooks.hooks.map { it.key })) {
274
239
  val value = hookOptions[key]
@@ -276,7 +241,7 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
276
241
  val context = hookContexts.find { it.key == key }
277
242
  if (context != null) {
278
243
  context.optionsChanged(value)
279
- } else if (key !in hookKeys && old[key] == null) {
244
+ } else if (key !in keysToAttach && old[key] == null) {
280
245
  attachLate(key)
281
246
  }
282
247
  }
@@ -285,13 +250,8 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
285
250
  private fun attachLate(key: String) {
286
251
  val hook = MinimalWebViewHooks.hooks.find { it.key == key }
287
252
  ?: return warn("extension $key: no hook is registered under this key")
288
- // configure runs before the package sets the WebView up, and a factory makes it: too late for one that exists.
289
- if (hook.configure != null || hook.webViewFactory != null) {
290
- val why = if (hook.configure != null) "configure" else "a webViewFactory"
291
- return warn("extension $key: its hook has $why, so it attaches only when the WebView is created")
292
- }
293
- hookKeys = hookKeys + key
294
- // The WebView the recovery builds attaches it with the others.
253
+ hook.whyNotLate?.let { return warn("extension $key: its hook has $it, so it attaches only when the WebView is created") }
254
+ keysToAttach = keysToAttach + key
295
255
  if (recovering) return
296
256
  val context = HookContext(hook, this)
297
257
  hookContexts = hookContexts + context
@@ -304,21 +264,18 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
304
264
  fun emit(key: String, name: String, payload: Map<String, Any?>) =
305
265
  onHookEvent(mapOf("key" to key, "name" to name, "payload" to payload))
306
266
 
307
- private var documentOpen = false
308
-
309
- internal fun endDocument(reason: DocumentEnd) {
310
- // The first commit after mount or a crash opens a Document and ends none: the asks and hooks don't hear it.
311
- val opening = reason == DocumentEnd.COMMITTED && !documentOpen
312
- documentOpen = reason == DocumentEnd.COMMITTED
313
- fileUpload.cancel()
314
- navigation.documentEnded()
315
- scripts.documentEnded(reason)
316
- fullscreen.documentEnded(reason)
317
- if (opening) return
318
- // The asks and hooks last, so a throw in hook or Chromium code can't skip the core's resets.
319
- asks.documentEnded(reason)
320
- hookContexts.forEach { it.documentEnded(reason) }
321
- }
267
+ internal val documents = Documents(
268
+ core = { reason ->
269
+ fileUpload.cancel()
270
+ navigation.documentEnded()
271
+ scripts.documentEnded(reason)
272
+ fullscreen.documentEnded(reason)
273
+ },
274
+ asksAndHooks = { reason ->
275
+ asks.documentEnded(reason)
276
+ hookContexts.forEach { it.documentEnded(reason) }
277
+ }
278
+ )
322
279
 
323
280
  internal fun loadStarted() {
324
281
  loading = true
@@ -326,7 +283,10 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
326
283
  stateChanged()
327
284
  }
328
285
 
329
- /** A load ended (callers set outcome first): loading stops, and the spinner with it. */
286
+ internal fun settleOutcome(value: LoadOutcome) {
287
+ outcome = outcome ?: value
288
+ }
289
+
330
290
  internal fun loadEnded() {
331
291
  loading = false
332
292
  refresher.pageFinished()
@@ -336,31 +296,25 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
336
296
  internal fun evaluate(script: String, onResult: (Result<String>) -> Unit) =
337
297
  if (recovering) onResult(Result.failure(EvaluateError("unavailable", RECOVERING))) else scripts.evaluate(script, onResult)
338
298
 
339
- /**
340
- * The renderer died. The WebView can't be reused: it goes now, after saving its history. The new one is built
341
- * at once if the view can be seen, else once it can (Android's guidance: not in the background).
342
- */
343
299
  internal fun processGone(cause: String, at: Long) {
344
300
  if (destroyed) return
345
301
  val reload = crashAllowsReload(crashTimes, at) && !showingPost
346
302
  // The source page reloads as the source: a restored entry carries neither source.headers nor an html source.
347
303
  val restorable = !showsSource(source, url)
348
- val history = Bundle().takeIf { reload && restorable && webView.saveState(it) != null }
304
+ val history = Bundle().takeIf { reload && webView.saveState(it) != null }
349
305
  tearDown(DocumentEnd.CRASHED)
350
- pendingRecovery = Recovery(reload, history)
351
- // Nothing will end the load the crash cut off. `url` stays: loadAgain() loads it.
352
- if (loading) outcome = "failed"
306
+ pendingRecovery = Recovery(reload, history, restorable)
307
+ if (loading) outcome = LoadOutcome.FAILED
353
308
  loading = false
354
309
  pendingUrl = null
355
310
  progress = 0.0
356
311
  refresher.pageFinished()
357
312
  onProcessGone(mapOf("cause" to cause, "recovered" to reload))
358
- // A detached view's window reports GONE: onWindowVisibilityChanged recovers once it is shown.
313
+ // A detached view's window reports GONE.
359
314
  if (windowVisibility == View.VISIBLE) recover()
360
- stateChanged() // after onProcessGone: the cut-off load ends as failed
315
+ stateChanged()
361
316
  }
362
317
 
363
- /** The renderer died and the new WebView isn't built yet: the one in [webView] is destroyed. */
364
318
  internal val recovering get() = pendingRecovery != null
365
319
 
366
320
  // Also on attach: dispatchAttachedToWindow calls this unless the window is GONE.
@@ -369,22 +323,19 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
369
323
  if (visibility == View.VISIBLE) recover()
370
324
  }
371
325
 
372
- /**
373
- * Builds the WebView that replaces the dead one and brings its history back, or else loads its page again. With
374
- * [reload] (the app's retry) it loads also when the crash-loop guard or a POST source held the reload back.
375
- */
376
- private fun recover(reload: Boolean = false) {
326
+ private fun recover(forceLoad: Boolean = false) {
377
327
  val recovery = pendingRecovery ?: return
378
328
  pendingRecovery = null
379
- webView = createWebView()
329
+ webView = createWebView(first = false)
380
330
  setUp()
381
- // A source the app set or a `load` it asked for while this waited loads instead of the old page.
382
- val loaded = loadNewSource()
383
- val asked = pendingLoad?.also(webView::loadUrl)
384
- pendingLoad = null
385
- if (!loaded && asked == null) {
386
- val restored = recovery.history?.let { webView.restoreState(it) } != null
387
- if (!restored && (recovery.reload || reload)) loadAgain()
331
+ val replaced = pendingLoad != null || source != null && source != loadedSource
332
+ val restored = (replaced || recovery.restorable) && recovery.history?.let { webView.restoreState(it) } != null
333
+ if (replaced) {
334
+ loadNewSource()
335
+ pendingLoad?.let(webView::loadUrl)
336
+ pendingLoad = null
337
+ } else if (!restored && (recovery.reload || forceLoad)) {
338
+ loadAgain()
388
339
  }
389
340
  stateChanged()
390
341
  }
@@ -392,18 +343,16 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
392
343
  internal fun destroy() {
393
344
  destroyed = true
394
345
  downloads.detach()
395
- // A crash tore the WebView down already, and detached the hooks; with none, there is nothing to tear down.
396
346
  if (!hasWebView || recovering) {
397
347
  pendingRecovery = null
398
- return endDocument(DocumentEnd.CLOSING)
348
+ return documents.end(DocumentEnd.CLOSING)
399
349
  }
400
350
  webView.stopLoading()
401
351
  tearDown(DocumentEnd.CLOSING)
402
352
  }
403
353
 
404
- /** Ends the Document with [reason] and destroys the WebView. The detached hooks' onDestroyed handlers run after it is destroyed. */
405
354
  private fun tearDown(reason: DocumentEnd) {
406
- endDocument(reason)
355
+ documents.end(reason)
407
356
  val detached = hookContexts
408
357
  detached.forEach { it.detach() }
409
358
  hookContexts = emptyList()
@@ -413,18 +362,15 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
413
362
  }
414
363
 
415
364
  internal fun reportError(kind: String, url: String, code: Int, description: String) {
416
- // A network or SSL error fails the load in progress; one with no load JS saw start (an SSL error before 146) doesn't.
417
- if (loading) outcome = "failed"
365
+ if (loading) outcome = LoadOutcome.FAILED
418
366
  onError(mapOf("kind" to kind, "url" to url, "code" to code, "description" to description))
419
367
  }
420
368
 
421
369
  internal fun reportHttpError(url: String, statusCode: Int) =
422
370
  onError(mapOf("kind" to "http", "url" to url, "statusCode" to statusCode))
423
371
 
424
- // Changes within one frame are combined into one event, except `loading` flips: a load that starts and fails
425
- // within one frame must still reach JS as loading true -> false (onLoadStart / onLoadEnd).
426
372
  internal fun stateChanged() {
427
- if (loading != lastEmitted?.get("loading")) return emitState()
373
+ if (loadingFlipped) return emitState()
428
374
  if (emitScheduled) return
429
375
  emitScheduled = true
430
376
  mainHandler.postDelayed({
@@ -433,9 +379,10 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
433
379
  }, FRAME_MS)
434
380
  }
435
381
 
382
+ private val loadingFlipped get() = loading != lastEmitted?.get("loading")
383
+
436
384
  private fun emitState() {
437
385
  if (destroyed) return
438
- // While a recovery waits, `webView` is the destroyed one: the history stays as JS saw it last.
439
386
  val (back, forward) = if (recovering) {
440
387
  (lastEmitted?.get("canGoBack") ?: false) to (lastEmitted?.get("canGoForward") ?: false)
441
388
  } else {
@@ -449,7 +396,7 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
449
396
  "progress" to progress,
450
397
  "canGoBack" to back,
451
398
  "canGoForward" to forward,
452
- "outcome" to if (loading) null else outcome
399
+ "outcome" to if (loading) null else outcome?.jsName
453
400
  )
454
401
  if (state == lastEmitted) return
455
402
  lastEmitted = state
@@ -464,14 +411,15 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
464
411
 
465
412
  internal const val TAG = "MinimalWebView"
466
413
 
414
+ internal enum class LoadOutcome(val jsName: String) { FINISHED("finished"), FAILED("failed"), CANCELLED("cancelled") }
415
+
467
416
  /**
468
- * The core's deferred work. Not View.post: a detached view (unmounted, or a covered screen) holds that until it is
469
- * attached again. Lazy: the JVM tests load this file, and Handler's constructor throws there.
417
+ * Not View.post: a detached view (unmounted, or a covered screen) holds that until it is attached again. Lazy: the JVM
418
+ * tests load this file, and Handler's constructor throws there.
470
419
  */
471
420
  internal val mainHandler by lazy { Handler(Looper.getMainLooper()) }
472
421
  internal const val RECOVERING = "the WebView is being rebuilt after its renderer died"
473
422
 
474
- /** Whether this process has made a WebView. */
475
423
  @Volatile internal var webViewCreated = false
476
424
 
477
425
  /** What `setWebContentsDebuggingEnabled` set; null until it is called. */
@@ -512,12 +460,23 @@ private fun canonicalUrl(url: String): String {
512
460
  return "$lower://$userinfo${host.lowercase()}$portPart${if (rest.startsWith('/')) rest else "/$rest"}"
513
461
  }
514
462
 
515
- // scheme "://" [userinfo "@"] host [":" port] rest
516
463
  private val urlAuthority = Regex("^([a-zA-Z][a-zA-Z0-9+.-]*)://([^/?#@]*@)?(\\[[^\\]/?#]*]|[^/?#:]*)(?::(\\d*))?(.*)$")
517
464
 
518
- /** The special schemes' default ports (the WHATWG URL Standard's), as on iOS (Loads.swift). */
465
+ /** The special schemes' default ports (the WHATWG URL Standard's). */
519
466
  internal val defaultPorts = mapOf("http" to 80, "https" to 443, "ws" to 80, "wss" to 443, "ftp" to 21)
520
467
 
468
+ /** The first commit after mount or a crash opens a Document and ends none: only [core] hears it. */
469
+ internal class Documents(private val core: (DocumentEnd) -> Unit, private val asksAndHooks: (DocumentEnd) -> Unit) {
470
+ private var open = false
471
+
472
+ fun end(reason: DocumentEnd) {
473
+ val opening = reason == DocumentEnd.COMMITTED && !open
474
+ open = reason == DocumentEnd.COMMITTED
475
+ core(reason)
476
+ if (!opening) asksAndHooks(reason)
477
+ }
478
+ }
479
+
521
480
  /**
522
481
  * Records a renderer death at [now] in [times] and says whether to reload after it: not after more than
523
482
  * [MAX_CRASHES_PER_WINDOW] in [CRASH_WINDOW_MS]. Every WebView on the renderer hears of its death, so one within
@@ -529,7 +488,6 @@ internal fun crashAllowsReload(times: ArrayDeque<Long>, now: Long): Boolean {
529
488
  return times.size <= MAX_CRASHES_PER_WINDOW
530
489
  }
531
490
 
532
- // shortcut: a fixed crash-loop guard, make it a prop if an app needs a different policy
533
491
  private const val MAX_CRASHES_PER_WINDOW = 3
534
492
  private const val CRASH_WINDOW_MS = 60_000L
535
493
  private const val SAME_CRASH_MS = 100L
@@ -1,6 +1,5 @@
1
1
  package expo.modules.minimalwebview
2
2
 
3
- import android.annotation.SuppressLint
4
3
  import android.graphics.Bitmap
5
4
  import android.net.Uri
6
5
  import android.net.http.SslError
@@ -29,11 +28,7 @@ import androidx.webkit.Navigation
29
28
  import androidx.webkit.NavigationListener
30
29
  import androidx.webkit.Page
31
30
 
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`, the rest through `observing`.
34
-
35
31
  internal class Listener(private val owner: MinimalWebView) : NavigationListener {
36
- /** Pages that fired their load event and are still alive (current or in the back-forward cache). */
37
32
  private val loadedPages = mutableSetOf<Page>()
38
33
 
39
34
  override fun onPageDeleted(page: Page) {
@@ -52,21 +47,20 @@ internal class Listener(private val owner: MinimalWebView) : NavigationListener
52
47
  owner.stateChanged()
53
48
  }
54
49
 
55
- // A failed main-frame load commits an error page at the failed URL: `url` becomes that URL, as on iOS.
56
50
  override fun onNavigationCompleted(navigation: Navigation) {
57
- // The Document ends before `url` moves on, so its handlers see the page that ended: as on iOS, and before 146,
58
- // where onPageStarted comes ahead of doUpdateVisitedHistory.
59
- if (navigation.didCommit() && !navigation.isSameDocument) owner.endDocument(DocumentEnd.COMMITTED)
51
+ if (navigation.didCommit() && !navigation.isSameDocument) owner.documents.end(DocumentEnd.COMMITTED)
60
52
  if (navigation.didCommit()) owner.url = navigation.url
61
53
  if (!navigation.isSameDocument) {
62
54
  owner.pendingUrl = null
63
- // A reported network or SSL error already made it "failed". Chromium's error page for an HTTP status (a 404 with
64
- // an empty body) is the server's answer: "finished", as on iOS.
65
- owner.outcome = owner.outcome ?: when {
66
- !navigation.didCommit() -> "cancelled" // a stop, a download, a 204, a blocked redirect, a newer load
67
- navigation.didCommitErrorPage() && navigation.statusCode < 400 -> "failed"
68
- else -> "finished"
69
- }
55
+ // Chromium's error page for an HTTP status (a 404 with an empty body) is the server's answer: "finished", as on
56
+ // iOS.
57
+ owner.settleOutcome(
58
+ when {
59
+ !navigation.didCommit() -> LoadOutcome.CANCELLED
60
+ navigation.didCommitErrorPage() && navigation.statusCode < 400 -> LoadOutcome.FAILED
61
+ else -> LoadOutcome.FINISHED
62
+ }
63
+ )
70
64
  // A page restored from the back-forward cache (its Page, already loaded) gets no onPageLoadEvent again.
71
65
  if (!navigation.didCommit() || navigation.page?.let { it in loadedPages } == true) owner.loadEnded()
72
66
  }
@@ -87,16 +81,12 @@ private val BOOLEAN = java.lang.Boolean.TYPE
87
81
  private val FLOAT = java.lang.Float.TYPE
88
82
 
89
83
  internal class Client(private val owner: MinimalWebView, private val navigation: MinimalWebViewNavigation) : WebViewClient() {
90
- /** The first hook client that overrides a decision callback, or null: the core decides. */
91
84
  private fun deciding(name: String, vararg types: Class<*>, lost: String? = null) =
92
85
  owner.deciders.first(name, owner.clients, lost) { it.overrides(name, *types) }
93
86
 
94
- /** Every hook client that overrides an observation callback, after the core. */
95
87
  private inline fun observing(name: String, vararg types: Class<*>, block: (WebViewClient) -> Unit) =
96
88
  owner.clients.forEach { if (it.overrides(name, *types)) block(it) }
97
89
 
98
- // Without NavigationListener: the last main-frame URL allowed to load (a page's navigation or a redirect), for
99
- // onReceivedSslError.
100
90
  private var allowedMainFrameUrl: String? = null
101
91
 
102
92
  // Not called for POST, the initial loadUrl, or reissued loads; called again for their redirects.
@@ -116,7 +106,7 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
116
106
  // blocked redirect) gets no load events and no outcome here.
117
107
  override fun onPageStarted(view: WebView, url: String?, favicon: Bitmap?) {
118
108
  if (!owner.hasNavigationListener) {
119
- owner.endDocument(DocumentEnd.COMMITTED)
109
+ owner.documents.end(DocumentEnd.COMMITTED)
120
110
  owner.loadStarted()
121
111
  }
122
112
  observing("onPageStarted", WEB_VIEW, STRING, Bitmap::class.java) { it.onPageStarted(view, url, favicon) }
@@ -124,7 +114,7 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
124
114
 
125
115
  override fun onPageFinished(view: WebView, url: String?) {
126
116
  if (!owner.hasNavigationListener) {
127
- owner.outcome = owner.outcome ?: "finished" // "failed" when a main-frame error came first
117
+ owner.settleOutcome(LoadOutcome.FINISHED)
128
118
  owner.loadEnded()
129
119
  }
130
120
  observing("onPageFinished", WEB_VIEW, STRING) { it.onPageFinished(view, url) }
@@ -139,7 +129,6 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
139
129
  override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? =
140
130
  deciding("shouldInterceptRequest", WEB_VIEW, WebResourceRequest::class.java)?.shouldInterceptRequest(view, request)
141
131
 
142
- // Main frame only: a subresource that fails to load (an ad) is the page's business.
143
132
  override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) {
144
133
  val description = error.description.toString()
145
134
  if (request.isForMainFrame && !description.contains("ERR_ABORTED")) {
@@ -158,7 +147,6 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
158
147
  if (hook != null) hook.onFormResubmission(view, dontResend, resend) else super.onFormResubmission(view, dontResend, resend)
159
148
  }
160
149
 
161
- // Without NavigationListener (WebView older than 146): best-effort URL tracking.
162
150
  override fun doUpdateVisitedHistory(view: WebView, url: String?, isReload: Boolean) {
163
151
  if (!owner.hasNavigationListener && url != null) {
164
152
  owner.url = url
@@ -167,7 +155,6 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
167
155
  observing("doUpdateVisitedHistory", WEB_VIEW, STRING, BOOLEAN) { it.doUpdateVisitedHistory(view, url, isReload) }
168
156
  }
169
157
 
170
- @SuppressLint("WebViewClientOnReceivedSslError") // because the core always cancels; it only reports the error
171
158
  override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, sslError: SslError) {
172
159
  val hook = deciding(
173
160
  "onReceivedSslError", WEB_VIEW, SslErrorHandler::class.java, SslError::class.java,
@@ -175,8 +162,8 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
175
162
  )
176
163
  if (hook != null) return hook.onReceivedSslError(view, handler, sslError)
177
164
  handler.cancel()
178
- // Also called for subresources (an ad image): only the main frame's URL is a page error. Without NavigationListener
179
- // there's no pendingUrl: view.url shows a loadUrl in progress (back/forward stays unreported).
165
+ // Also called for subresources (an ad image): only the main frame's URL is a page error.
166
+ // Without a NavigationListener there is no pendingUrl: WebView's url shows a loadUrl in progress.
180
167
  val mainFrame = if (owner.hasNavigationListener) setOf(owner.pendingUrl ?: owner.url) else setOf(view.url, allowedMainFrameUrl)
181
168
  if (sslError.url in mainFrame) {
182
169
  owner.reportError("ssl", sslError.url, sslError.primaryError, "SSL error ${sslError.primaryError}")
@@ -188,7 +175,6 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
188
175
  if (hook != null) hook.onReceivedClientCertRequest(view, request) else super.onReceivedClientCertRequest(view, request)
189
176
  }
190
177
 
191
- // Basic and digest auth: a hook client, else cancel (the page shows its 401).
192
178
  override fun onReceivedHttpAuthRequest(view: WebView, handler: HttpAuthHandler, host: String, realm: String) {
193
179
  val hook = deciding("onReceivedHttpAuthRequest", WEB_VIEW, HttpAuthHandler::class.java, STRING, STRING)
194
180
  if (hook != null) hook.onReceivedHttpAuthRequest(view, handler, host, realm) else handler.cancel()
@@ -210,7 +196,7 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
210
196
  observing("onReceivedLoginRequest", WEB_VIEW, STRING, STRING, STRING) { it.onReceivedLoginRequest(view, realm, account, args) }
211
197
 
212
198
  override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {
213
- // Returning true keeps the app alive; a stale WebView (already replaced) needs nothing more.
199
+ // Returning true keeps the app alive.
214
200
  // Timed here: every WebView on the renderer hears of its death back to back, before any recovery runs.
215
201
  val at = SystemClock.elapsedRealtime()
216
202
  if (view === owner.webView) mainHandler.post { owner.processGone(if (detail.didCrash()) "crash" else "memory", at) }
@@ -239,7 +225,7 @@ internal class ChromeClient(private val owner: MinimalWebView, private val navig
239
225
  ?: navigation.createWindow(isUserGesture, resultMsg)
240
226
 
241
227
  override fun onShowFileChooser(view: WebView, callback: ValueCallback<Array<Uri>>, params: FileChooserParams): Boolean {
242
- val once = owner.fileUpload.hold(callback) // before the hook branch: a hook's chooser is held too
228
+ val once = owner.fileUpload.hold(callback)
243
229
  val hook = deciding(
244
230
  "onShowFileChooser", WEB_VIEW, ValueCallback::class.java, FileChooserParams::class.java,
245
231
  lost = "onFileRequest doesn't apply"
@@ -249,7 +235,6 @@ internal class ChromeClient(private val owner: MinimalWebView, private val navig
249
235
  return true
250
236
  }
251
237
 
252
- // Without a hook client or the app's prop: deny (never grant device access by default).
253
238
  override fun onPermissionRequest(request: PermissionRequest) {
254
239
  val hook = deciding("onPermissionRequest", PermissionRequest::class.java, lost = "onPermissionRequest and the default deny don't apply")
255
240
  when {