react-native-minimal-webview 1.0.1 → 1.2.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 (78) hide show
  1. package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +19 -32
  2. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +55 -26
  3. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +3 -3
  4. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +2 -1
  5. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +8 -8
  6. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +5 -7
  7. package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +32 -44
  8. package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +2 -2
  9. package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +7 -8
  10. package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +2 -2
  11. package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +4 -5
  12. package/build/WebView.d.ts +1 -9
  13. package/build/WebView.d.ts.map +1 -1
  14. package/build/WebView.js +37 -107
  15. package/build/WebView.js.map +1 -1
  16. package/build/bridge/createBridge.d.ts +19 -13
  17. package/build/bridge/createBridge.d.ts.map +1 -1
  18. package/build/bridge/createBridge.js +33 -45
  19. package/build/bridge/createBridge.js.map +1 -1
  20. package/build/bridge/endpoint.d.ts +3 -8
  21. package/build/bridge/endpoint.d.ts.map +1 -1
  22. package/build/bridge/endpoint.js +2 -3
  23. package/build/bridge/endpoint.js.map +1 -1
  24. package/build/bridge/origins.d.ts +5 -2
  25. package/build/bridge/origins.d.ts.map +1 -1
  26. package/build/bridge/origins.js +15 -4
  27. package/build/bridge/origins.js.map +1 -1
  28. package/build/bridge/pageClient.generated.d.ts +1 -1
  29. package/build/bridge/pageClient.generated.d.ts.map +1 -1
  30. package/build/bridge/pageClient.generated.js +1 -1
  31. package/build/bridge/pageClient.generated.js.map +1 -1
  32. package/build/index.d.ts +1 -1
  33. package/build/index.d.ts.map +1 -1
  34. package/build/index.js +1 -1
  35. package/build/index.js.map +1 -1
  36. package/build/{defaultNavigationRules.d.ts → navigationRules.d.ts} +10 -1
  37. package/build/navigationRules.d.ts.map +1 -0
  38. package/build/navigationRules.js +93 -0
  39. package/build/navigationRules.js.map +1 -0
  40. package/build/refStore.d.ts.map +1 -1
  41. package/build/refStore.js +13 -19
  42. package/build/refStore.js.map +1 -1
  43. package/build/types.d.ts +55 -35
  44. package/build/types.d.ts.map +1 -1
  45. package/ios/DelegateProxy.swift +32 -30
  46. package/ios/DocumentEnd.swift +1 -2
  47. package/ios/Hooks.swift +28 -28
  48. package/ios/Loads.swift +5 -4
  49. package/ios/MRWInvoke.h +10 -9
  50. package/ios/MRWInvoke.m +39 -24
  51. package/ios/MinimalWebView+Navigation.swift +18 -16
  52. package/ios/MinimalWebView+Scripts.swift +0 -8
  53. package/ios/MinimalWebView.podspec +0 -1
  54. package/ios/MinimalWebView.swift +77 -35
  55. package/ios/MinimalWebViewModule.swift +1 -0
  56. package/ios/NavigationRules.swift +15 -15
  57. package/ios/OriginRules.swift +6 -0
  58. package/ios/PlatformSettings.swift +3 -22
  59. package/ios/Recovery.swift +6 -5
  60. package/ios/SharedCookies.swift +1 -2
  61. package/package.json +7 -3
  62. package/src/WebView.tsx +50 -123
  63. package/src/bridge/createBridge.ts +48 -56
  64. package/src/bridge/endpoint.ts +6 -9
  65. package/src/bridge/origins.ts +18 -6
  66. package/src/bridge/pageClient.generated.ts +1 -1
  67. package/src/bridge/pageClient.ts +3 -7
  68. package/src/bridge/protocol.ts +1 -1
  69. package/src/index.ts +1 -1
  70. package/src/navigationRules.ts +111 -0
  71. package/src/refStore.ts +15 -21
  72. package/src/types.ts +56 -35
  73. package/build/defaultNavigationRules.d.ts.map +0 -1
  74. package/build/defaultNavigationRules.js +0 -22
  75. package/build/defaultNavigationRules.js.map +0 -1
  76. package/ios/MRWExceptions.h +0 -9
  77. package/ios/MRWExceptions.m +0 -10
  78. package/src/defaultNavigationRules.ts +0 -24
@@ -1,7 +1,6 @@
1
1
  package expo.modules.minimalwebview
2
2
 
3
3
  import android.content.Context
4
- import android.os.Handler
5
4
  import android.os.Looper
6
5
  import android.util.Log
7
6
  import android.view.View
@@ -44,10 +43,8 @@ object MinimalWebViewHooks {
44
43
  *
45
44
  * Call it from your module's `OnCreate`, before the first WebView.
46
45
  *
47
- * The same `register` call running again replaces its hook: a JS reload creates the modules anew and runs their
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.
46
+ * A hook under a key that is taken already replaces that hook in its place, with a warning, so a key collision
47
+ * doesn't stop the app.
51
48
  *
52
49
  * The hook attaches to each WebView whose `extensions` prop has an extension with [key] that is on;
53
50
  * [HookExtension.options](https://rasmuskard.github.io/react-native-minimal-webview/typescript/react-native-minimal-webview/type-aliases/HookExtension/#options)
@@ -71,8 +68,6 @@ object MinimalWebViewHooks {
71
68
  * sets wins over those settings. Register what to run when that WebView goes away with
72
69
  * [WebViewContext.onDestroyed]. Document-start scripts you add here run before the package's, so
73
70
  * `window.nativeBridge` and `injectedScripts` aren't there yet (on iOS yours run after them).
74
- * @throws IllegalStateException when a different hook is registered under [key] already. Don't rely on it: a minified
75
- * build can't tell the two apart and may replace the first hook instead, so give each hook its own key.
76
71
  */
77
72
  fun register(
78
73
  key: String,
@@ -84,23 +79,23 @@ object MinimalWebViewHooks {
84
79
  Log.e(TAG, "the hook key `core` is reserved: the hook is not registered")
85
80
  return
86
81
  }
87
- val hook = Hook(key, webViewFactory, configure, attach)
88
- val index = hooks.indexOfFirst { it.key == key }
89
- if (index < 0) {
90
- hooks += hook
91
- return
92
- }
93
- // Each lambda in the source compiles to a class of its own: the same class is the same call running again.
94
- // shortcut: R8 can merge two lambdas' classes in a minified build; upgrade if a duplicate must throw there too.
95
- val first = hooks[index].attach.javaClass
96
- check(first == attach.javaClass) {
97
- "two hooks are registered under `$key` (${first.name} and ${attach.javaClass.name}): " +
98
- "prefix yours with your package's name"
82
+ if (putHook(hooks, Hook(key, webViewFactory, configure, attach))) {
83
+ Log.w(
84
+ TAG,
85
+ "a hook under `$key` replaces the one registered before: a JS reload registers every hook again; " +
86
+ "otherwise two hooks share the key and the last one wins, so prefix yours with your package's name"
87
+ )
99
88
  }
100
- hooks[index] = hook
101
89
  }
102
90
  }
103
91
 
92
+ /** Adds [hook] to [hooks], or replaces the one under its key in place; returns whether it replaced one. */
93
+ internal fun putHook(hooks: MutableList<MinimalWebViewHooks.Hook>, hook: MinimalWebViewHooks.Hook): Boolean {
94
+ val index = hooks.indexOfFirst { it.key == hook.key }
95
+ if (index < 0) hooks += hook else hooks[index] = hook
96
+ return index >= 0
97
+ }
98
+
104
99
  /** Splits [keys] into the [hooks] registered under them, in registration order, and the keys no hook is registered under. */
105
100
  internal fun selectHooks(
106
101
  hooks: List<MinimalWebViewHooks.Hook>,
@@ -110,11 +105,11 @@ internal fun selectHooks(
110
105
  return attaching to keys - attaching.map { it.key }.toSet()
111
106
  }
112
107
 
113
- /** Hooks whose keys turn on together attach in registration order, which orders their clients. */
108
+ /** [keys] in registration order, then those no hook is registered under, sorted. */
114
109
  internal fun inRegistrationOrder(keys: Set<String>, registered: List<String>) =
115
110
  registered.filter { it in keys } + (keys - registered.toSet()).sorted()
116
111
 
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. */
112
+ /** The hook whose factory makes the WebView (null: a plain one), and the keys of the others with a different factory. */
118
113
  internal fun pickFactory(attaching: List<MinimalWebViewHooks.Hook>): Pair<MinimalWebViewHooks.Hook?, List<String>> {
119
114
  val named = attaching.filter { it.webViewFactory != null }
120
115
  val maker = named.firstOrNull()
@@ -379,11 +374,7 @@ internal open class Attachment(value: Any?) {
379
374
  internal fun <T> routed(attachments: List<Attachment>, pick: (Attachment) -> List<T>) =
380
375
  attachments.filter { it.routed }.flatMap(pick)
381
376
 
382
- /**
383
- * A hook's view of the WebView, one per hook and WebView: the core's context with the hook's key on its events. The
384
- * handlers live here, so the WebView after a crash gets the ones its `attach` registers again. A hook can keep the
385
- * context past its attach (an async callback): [detach] then leaves it holding nothing of the view.
386
- */
377
+ /** The core's [WebViewContext] for one hook's attach: the hook's key goes on its events and asks. */
387
378
  internal class HookContext(val hook: MinimalWebViewHooks.Hook, view: MinimalWebView) :
388
379
  Attachment(view.hookOptions[hook.key]), WebViewContext {
389
380
  /** Null once the attach ended. Main thread only. */
@@ -430,11 +421,7 @@ internal class HookContext(val hook: MinimalWebViewHooks.Hook, view: MinimalWebV
430
421
 
431
422
  // A hook's shouldInterceptRequest runs on Chromium's IO thread; the view's events and asks are main-thread state.
432
423
  private fun onMain(block: () -> Unit) {
433
- if (Looper.myLooper() == Looper.getMainLooper()) block() else main.post { block() }
434
- }
435
-
436
- private companion object {
437
- val main = Handler(Looper.getMainLooper())
424
+ if (Looper.myLooper() == Looper.getMainLooper()) block() else mainHandler.post { block() }
438
425
  }
439
426
  }
440
427
 
@@ -1,7 +1,6 @@
1
1
  package expo.modules.minimalwebview
2
2
 
3
3
  import android.annotation.SuppressLint
4
- import android.app.Activity
5
4
  import android.content.Context
6
5
  import android.content.pm.ApplicationInfo
7
6
  import android.os.Bundle
@@ -28,7 +27,7 @@ import expo.modules.minimalwebview.requests.FileUpload
28
27
  import expo.modules.minimalwebview.requests.FullscreenVideo
29
28
  import expo.modules.minimalwebview.requests.Permissions
30
29
 
31
- @Suppress("TooManyFunctions") // because the view is the aggregate root: it holds what has one owner (the Expo surface, the platform WebView's life, crash recovery, the Document scope, the navigation state, the hook plumbing), and a feature with state of its own gets its own class
30
+ @Suppress("TooManyFunctions") // because the view is the aggregate root; a feature with state of its own gets its own class
32
31
  internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoView(context, appContext) {
33
32
  private val onNavigationState by EventDispatcher<Map<String, Any?>>()
34
33
  private val onBridge by EventDispatcher<Map<String, Any?>>()
@@ -39,7 +38,7 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
39
38
 
40
39
  internal val hasNavigationListener = WebViewFeature.isFeatureSupported(WebViewFeature.NAVIGATION_LISTENER)
41
40
  private val navigation = MinimalWebViewNavigation(this) { onNavigation(it) }
42
- private val scripts = MinimalWebViewScripts(this) { onBridge(it) }
41
+ internal val scripts = MinimalWebViewScripts(this) { onBridge(it) }
43
42
 
44
43
  /** Set by the first prop batch and replaced after a renderer crash; see [recovering]. */
45
44
  internal lateinit var webView: WebView
@@ -62,8 +61,12 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
62
61
  /** The `android` prop: WebSettings and WebView setters by name, applied by [PlatformSettings]. */
63
62
  internal var settings: Map<String, Any?>? = null
64
63
  internal val platformSettings = PlatformSettings { PlatformSettings.targets(webView, it) }
65
- internal var pullToRefresh = false
66
64
  private val refresher = PullToRefresh(this)
65
+ internal var pullToRefresh = false
66
+ set(value) {
67
+ field = value
68
+ refresher.layout.isEnabled = value
69
+ }
67
70
  /**
68
71
  * The page requests JS has a prop for, by prop name (`onFileRequest`, `onDownload`, ...), and `onNavigation`, read when a
69
72
  * request comes or a decision is reported.
@@ -74,7 +77,6 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
74
77
  // The hooks' lists: each context owns its own, and the core routes those of the hooks that are on, in attach order.
75
78
  val clients: List<WebViewClient> get() = routed(hookContexts) { it.clients }
76
79
  val chromeClients: List<WebChromeClient> get() = routed(hookContexts) { it.chromeClients }
77
- val activity: Activity? get() = appContext.currentActivity
78
80
  internal val fileUpload = FileUpload(this)
79
81
  internal val fullscreen = FullscreenVideo(this)
80
82
  internal val permissions = Permissions(this)
@@ -101,12 +103,10 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
101
103
  /** From a renderer death until [recover] builds the new WebView: whether it loads, and the dead one's history. */
102
104
  private var pendingRecovery: Recovery? = null
103
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. */
107
+ private var pendingLoad: String? = null
104
108
  private var destroyed = false
105
109
 
106
- // The core's deferred work. Not View.post: a detached view (unmounted, or a covered screen) holds that until it is
107
- // attached again.
108
- internal val mainHandler = Handler(Looper.getMainLooper())
109
-
110
110
  init {
111
111
  // The WebView goes into the layout in setUp(); the prop only turns the pull on and off.
112
112
  addView(refresher.layout, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
@@ -191,7 +191,6 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
191
191
  webView = createWebView()
192
192
  setUp()
193
193
  }
194
- refresher.layout.isEnabled = pullToRefresh
195
194
  loadNewSource()
196
195
  }
197
196
 
@@ -225,14 +224,20 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
225
224
  }
226
225
  }
227
226
 
227
+ /** The ref's `load`: like [retry], the app's own action starts the crash-loop guard over. */
228
+ internal fun load(url: String) {
229
+ crashTimes.clear()
230
+ if (recovering) pendingLoad = url else webView.loadUrl(url)
231
+ }
232
+
228
233
  /** Loads the page on screen again: the `source` when that is the page (its headers, html or POST), else its URL. */
229
234
  private fun loadAgain() {
230
235
  if (showsSource(source, url)) source?.let(::load) else if (url.isNotEmpty()) webView.loadUrl(url)
231
236
  }
232
237
 
233
238
  /**
234
- * The ref's reload: the app's retry starts the crash-loop guard over. Only this clears it: the guard counts the
235
- * process's renderer deaths, so another view's new source or pull-to-refresh mustn't end a crash loop's count.
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.
236
241
  */
237
242
  internal fun retry() {
238
243
  crashTimes.clear()
@@ -243,14 +248,15 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
243
248
  when {
244
249
  // The renderer died and the new WebView isn't built yet: build it now, and load.
245
250
  recovering -> recover(reload = true)
246
- // Nothing loaded: the crash-loop guard gave up (processGone), and this is the app's retry.
247
- webView.url == null -> loadAgain()
248
- // WebView's reload declines a POST's form resubmission: send the source again.
249
- source?.body != null && showsSource(source, url) -> source?.let(::load)
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.
253
+ webView.url == null || showingPost -> loadAgain()
250
254
  else -> webView.reload()
251
255
  }
252
256
  }
253
257
 
258
+ private val showingPost get() = source?.body != null && showsSource(source, url)
259
+
254
260
  /**
255
261
  * The `android` settings, applied from each prop batch (only the keys that changed) and all again to a new WebView
256
262
  * after a crash. A key that can't be applied is reported to JS, which warns.
@@ -327,8 +333,6 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
327
333
  stateChanged()
328
334
  }
329
335
 
330
- internal fun bridgePost(message: String) = scripts.post(message)
331
-
332
336
  internal fun evaluate(script: String, onResult: (Result<String>) -> Unit) =
333
337
  if (recovering) onResult(Result.failure(EvaluateError("unavailable", RECOVERING))) else scripts.evaluate(script, onResult)
334
338
 
@@ -338,7 +342,7 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
338
342
  */
339
343
  internal fun processGone(cause: String, at: Long) {
340
344
  if (destroyed) return
341
- val reload = crashAllowsReload(crashTimes, at) && !(source?.body != null && showsSource(source, url))
345
+ val reload = crashAllowsReload(crashTimes, at) && !showingPost
342
346
  // The source page reloads as the source: a restored entry carries neither source.headers nor an html source.
343
347
  val restorable = !showsSource(source, url)
344
348
  val history = Bundle().takeIf { reload && restorable && webView.saveState(it) != null }
@@ -374,9 +378,11 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
374
378
  pendingRecovery = null
375
379
  webView = createWebView()
376
380
  setUp()
377
- refresher.layout.isEnabled = pullToRefresh
378
- // A source the app set while this waited loads instead of the old page.
379
- if (!loadNewSource()) {
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) {
380
386
  val restored = recovery.history?.let { webView.restoreState(it) } != null
381
387
  if (!restored && (recovery.reload || reload)) loadAgain()
382
388
  }
@@ -457,9 +463,15 @@ internal class MinimalWebView(context: Context, appContext: AppContext) : ExpoVi
457
463
  }
458
464
 
459
465
  internal const val TAG = "MinimalWebView"
466
+
467
+ /**
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.
470
+ */
471
+ internal val mainHandler by lazy { Handler(Looper.getMainLooper()) }
460
472
  internal const val RECOVERING = "the WebView is being rebuilt after its renderer died"
461
473
 
462
- /** Whether this process has made a WebView; until then WebView isn't started. */
474
+ /** Whether this process has made a WebView. */
463
475
  @Volatile internal var webViewCreated = false
464
476
 
465
477
  /** What `setWebContentsDebuggingEnabled` set; null until it is called. */
@@ -479,16 +491,33 @@ internal fun profileOf(webView: WebView): Profile? =
479
491
  if (WebViewFeature.isFeatureSupported(WebViewFeature.MULTI_PROFILE)) WebViewCompat.getProfile(webView) else null
480
492
 
481
493
  /**
482
- * Whether the committed [url] is the [source]'s page (or nothing has committed yet). An html source's page is its
483
- * baseUrl or about:blank. Chromium canonicalizes (`https://example.com` commits as `https://example.com/`).
494
+ * Whether the committed [url] is the [source]'s page (or nothing has committed yet): the same [canonicalUrl] up to
495
+ * trailing slashes. An html source's page is its baseUrl or about:blank.
484
496
  */
485
497
  internal fun showsSource(source: WebViewSource?, url: String): Boolean {
486
498
  if (source == null) return false
487
499
  if (url.isEmpty()) return true
488
500
  val page = source.uri ?: source.baseUrl ?: "about:blank"
489
- return page.trimEnd('/') == url.trimEnd('/')
501
+ return canonicalUrl(page).trimEnd('/') == canonicalUrl(url).trimEnd('/')
502
+ }
503
+
504
+ /**
505
+ * [url] as Chromium commits it: the scheme and host lowercase, the scheme's default port dropped and an empty path
506
+ * `/`; the rest as it is. A URL with no `//` authority is returned unchanged.
507
+ */
508
+ private fun canonicalUrl(url: String): String {
509
+ val (scheme, userinfo, host, port, rest) = urlAuthority.find(url)?.destructured ?: return url
510
+ val lower = scheme.lowercase()
511
+ val portPart = port.toIntOrNull()?.takeIf { it != defaultPorts[lower] }?.let { ":$it" }.orEmpty()
512
+ return "$lower://$userinfo${host.lowercase()}$portPart${if (rest.startsWith('/')) rest else "/$rest"}"
490
513
  }
491
514
 
515
+ // scheme "://" [userinfo "@"] host [":" port] rest
516
+ private val urlAuthority = Regex("^([a-zA-Z][a-zA-Z0-9+.-]*)://([^/?#@]*@)?(\\[[^\\]/?#]*]|[^/?#:]*)(?::(\\d*))?(.*)$")
517
+
518
+ /** The special schemes' default ports (the WHATWG URL Standard's), as on iOS (Loads.swift). */
519
+ internal val defaultPorts = mapOf("http" to 80, "https" to 443, "ws" to 80, "wss" to 443, "ftp" to 21)
520
+
492
521
  /**
493
522
  * Records a renderer death at [now] in [times] and says whether to reload after it: not after more than
494
523
  * [MAX_CRASHES_PER_WINDOW] in [CRASH_WINDOW_MS]. Every WebView on the renderer hears of its death, so one within
@@ -75,7 +75,8 @@ internal class Listener(private val owner: MinimalWebView) : NavigationListener
75
75
 
76
76
  override fun onPageLoadEvent(page: Page) {
77
77
  loadedPages += page
78
- owner.loadEnded()
78
+ // The page being left still fires its load event while the next one is pending: that load isn't over.
79
+ if (owner.pendingUrl == null) owner.loadEnded()
79
80
  }
80
81
  }
81
82
 
@@ -135,7 +136,6 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
135
136
  override fun onPageCommitVisible(view: WebView, url: String?) =
136
137
  observing("onPageCommitVisible", WEB_VIEW, STRING) { it.onPageCommitVisible(view, url) }
137
138
 
138
- // On a background thread, as WebView calls it: a hook client that overrides it runs there too.
139
139
  override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? =
140
140
  deciding("shouldInterceptRequest", WEB_VIEW, WebResourceRequest::class.java)?.shouldInterceptRequest(view, request)
141
141
 
@@ -213,7 +213,7 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
213
213
  // Returning true keeps the app alive; a stale WebView (already replaced) needs nothing more.
214
214
  // Timed here: every WebView on the renderer hears of its death back to back, before any recovery runs.
215
215
  val at = SystemClock.elapsedRealtime()
216
- if (view === owner.webView) owner.mainHandler.post { owner.processGone(if (detail.didCrash()) "crash" else "memory", at) }
216
+ if (view === owner.webView) mainHandler.post { owner.processGone(if (detail.didCrash()) "crash" else "memory", at) }
217
217
  observing("onRenderProcessGone", WEB_VIEW, RenderProcessGoneDetail::class.java) { it.onRenderProcessGone(view, detail) }
218
218
  return true
219
219
  }
@@ -106,6 +106,7 @@ class MinimalWebViewModule : Module() {
106
106
 
107
107
  AsyncFunction("goBack") { view: MinimalWebView -> live(view) { it.goBack() } }.runOnQueue(Queues.MAIN)
108
108
  AsyncFunction("goForward") { view: MinimalWebView -> live(view) { it.goForward() } }.runOnQueue(Queues.MAIN)
109
+ AsyncFunction("load") { view: MinimalWebView, url: String -> view.load(url) }.runOnQueue(Queues.MAIN)
109
110
  AsyncFunction("reload") { view: MinimalWebView -> view.retry() }.runOnQueue(Queues.MAIN)
110
111
  AsyncFunction("stopLoading") { view: MinimalWebView -> live(view) { it.stopLoading() } }.runOnQueue(Queues.MAIN)
111
112
  AsyncFunction("get") { view: MinimalWebView, path: String, promise: Promise ->
@@ -118,7 +119,7 @@ class MinimalWebViewModule : Module() {
118
119
  // A call can change what the state shows (clearHistory, canGoBack); an unchanged state isn't sent.
119
120
  view.stateChanged()
120
121
  }.runOnQueue(Queues.MAIN)
121
- AsyncFunction("bridgePost") { view: MinimalWebView, message: String -> view.bridgePost(message) }.runOnQueue(Queues.MAIN)
122
+ AsyncFunction("bridgePost") { view: MinimalWebView, message: String -> view.scripts.post(message) }.runOnQueue(Queues.MAIN)
122
123
  AsyncFunction("answer") { view: MinimalWebView, askId: Int, json: String ->
123
124
  view.asks.answer(askId, fromJson(JSONTokener(json).nextValue()))
124
125
  }.runOnQueue(Queues.MAIN)
@@ -38,7 +38,7 @@ internal class MinimalWebViewNavigation(
38
38
  val asked = if (request.isRedirect) askedAndAllowed else emptySet()
39
39
  val decision = NavigationRules.decide(owner.navigationRules, request, asked, "onNavigationRequest" in owner.requestHandlers)
40
40
  val action = if (decision.action == "ask" && !request.mainFrame) {
41
- // Android can't hold a navigation, so `ask` cancels and reissues it: a subframe's can't be reissued.
41
+ // loadUrl reissues only a main-frame navigation.
42
42
  Log.w(TAG, "`ask` only works for main-frame navigations on Android; blocked ${request.url}")
43
43
  "block"
44
44
  } else {
@@ -67,7 +67,7 @@ internal class MinimalWebViewNavigation(
67
67
  if ("onNavigation" in owner.requestHandlers) onNavigation(fields(request) + mapOf("action" to action, "rule" to rule))
68
68
  }
69
69
 
70
- // Cancel now, ask JS, reissue on allow. Never blocks the UI thread. Loses the gesture flag and the redirect chain.
70
+ // Cancel now, ask JS, reissue on allow; the redirect chain is lost.
71
71
  private fun ask(request: NavigationRules.Request, rule: Int?) {
72
72
  val referrer = webView.url
73
73
  val id = owner.asks.ask("core", "onNavigationRequest", fields(request)) { answer ->
@@ -79,12 +79,12 @@ internal class MinimalWebViewNavigation(
79
79
  if (action == "external") openExternal(request, rule) else notifyNavigation(request, action, rule)
80
80
  }
81
81
  // Unanswered after the timeout: block (the answer callback runs with null). A late answer finds nothing.
82
- owner.mainHandler.postDelayed({ owner.asks.cancel(id) }, ASK_TIMEOUT_MS)
82
+ mainHandler.postDelayed({ owner.asks.cancel(id) }, ASK_TIMEOUT_MS)
83
83
  }
84
84
 
85
- // WebView's request headers on a navigation are empty, so the page's URL goes as the referrer. WebView applies its
86
- // default policy to it (origin only cross-origin, none from https to http); the page's own referrer policy is lost.
87
- // loadUrl skips shouldOverrideUrlLoading, so the reissued URL isn't asked again (its redirects still go to decide).
85
+ // WebView's request headers on a navigation are empty, so the page's URL goes as the Referer, trimmed by WebView's
86
+ // default policy (origin only cross-origin, none from https to http). loadUrl skips shouldOverrideUrlLoading, so the
87
+ // reissued URL isn't asked again (its redirects still go to decide).
88
88
  private fun reissue(url: String, referrer: String?) = webView.loadUrl(url, referrer?.let { mapOf("Referer" to it) }.orEmpty())
89
89
 
90
90
  /** A download no `onDownload` takes. */
@@ -171,7 +171,7 @@ internal class MinimalWebViewNavigation(
171
171
  // Destroyed later: this may run inside the child's own callback.
172
172
  fun finish(): Boolean {
173
173
  val wasPending = children.remove(child)
174
- if (wasPending) owner.mainHandler.post { child.destroy() }
174
+ if (wasPending) mainHandler.post { child.destroy() }
175
175
  return wasPending
176
176
  }
177
177
  child.webViewClient = object : WebViewClient() {
@@ -188,7 +188,7 @@ internal class MinimalWebViewNavigation(
188
188
  }
189
189
  }
190
190
  // window.open('') or about:blank never navigates: give up on it.
191
- owner.mainHandler.postDelayed({ finish() }, NEW_WINDOW_TIMEOUT_MS)
191
+ mainHandler.postDelayed({ finish() }, NEW_WINDOW_TIMEOUT_MS)
192
192
  (resultMsg.obj as WebView.WebViewTransport).webView = child
193
193
  resultMsg.sendToTarget()
194
194
  return true
@@ -27,12 +27,9 @@ internal class MinimalWebViewScripts(private val owner: MinimalWebView, private
27
27
  scriptHandlers.clear()
28
28
  installEvaluate()
29
29
  installBridge()
30
- installScripts(force = true)
30
+ update(force = true)
31
31
  }
32
32
 
33
- /** A later prop batch: only `injectedScripts` can change. */
34
- fun update() = installScripts()
35
-
36
33
  private fun installBridge() {
37
34
  val script = owner.bridgeScript ?: return
38
35
  val bridgeFeatures = listOf(WebViewFeature.WEB_MESSAGE_LISTENER, WebViewFeature.DOCUMENT_START_SCRIPT)
@@ -60,8 +57,8 @@ internal class MinimalWebViewScripts(private val owner: MinimalWebView, private
60
57
  }
61
58
  }
62
59
 
63
- /** Changed scripts take effect from the next navigation. */
64
- private fun installScripts(force: Boolean = false) {
60
+ /** Installs `injectedScripts` if they changed, or with [force] always. They take effect from the next navigation. */
61
+ fun update(force: Boolean = false) {
65
62
  val scripts = owner.injectedScripts.orEmpty()
66
63
  if (!force && scripts == installedScripts) return
67
64
  installedScripts = scripts
@@ -90,7 +87,8 @@ internal class MinimalWebViewScripts(private val owner: MinimalWebView, private
90
87
  // At a commit this runs one main-thread hop after Chromium's (the NavigationListener's executor posts it), and
91
88
  // relies on landing before the new page's first message sets replyProxy (the bridge suite's head-script call).
92
89
  replyProxy = null
93
- if (reason != DocumentEnd.CLOSING && owner.bridgeScript != null) onBridge(mapOf("navigated" to true))
90
+ if (reason == DocumentEnd.COMMITTED && owner.bridgeScript != null) onBridge(mapOf("navigated" to true))
91
+ if (reason == DocumentEnd.CRASHED && owner.bridgeScript != null) onBridge(mapOf("crashed" to true))
94
92
  }
95
93
 
96
94
  /**
@@ -15,16 +15,9 @@ import java.lang.reflect.Modifier
15
15
  import kotlin.math.truncate
16
16
 
17
17
  /**
18
- * The `android` settings prop, `{ settings: {…}, webView: {…} }`, applied by name through reflection, so a public
19
- * setter this package doesn't know (one a newer SDK or androidx.webkit adds) needs no code here.
20
- * `settings.textZoom: 120` calls `WebSettings.setTextZoom(120)`, else `WebSettingsCompat.setTextZoom(settings, 120)`.
21
- * `webView.acceptThirdPartyCookies: true` calls `WebView.set…`, else `WebViewCompat.set…(webView, …)`, else
22
- * `CookieManager.set…(webView, …)`. [get] reads through the matching getter and [call] invokes a method; for those two,
23
- * `cookieManager` and `webStorage`, the WebView profile's, are roots as well.
24
- *
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].
18
+ * The `android` settings prop, `get` and `call`, by name through reflection over public SDK methods only
19
+ * (`getMethods()`), so a setter a newer SDK or androidx.webkit adds needs no code here. The roots and their order:
20
+ * [Companion.targets].
28
21
  */
29
22
  internal class PlatformSettings(private val targets: (root: String) -> List<Target>?) {
30
23
  /** `root.key` -> the last value applied or rejected, so an unchanged value is neither applied nor reported again. */
@@ -116,12 +109,17 @@ internal class PlatformSettings(private val targets: (root: String) -> List<Targ
116
109
  fun call(path: String, args: List<Any?>, reply: (() -> String) -> Unit) {
117
110
  val (targets, name) = resolve(path)
118
111
  if (name in OWNED) throw problem("$name is ${owned(name)}")
119
- val result = invokeFirst(targets, name, args) { true }
120
- if (result !== NONE) return reply { toJson(result) }
112
+ val direct = find(targets, args) { it.name == name }
113
+ if (direct != null) {
114
+ val result = direct()
115
+ return reply { toJson(result) }
116
+ }
121
117
  // The callback runs later, outside the caller's try: the receiver converts, so it can reject instead of crashing.
122
118
  val callback = ValueCallback<Any?> { value -> reply { toJson(value) } }
123
- val awaiting = invokeFirst(targets, name, args + callback) { it.parameterTypes.lastOrNull() == ValueCallback::class.java }
124
- if (awaiting === NONE) throw notFound("no public method $path takes these arguments")
119
+ val awaiting = find(targets, args + callback) {
120
+ it.name == name && it.parameterTypes.lastOrNull() == ValueCallback::class.java
121
+ } ?: throw notFound("no public method $path takes these arguments")
122
+ awaiting()
125
123
  }
126
124
 
127
125
  /** The targets of `root.key` and the key; throws for a malformed path or an unknown root. */
@@ -163,16 +161,16 @@ internal class PlatformSettings(private val targets: (root: String) -> List<Targ
163
161
  "setWebContentsDebuggingEnabled", "setOnTouchListener", "setOnScrollChangeListener", "addNavigationListener"
164
162
  )
165
163
 
166
- /** The result of the first method [name] of [targets] that [accepts] and takes [values], or [NONE] when none does. */
167
- private fun invokeFirst(targets: List<Target>, name: String, values: List<Any?>, accepts: (Method) -> Boolean): Any? {
164
+ /** The first method of [targets], target by target, that [accepts] and takes [values], bound to them; or null. */
165
+ private fun find(targets: List<Target>, values: List<Any?>, accepts: (Method) -> Boolean): (() -> Any?)? {
168
166
  for (target in targets) {
169
167
  for (method in target.cls.methods) {
170
- if (method.name != name || !accepts(method)) continue
171
- val arguments = arguments(method, target, values) ?: continue
172
- return invoke(method, target, arguments)
168
+ if (!accepts(method)) continue
169
+ val args = arguments(method, target, values) ?: continue
170
+ return { invoke(method, target, args) }
173
171
  }
174
172
  }
175
- return NONE
173
+ return null
176
174
  }
177
175
 
178
176
  private fun owned(name: String) =
@@ -190,36 +188,26 @@ internal class PlatformSettings(private val targets: (root: String) -> List<Targ
190
188
  if (key.isEmpty() || key.startsWith("_")) return "not a public setter"
191
189
  val setter = "set" + key.replaceFirstChar { it.uppercaseChar() }
192
190
  if (setter in OWNED) return owned(setter)
193
- var seen = false
194
- for (target in targets) {
195
- for (method in target.cls.methods) {
196
- if (method.name != setter) continue
197
- seen = true
198
- val args = arguments(method, target, listOf(value)) ?: continue
199
- return try {
200
- before()
201
- invoke(method, target, args)
202
- null
203
- } catch (e: IllegalArgumentException) { // a PlatformException from invoke is one, so its reason is the message
204
- e.message
205
- }
206
- }
191
+ val apply = find(targets, listOf(value)) { it.name == setter } ?: return when {
192
+ targets.none { t -> t.cls.methods.any { it.name == setter } } -> "no public setter"
193
+ else -> "no public setter takes a ${value?.javaClass?.simpleName ?: "null"}"
194
+ }
195
+ return try {
196
+ before()
197
+ apply()
198
+ null
199
+ } catch (e: IllegalArgumentException) { // a PlatformException from invoke is one, so its reason is the message
200
+ e.message
207
201
  }
208
- return if (seen) "no public setter takes a ${value?.javaClass?.simpleName ?: "null"}" else "no public setter"
209
202
  }
210
203
 
211
204
  /** The value of [key]'s getter on the first target that has one, or [NONE]. */
212
205
  private fun read(targets: List<Target>, key: String): Any? {
213
206
  val capital = key.replaceFirstChar { it.uppercaseChar() }
214
- for (target in targets) {
215
- for (method in target.cls.methods) {
216
- val getter = method.name == "get$capital" || method.name == "is$capital"
217
- if (!getter && (method.name != key || method.returnType == Void.TYPE)) continue
218
- val args = arguments(method, target, emptyList()) ?: continue
219
- return invoke(method, target, args)
220
- }
221
- }
222
- return NONE
207
+ val getter = find(targets, emptyList()) {
208
+ it.name == "get$capital" || it.name == "is$capital" || (it.name == key && it.returnType != Void.TYPE)
209
+ } ?: return NONE
210
+ return getter()
223
211
  }
224
212
 
225
213
  /** The method's arguments for [values], with the target's leading object first, or null when they don't fit. */
@@ -20,7 +20,7 @@ internal class PullToRefresh(private val owner: MinimalWebView) {
20
20
  /** Holds the WebView. SwipeRefreshLayout keeps its first child as its target for good, so a crash swaps the WebView here. */
21
21
  val content = FrameLayout(owner.context)
22
22
 
23
- /** Always around [content]; off until the first prop batch, then the prop sets `isEnabled`. */
23
+ /** Always around [content]; off until the prop sets `isEnabled`. */
24
24
  val layout: SwipeRefreshLayout = Layout(owner.context).apply {
25
25
  isEnabled = false
26
26
  addView(content, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
@@ -35,7 +35,7 @@ internal class PullToRefresh(private val owner: MinimalWebView) {
35
35
  if (touch == touches) innerScrolled = result == "true"
36
36
  }
37
37
  // A busy page answers late: don't hold the pull off for longer than this.
38
- owner.mainHandler.postDelayed({ if (touch == touches && innerScrolled == null) innerScrolled = false }, ANSWER_TIMEOUT_MS)
38
+ mainHandler.postDelayed({ if (touch == touches && innerScrolled == null) innerScrolled = false }, ANSWER_TIMEOUT_MS)
39
39
  }
40
40
 
41
41
  /** A load ended: the spinner stops, or it would ignore the next pull. */
@@ -6,6 +6,7 @@ import android.webkit.CookieManager
6
6
  import androidx.webkit.URLUtilCompat
7
7
  import expo.modules.minimalwebview.MinimalWebView
8
8
  import expo.modules.minimalwebview.TAG
9
+ import expo.modules.minimalwebview.mainHandler
9
10
  import expo.modules.minimalwebview.profileOf
10
11
  import org.json.JSONArray
11
12
  import org.json.JSONObject
@@ -50,17 +51,15 @@ internal class Downloads(private val owner: MinimalWebView) {
50
51
  when {
51
52
  download.url.startsWith("blob:") -> readBlob(download.url, name)
52
53
  download.url.startsWith("data:") -> save(name, download.url) { file -> append(file, decodeDataUrl(download.url)) }
53
- download.url.startsWith("http:") || download.url.startsWith("https:") -> fetch(download, name)
54
+ download.url.startsWith("http:") || download.url.startsWith("https:") -> {
55
+ val cookies = profileOf(owner.webView)?.cookieManager ?: CookieManager.getInstance()
56
+ save(name, download.url) { file -> fetchTo(download, file, cookies::getCookie, cookies::setCookie) }
57
+ }
54
58
  else -> failed(name, download.url, IOException("unsupported URL scheme"))
55
59
  }
56
60
  return true
57
61
  }
58
62
 
59
- private fun fetch(download: DownloadInfo, name: String) {
60
- val cookies = profileOf(owner.webView)?.cookieManager ?: CookieManager.getInstance()
61
- save(name, download.url) { file -> fetchTo(download, file, cookies::getCookie, cookies::setCookie) }
62
- }
63
-
64
63
  /** Appends a decoded data: URL's bytes to [file], creating it, and returns its MIME type. */
65
64
  private fun append(file: File, data: Pair<ByteArray, String>): String {
66
65
  file.appendBytes(data.first)
@@ -83,7 +82,7 @@ internal class Downloads(private val owner: MinimalWebView) {
83
82
  e
84
83
  }
85
84
  if (result is Exception) file.parentFile?.deleteRecursively() // no partial file stays in the cache
86
- owner.mainHandler.post {
85
+ mainHandler.post {
87
86
  when (result) {
88
87
  is String -> owner.emit(
89
88
  "core", "onDownload",
@@ -122,7 +121,7 @@ internal class Downloads(private val owner: MinimalWebView) {
122
121
  }))
123
122
  """.trimIndent()
124
123
  val reply = ArrayBlockingQueue<Result<String>>(1)
125
- owner.mainHandler.post { owner.evaluate(script) { reply.offer(it) } }
124
+ mainHandler.post { owner.evaluate(script) { reply.offer(it) } }
126
125
  val result = reply.poll(TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS) ?: throw IOException("the page did not read the blob in time")
127
126
  val json = result.getOrElse { throw IOException("could not read the blob: ${it.message}") }
128
127
  // A reply far longer than a chunk's data: URL is forged: refuse it before it is copied twice more.
@@ -33,7 +33,7 @@ internal class FullscreenVideo(private val owner: MinimalWebView) {
33
33
  window.addView(this, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
34
34
  }
35
35
  shownCallback = callback
36
- backCallback = (owner.activity as? ComponentActivity)?.let { component ->
36
+ backCallback = (owner.appContext.currentActivity as? ComponentActivity)?.let { component ->
37
37
  object : OnBackPressedCallback(true) {
38
38
  override fun handleOnBackPressed() = exit()
39
39
  }.also { component.onBackPressedDispatcher.addCallback(it) }
@@ -78,7 +78,7 @@ internal class FullscreenVideo(private val owner: MinimalWebView) {
78
78
  if ("onFullscreenChange" in owner.requestHandlers) owner.emit("core", "onFullscreenChange", mapOf("active" to active))
79
79
  }
80
80
 
81
- private fun controller() = owner.activity?.window?.let { WindowCompat.getInsetsController(it, it.decorView) }
81
+ private fun controller() = owner.appContext.currentActivity?.window?.let { WindowCompat.getInsetsController(it, it.decorView) }
82
82
 
83
83
  /** The Document ended: removes its fullscreen view. Only CLOSING (unmount) also tells WebView via `onCustomViewHidden`; after a crash no renderer is left to tell. */
84
84
  fun documentEnded(reason: DocumentEnd) {