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
@@ -14,20 +14,19 @@ import java.lang.reflect.Method
14
14
  import java.lang.reflect.Modifier
15
15
  import kotlin.math.truncate
16
16
 
17
- /**
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].
21
- */
22
- internal class PlatformSettings(private val targets: (root: String) -> List<Target>?) {
23
- /** `root.key` -> the last value applied or rejected, so an unchanged value is neither applied nor reported again. */
24
- private val applied = mutableMapOf<String, Any?>()
17
+ internal class PlatformSettings(
18
+ private val hasNavigationListener: () -> Boolean = { true },
19
+ private val targets: (root: String) -> List<Target>?
20
+ ) {
21
+ private val applied = mutableMapOf<SettingId, Any?>()
25
22
 
26
- /** `root.key` -> its getter's value before the first write ([NONE]: no getter), set back when the key is removed. */
27
- private val originals = mutableMapOf<String, Any?>()
23
+ private val originals = mutableMapOf<SettingId, Any?>()
28
24
 
29
- /** A receiver (null for statics) and, for compat and CookieManager methods, the root object passed first. */
30
- internal class Target(val cls: Class<*>, val receiver: Any?, val leading: Any?)
25
+ private data class SettingId(val root: String, val key: String) {
26
+ override fun toString() = "$root.$key"
27
+ }
28
+
29
+ internal class Target(val cls: Class<*>, val receiver: Any?, val firstArgument: Any?)
31
30
 
32
31
  /**
33
32
  * Applies [settings], and sets a key applied before and missing now back to its value before the first write;
@@ -38,7 +37,6 @@ internal class PlatformSettings(private val targets: (root: String) -> List<Targ
38
37
  applied.clear()
39
38
  originals.clear()
40
39
  }
41
- // Before the new values, so restoring one can't undo another that depends on it.
42
40
  val rejected = restore(removedFrom = settings.orEmpty()).toMutableList()
43
41
  for ((rootName, entries) in settings.orEmpty()) {
44
42
  val targets = settingsTargets(rootName)
@@ -48,47 +46,45 @@ internal class PlatformSettings(private val targets: (root: String) -> List<Targ
48
46
  }
49
47
  for ((k, value) in entries) {
50
48
  val key = k as? String ?: continue
51
- val id = "$rootName.$key"
49
+ val id = SettingId(rootName, key)
52
50
  if (applied.containsKey(id) && applied[id] == value) continue
53
51
  applied[id] = value
54
- val problem = write(targets, id, key, value) ?: continue
55
- rejected += mapOf("key" to id, "reason" to problem)
52
+ val problem = write(targets, id, value) ?: continue
53
+ rejected += mapOf("key" to id.toString(), "reason" to problem)
56
54
  }
57
55
  }
58
56
  return rejected
59
57
  }
60
58
 
61
- /** The targets of a root the prop has, `settings` or `webView`; null for another. */
62
59
  private fun settingsTargets(rootName: String) =
63
60
  // Not targets() first: the other roots are the WebView profile's, which `webView.profile` may not have set yet.
64
61
  if (rootName in listOf("settings", "webView")) targets(rootName) else null
65
62
 
66
63
  /** [set], keeping the value it replaces the first time under [id]; returns the problem, or null when it was set. */
67
- private fun write(targets: List<Target>, id: String, key: String, value: Any?): String? {
68
- if (id in originals) return set(targets, key, value)
69
- return set(targets, key, value) {
70
- originals[id] = runCatching { read(targets, key) }.getOrDefault(NONE)
64
+ private fun write(targets: List<Target>, id: SettingId, value: Any?): String? {
65
+ refusal(setterOf(id.key), listOf(value))?.let { return it }
66
+ if (id in originals) return set(targets, id.key, value)
67
+ return set(targets, id.key, value) {
68
+ originals[id] = runCatching { read(targets, id.key) }.getOrDefault(NONE)
71
69
  }?.also { originals.remove(id) }
72
70
  }
73
71
 
74
72
  /** Forgets each applied key [removedFrom] no longer has and sets its original value back; returns what failed. */
75
73
  private fun restore(removedFrom: Map<String, Any?>): List<Map<String, String>> {
76
74
  val present = removedFrom.flatMap { (rootName, entries) ->
77
- (entries as? Map<*, *>)?.keys.orEmpty().map { "$rootName.$it" }
75
+ (entries as? Map<*, *>)?.keys.orEmpty().map { SettingId(rootName, it.toString()) }
78
76
  }.toSet()
79
77
  return (applied.keys - present).mapNotNull { id ->
80
78
  applied.remove(id)
81
79
  if (id !in originals) return@mapNotNull null
82
80
  val original = originals.remove(id)
83
- val (rootName, key) = id.split('.', limit = 2)
84
- // shortcut: a setter with no getter (geolocationEnabled, initialScale, backgroundColor) can't be restored; add
85
- // the platform's defaults for those if one matters.
81
+ val (rootName, key) = id
86
82
  val problem = if (original === NONE) {
87
83
  "removed, but it has no getter to restore it from: it keeps its value until the WebView is recreated"
88
84
  } else {
89
85
  set(targets(rootName).orEmpty(), key, original)?.let { "removed, but restoring it failed: $it" }
90
86
  }
91
- problem?.let { mapOf("key" to id, "reason" to it) }
87
+ problem?.let { mapOf("key" to id.toString(), "reason" to it) }
92
88
  }
93
89
  }
94
90
 
@@ -109,12 +105,12 @@ internal class PlatformSettings(private val targets: (root: String) -> List<Targ
109
105
  fun call(path: String, args: List<Any?>, reply: (() -> String) -> Unit) {
110
106
  val (targets, name) = resolve(path)
111
107
  if (name in OWNED) throw problem("$name is ${owned(name)}")
108
+ refusal(name, args)?.let { throw PlatformException("unavailable", it) }
112
109
  val direct = find(targets, args) { it.name == name }
113
110
  if (direct != null) {
114
111
  val result = direct()
115
112
  return reply { toJson(result) }
116
113
  }
117
- // The callback runs later, outside the caller's try: the receiver converts, so it can reject instead of crashing.
118
114
  val callback = ValueCallback<Any?> { value -> reply { toJson(value) } }
119
115
  val awaiting = find(targets, args + callback) {
120
116
  it.name == name && it.parameterTypes.lastOrNull() == ValueCallback::class.java
@@ -129,9 +125,19 @@ internal class PlatformSettings(private val targets: (root: String) -> List<Targ
129
125
  return (targets(parts[0]) ?: throw notFound("unknown root: use settings, webView, cookieManager or webStorage")) to parts[1]
130
126
  }
131
127
 
128
+ /** Why [method] can't take [args] on this WebView, or null. */
129
+ private fun refusal(method: String, args: List<Any?>) =
130
+ if (method == "setBackForwardCacheEnabled" && args == listOf(true) && !hasNavigationListener()) {
131
+ "not supported by this WebView: below Android System WebView 146 a page restored from the cache reports no load end"
132
+ } else {
133
+ null
134
+ }
135
+
132
136
  internal companion object {
133
137
  private val NONE = Any()
134
138
 
139
+ private fun setterOf(key: String) = "set" + key.replaceFirstChar { it.uppercaseChar() }
140
+
135
141
  /** The targets of [root] on [webView], or null for an unknown root. */
136
142
  fun targets(webView: WebView, root: String): List<Target>? = when (root) {
137
143
  "settings" -> listOf(
@@ -149,10 +155,6 @@ internal class PlatformSettings(private val targets: (root: String) -> List<Targ
149
155
  else -> null
150
156
  }
151
157
 
152
- /**
153
- * Methods the core owns: its clients, listeners, scripts, loads and navigations, the WebView's lifetime and timers,
154
- * and the process-wide debugging switch; the page's JS goes through `evaluate` and the bridge.
155
- */
156
158
  val OWNED = setOf(
157
159
  "setWebViewClient", "setWebChromeClient", "setDownloadListener", "addJavascriptInterface",
158
160
  "removeJavascriptInterface", "addWebMessageListener", "removeWebMessageListener", "addDocumentStartJavaScript",
@@ -186,7 +188,7 @@ internal class PlatformSettings(private val targets: (root: String) -> List<Targ
186
188
  */
187
189
  private fun set(targets: List<Target>, key: String, value: Any?, before: () -> Unit = {}): String? {
188
190
  if (key.isEmpty() || key.startsWith("_")) return "not a public setter"
189
- val setter = "set" + key.replaceFirstChar { it.uppercaseChar() }
191
+ val setter = setterOf(key)
190
192
  if (setter in OWNED) return owned(setter)
191
193
  val apply = find(targets, listOf(value)) { it.name == setter } ?: return when {
192
194
  targets.none { t -> t.cls.methods.any { it.name == setter } } -> "no public setter"
@@ -196,7 +198,9 @@ internal class PlatformSettings(private val targets: (root: String) -> List<Targ
196
198
  before()
197
199
  apply()
198
200
  null
199
- } catch (e: IllegalArgumentException) { // a PlatformException from invoke is one, so its reason is the message
201
+ } catch (e: PlatformException) {
202
+ e.message
203
+ } catch (e: IllegalArgumentException) {
200
204
  e.message
201
205
  }
202
206
  }
@@ -210,13 +214,13 @@ internal class PlatformSettings(private val targets: (root: String) -> List<Targ
210
214
  return getter()
211
215
  }
212
216
 
213
- /** The method's arguments for [values], with the target's leading object first, or null when they don't fit. */
217
+ /** The method's arguments for [values], after the target's [Target.firstArgument], or null when they don't fit. */
214
218
  private fun arguments(method: Method, target: Target, values: List<Any?>): Array<Any?>? {
215
219
  if (target.receiver == null && !Modifier.isStatic(method.modifiers)) return null
216
220
  val types = method.parameterTypes
217
- val leading = if (target.leading != null) listOf(target.leading) else emptyList()
221
+ val leading = if (target.firstArgument != null) listOf(target.firstArgument) else emptyList()
218
222
  if (types.size != leading.size + values.size) return null
219
- if (leading.isNotEmpty() && !types[0].isInstance(target.leading)) return null
223
+ if (leading.isNotEmpty() && !types[0].isInstance(target.firstArgument)) return null
220
224
  val args = arrayOfNulls<Any?>(types.size)
221
225
  leading.forEachIndexed { i, value -> args[i] = value }
222
226
  values.forEachIndexed { i, value ->
@@ -288,4 +292,4 @@ internal class PlatformSettings(private val targets: (root: String) -> List<Targ
288
292
  }
289
293
 
290
294
  /** Why [PlatformSettings.get] or [PlatformSettings.call] failed; [code] is the JS error code (`not_found`, `native_error` or `unavailable`). */
291
- internal class PlatformException(val code: String, message: String) : IllegalArgumentException(message)
295
+ internal class PlatformException(val code: String, message: String) : RuntimeException(message)
@@ -7,56 +7,50 @@ import android.widget.FrameLayout
7
7
  import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
8
8
 
9
9
  /**
10
- * The `pullToRefresh` prop. WebView sends no nested-scroll events, so it asks the WebView whether the document can
11
- * scroll up, and on touch-down asks the page whether the element under the finger is inside an inner scroller
12
- * (overflow: auto or scroll) that is already scrolled.
10
+ * WebView sends no nested-scroll events, so it asks the WebView whether the document can scroll up, and on touch-down
11
+ * asks the page whether the element under the finger is inside an inner scroller (overflow: auto or scroll) that is
12
+ * already scrolled.
13
13
  */
14
14
  internal class PullToRefresh(private val owner: MinimalWebView) {
15
- // The page's answer for the current touch; null while it is pending, which holds the pull off. The down event itself
16
- // must see false: SwipeRefreshLayout only tracks a gesture whose down event it accepted.
17
- private var innerScrolled: Boolean? = false
15
+ // The down event itself must see UNSCROLLED: SwipeRefreshLayout only tracks a gesture whose down event it accepted.
16
+ private var innerScroller = InnerScroller.UNSCROLLED
18
17
  private var touches = 0
19
18
 
20
- /** Holds the WebView. SwipeRefreshLayout keeps its first child as its target for good, so a crash swaps the WebView here. */
19
+ /** SwipeRefreshLayout keeps its first child as its target for good, so a crash swaps the WebView here. */
21
20
  val content = FrameLayout(owner.context)
22
21
 
23
- /** Always around [content]; off until the prop sets `isEnabled`. */
24
22
  val layout: SwipeRefreshLayout = Layout(owner.context).apply {
25
23
  isEnabled = false
26
24
  addView(content, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
27
25
  setOnRefreshListener { owner.reload() }
28
- setOnChildScrollUpCallback { _, _ -> owner.webView.canScrollVertically(-1) || innerScrolled != false }
26
+ setOnChildScrollUpCallback { _, _ -> owner.webView.canScrollVertically(-1) || innerScroller != InnerScroller.UNSCROLLED }
29
27
  }
30
28
 
31
29
  private fun checkInnerScroller(x: Float, y: Float) {
32
30
  val touch = ++touches
33
31
  val density = owner.webView.resources.displayMetrics.density
34
32
  owner.webView.evaluateJavascript("($INNER_SCROLLED)(${x / density}, ${y / density})") { result ->
35
- if (touch == touches) innerScrolled = result == "true"
33
+ if (touch == touches) innerScroller = if (result == "true") InnerScroller.SCROLLED else InnerScroller.UNSCROLLED
36
34
  }
37
- // A busy page answers late: don't hold the pull off for longer than this.
38
- mainHandler.postDelayed({ if (touch == touches && innerScrolled == null) innerScrolled = false }, ANSWER_TIMEOUT_MS)
35
+ mainHandler.postDelayed({ if (touch == touches && innerScroller == InnerScroller.ASKING) innerScroller = InnerScroller.UNSCROLLED }, ANSWER_TIMEOUT_MS)
39
36
  }
40
37
 
41
38
  /** A load ended: the spinner stops, or it would ignore the next pull. */
42
39
  fun pageFinished() {
43
40
  layout.isRefreshing = false
44
- innerScrolled = false
41
+ innerScroller = InnerScroller.UNSCROLLED
45
42
  }
46
43
 
47
44
  private inner class Layout(context: Context) : SwipeRefreshLayout(context) {
48
45
  override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
49
- // Off: no pull, and no question to the page on every touch.
50
46
  if (!isEnabled) return false
51
47
  if (event.actionMasked != MotionEvent.ACTION_DOWN) return super.onInterceptTouchEvent(event)
52
- innerScrolled = false
48
+ innerScroller = InnerScroller.UNSCROLLED
53
49
  val intercepted = super.onInterceptTouchEvent(event)
54
50
  if (owner.webView.canScrollVertically(-1)) {
55
- // A scrolled document already ruled this gesture out, whatever the page says: don't ask it. Dropping the
56
- // count makes a late answer or timeout from an earlier touch a no-op.
57
51
  touches++
58
52
  } else {
59
- innerScrolled = null
53
+ innerScroller = InnerScroller.ASKING
60
54
  checkInnerScroller(event.x, event.y)
61
55
  }
62
56
  return intercepted
@@ -64,6 +58,8 @@ internal class PullToRefresh(private val owner: MinimalWebView) {
64
58
  }
65
59
  }
66
60
 
61
+ private enum class InnerScroller { UNSCROLLED, SCROLLED, ASKING }
62
+
67
63
  private const val ANSWER_TIMEOUT_MS = 150L
68
64
 
69
65
  /** True when the element at (x, y) has a scrolled ancestor that can scroll vertically (CSS pixels). */
@@ -22,13 +22,10 @@ import java.util.concurrent.ArrayBlockingQueue
22
22
  import java.util.concurrent.Executors
23
23
  import java.util.concurrent.TimeUnit
24
24
 
25
- /** The server answered [code], not 2xx. */
26
25
  internal class HttpStatus(val code: Int) : IOException("HTTP $code")
27
26
 
28
- /** The file is above [Downloads.MAX_BYTES]. */
29
27
  internal class TooLarge : IOException(Downloads.TOO_LARGE)
30
28
 
31
- /** What WebView's DownloadListener reports. */
32
29
  internal data class DownloadInfo(
33
30
  val url: String,
34
31
  val userAgent: String,
@@ -37,9 +34,8 @@ internal data class DownloadInfo(
37
34
  )
38
35
 
39
36
  /**
40
- * The `onDownload` prop. WebView hands over only the URL, so http(s) is fetched again, through `HttpURLConnection` and
41
- * the WebView profile's `CookieManager` rather than React Native's OkHttp, so the package builds without
42
- * `react-android`. Nothing here may crash the app: the page controls the URL.
37
+ * WebView hands over only the URL, so http(s) is fetched again, through `HttpURLConnection` and the WebView profile's
38
+ * `CookieManager` rather than React Native's OkHttp, so the package builds without `react-android`.
43
39
  */
44
40
  internal class Downloads(private val owner: MinimalWebView) {
45
41
  private val io = Executors.newSingleThreadExecutor()
@@ -66,11 +62,7 @@ internal class Downloads(private val owner: MinimalWebView) {
66
62
  return data.second
67
63
  }
68
64
 
69
- /**
70
- * Runs [write] off the main thread (a download can be megabytes); it fills the file and returns its MIME type. One
71
- * directory per download, so the same guessed name never overwrites a file already handed to the app. The event goes
72
- * back on the main thread. [url] is the download's own URL, for the event.
73
- */
65
+ /** Runs [write] off the main thread; it fills the file and returns its MIME type. */
74
66
  private fun save(name: String, url: String, write: (File) -> String) {
75
67
  val file = File(owner.webView.context.cacheDir, "downloads/${System.nanoTime()}/$name")
76
68
  io.execute {
@@ -78,10 +70,9 @@ internal class Downloads(private val owner: MinimalWebView) {
78
70
  file.parentFile?.mkdirs()
79
71
  write(file)
80
72
  } catch (e: Exception) {
81
- // a malformed data: URL or forged JSON from the page: no failure may reach the io thread
82
73
  e
83
74
  }
84
- if (result is Exception) file.parentFile?.deleteRecursively() // no partial file stays in the cache
75
+ if (result is Exception) file.parentFile?.deleteRecursively()
85
76
  mainHandler.post {
86
77
  when (result) {
87
78
  is String -> owner.emit(
@@ -106,7 +97,7 @@ internal class Downloads(private val owner: MinimalWebView) {
106
97
  val (size, data) = readChunk(url, offset)
107
98
  type = append(file, decodeChunk(data))
108
99
  offset += CHUNK_BYTES
109
- if (offset > MAX_BYTES) throw TooLarge() // the page's own size check can be forged
100
+ if (offset > MAX_BYTES) throw TooLarge()
110
101
  } while (offset < size)
111
102
  type
112
103
  }
@@ -124,8 +115,7 @@ internal class Downloads(private val owner: MinimalWebView) {
124
115
  mainHandler.post { owner.evaluate(script) { reply.offer(it) } }
125
116
  val result = reply.poll(TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS) ?: throw IOException("the page did not read the blob in time")
126
117
  val json = result.getOrElse { throw IOException("could not read the blob: ${it.message}") }
127
- // A reply far longer than a chunk's data: URL is forged: refuse it before it is copied twice more.
128
- if (json.length > CHUNK_BYTES / 3 * 4 + 1024) throw TooLarge()
118
+ if (json.length > MAX_CHUNK_REPLY_CHARS) throw TooLarge()
129
119
  val chunk = JSONTokener(json).nextValue() as? JSONArray ?: throw IOException("could not read the blob")
130
120
  return chunk.getLong(0) to chunk.getString(1)
131
121
  }
@@ -148,11 +138,12 @@ internal class Downloads(private val owner: MinimalWebView) {
148
138
  }
149
139
 
150
140
  internal companion object {
151
- // The page picks the file, and an http(s) one fills the cache: above this a download fails instead.
152
- const val MAX_BYTES = 100L * 1024 * 1024
153
- const val TOO_LARGE = "larger than 100 MB"
141
+ private const val MAX_MIB = 100L
142
+ const val MAX_BYTES = MAX_MIB * 1024 * 1024
143
+ const val TOO_LARGE = "larger than $MAX_MIB MiB"
154
144
  const val CHUNK_BYTES = 4L * 1024 * 1024
155
- const val MAX_REDIRECTS = 20 // OkHttp's, which React Native's fetch uses
145
+ private const val MAX_CHUNK_REPLY_CHARS = CHUNK_BYTES / 3 * 4 + 1024
146
+ const val MAX_REDIRECTS = 20 // OkHttp's limit, which React Native's fetch uses
156
147
  const val TIMEOUT_MS = 30_000
157
148
  private val PERCENT_ESCAPE = Regex("%[0-9A-Fa-f]{2}")
158
149
 
@@ -161,7 +152,6 @@ internal class Downloads(private val owner: MinimalWebView) {
161
152
  * except [TooLarge]; `data` for everything else.
162
153
  */
163
154
  fun kind(error: Exception, fetched: Boolean) =
164
- // shortcut: a disk error while an http(s) body streams reads as network; tell them apart if apps need to.
165
155
  if (fetched && error is IOException && error !is TooLarge) "network" else "data"
166
156
 
167
157
  /**
@@ -189,8 +179,7 @@ internal class Downloads(private val owner: MinimalWebView) {
189
179
 
190
180
  /** [text]'s UTF-8 bytes with each `%XX` replaced by the byte XX. The result is not decoded as UTF-8 again. */
191
181
  private fun percentDecode(text: String): ByteArray {
192
- if ('%' !in text) return text.toByteArray() // a blob's chunks: spares two copies of megabytes
193
- // Latin-1 maps each byte to one char and back, so the escapes are replaced in a string.
182
+ if ('%' !in text) return text.toByteArray()
194
183
  val latin1 = String(text.toByteArray(), Charsets.ISO_8859_1)
195
184
  return PERCENT_ESCAPE.replace(latin1) { it.value.substring(1).toInt(16).toChar().toString() }.toByteArray(Charsets.ISO_8859_1)
196
185
  }
@@ -6,7 +6,6 @@ import android.webkit.WebChromeClient.FileChooserParams
6
6
  import expo.modules.minimalwebview.MinimalWebView
7
7
  import expo.modules.minimalwebview.MinimalWebViewModule
8
8
 
9
- /** `<input type="file">`, and the `onFileRequest` prop. */
10
9
  internal class FileUpload(private val owner: MinimalWebView) {
11
10
  // The page's open file chooser (WebView allows one at a time). Chromium releases it only while its document is alive,
12
11
  // so a navigation away cancels it when it starts, not at commit; a later answer is dropped.
@@ -14,12 +14,10 @@ import androidx.core.view.WindowInsetsControllerCompat
14
14
  import expo.modules.minimalwebview.DocumentEnd
15
15
  import expo.modules.minimalwebview.MinimalWebView
16
16
 
17
- /** HTML5 fullscreen video, and the `onFullscreenChange` prop. */
18
17
  internal class FullscreenVideo(private val owner: MinimalWebView) {
19
18
  private var shownCallback: CustomViewCallback? = null
20
19
  private var backdrop: FrameLayout? = null
21
20
  private var backCallback: OnBackPressedCallback? = null
22
- // The app's bars before fullscreen, restored on exit: an immersive app keeps its bars hidden.
23
21
  private var barsShownBefore = 0
24
22
  private var barsBehaviorBefore: Int? = null
25
23
 
@@ -58,7 +56,6 @@ internal class FullscreenVideo(private val owner: MinimalWebView) {
58
56
  callback.onCustomViewHidden()
59
57
  }
60
58
 
61
- /** Removes the fullscreen view, which WebView hid or we are leaving. */
62
59
  fun onHideCustomView() {
63
60
  if (shownCallback == null) return
64
61
  shownCallback = null
@@ -80,7 +77,7 @@ internal class FullscreenVideo(private val owner: MinimalWebView) {
80
77
 
81
78
  private fun controller() = owner.appContext.currentActivity?.window?.let { WindowCompat.getInsetsController(it, it.decorView) }
82
79
 
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. */
80
+ /** Only CLOSING (unmount) also tells WebView via `onCustomViewHidden`; after a crash no renderer is left to tell. */
84
81
  fun documentEnded(reason: DocumentEnd) {
85
82
  if (reason == DocumentEnd.CLOSING) exit() else onHideCustomView()
86
83
  }
@@ -6,51 +6,61 @@ import android.webkit.PermissionRequest
6
6
  import expo.modules.minimalwebview.MinimalWebView
7
7
  import expo.modules.minimalwebview.defaultPorts
8
8
 
9
- /** The `onPermissionRequest` prop. */
10
9
  internal class Permissions(private val owner: MinimalWebView) {
11
- // Asks still waiting for JS's answer, keyed by their PermissionRequest or GeolocationPermissions.Callback so a platform cancel finds them.
12
- private val waiting = mutableMapOf<Any, Int>()
10
+ private val requests = Waiting<PermissionRequest>()
11
+ private val prompts = Waiting<GeolocationPermissions.Callback>()
13
12
 
14
13
  /** Returns true when the app's prop takes the request; it is then granted or denied once. */
15
14
  fun onPermissionRequest(request: PermissionRequest): Boolean {
16
15
  val known = request.resources.filter { it in RESOURCES }
17
- return decide(request, request.origin.toString(), known.map { RESOURCES.getValue(it) }, deny = request::deny) {
16
+ return requests.decide(request, request.origin.toString(), known.map { RESOURCES.getValue(it) }, deny = request::deny) {
18
17
  request.grant(known.toTypedArray())
19
18
  }
20
19
  }
21
20
 
22
21
  fun onGeolocationPrompt(origin: String, callback: GeolocationPermissions.Callback) =
23
- decide(callback, origin, listOf("geolocation"), deny = { callback.invoke(origin, false, false) }) {
22
+ prompts.decide(callback, origin, listOf("geolocation"), deny = { callback.invoke(origin, false, false) }) {
24
23
  callback.invoke(origin, true, false)
25
24
  }
26
25
 
27
26
  // Chromium gave up on the request: cancel its ask, removed first so that nothing answers the request. Answering one
28
27
  // Chromium already destroyed aborts the app on WebView 133 (an invalid JNI weak reference).
29
- fun onPermissionRequestCanceled(request: PermissionRequest) {
30
- waiting.remove(request)?.let { owner.asks.cancel(it) }
31
- }
28
+ fun onPermissionRequestCanceled(request: PermissionRequest) = requests.cancel(request)
32
29
 
33
30
  // Not told which prompt: every geolocation ask goes, unanswered like a cancelled request.
34
- fun onGeolocationPromptHidden() =
35
- waiting.keys.filterIsInstance<GeolocationPermissions.Callback>().forEach { key -> waiting.remove(key)?.let { owner.asks.cancel(it) } }
31
+ fun onGeolocationPromptHidden() = prompts.cancelAll()
32
+
33
+ private inner class Waiting<K> {
34
+ private val ids = mutableMapOf<K, Int>()
36
35
 
37
- /**
38
- * Asks the app, then runs [grant] or [deny]. Returns false (the caller denies) without the prop. Android reports the
39
- * requesting frame's origin but not the frame, so an origin other than the top-level page's is denied.
40
- */
41
- private fun decide(key: Any, origin: String, resources: List<String>, deny: () -> Unit, grant: () -> Unit): Boolean {
42
- if ("onPermissionRequest" !in owner.requestHandlers) return false
43
- val value = originOf(origin)
44
- if (resources.isEmpty() || value != originOf(owner.url)) {
45
- deny()
36
+ /**
37
+ * Asks the app, then runs [grant] or [deny]. Returns false (the caller denies) without the prop. Android reports the
38
+ * requesting frame's origin but not the frame, so an origin other than the top-level page's is denied.
39
+ */
40
+ fun decide(key: K, origin: String, resources: List<String>, deny: () -> Unit, grant: () -> Unit): Boolean {
41
+ if ("onPermissionRequest" !in owner.requestHandlers) return false
42
+ val value = originOf(origin)
43
+ if (resources.isEmpty() || value != originOf(owner.url)) {
44
+ deny()
45
+ return true
46
+ }
47
+ val id = owner.asks.ask("core", "onPermissionRequest", mapOf("origin" to value, "resources" to resources)) { answer ->
48
+ if (ids.remove(key) == null) return@ask
49
+ if (answer == true) grant() else deny()
50
+ }
51
+ if (id != null) ids[key] = id
46
52
  return true
47
53
  }
48
- waiting[key] = owner.asks.ask("core", "onPermissionRequest", mapOf("origin" to value, "resources" to resources)) { answer ->
49
- // Not there: Chromium cancelled the request, and it takes no answer.
50
- if (waiting.remove(key) == null) return@ask
51
- if (answer == true) grant() else deny()
54
+
55
+ fun cancel(key: K) {
56
+ ids.remove(key)?.let { owner.asks.cancel(it) }
57
+ }
58
+
59
+ fun cancelAll() {
60
+ val cancelled = ids.values.toList()
61
+ ids.clear()
62
+ cancelled.forEach { owner.asks.cancel(it) }
52
63
  }
53
- return true
54
64
  }
55
65
 
56
66
  internal companion object {
@@ -9,6 +9,14 @@ export type AskableEvent = {
9
9
  payload: Record<string, unknown>;
10
10
  askId?: number;
11
11
  };
12
+ export type CoreEventPayloads = {
13
+ warning: {
14
+ message: string;
15
+ };
16
+ askCancelled: {
17
+ askId: number;
18
+ };
19
+ };
12
20
  export type NativeMethods = {
13
21
  goBack(): Promise<void>;
14
22
  goForward(): Promise<void>;
@@ -16,7 +24,6 @@ export type NativeMethods = {
16
24
  reload(): Promise<void>;
17
25
  stopLoading(): Promise<void>;
18
26
  bridgePost(message: string): Promise<void>;
19
- /** Answers a native `ask`. `json` is JSON, as for `call`. */
20
27
  answer(askId: number, json: string): Promise<void>;
21
28
  /** The JSON-encoded result. */
22
29
  evaluate(script: string): Promise<string>;
@@ -33,6 +40,8 @@ export type NativeMethods = {
33
40
  /**
34
41
  * A WebView whose core decides navigations and owns the navigation state: see {@link WebViewProps} and
35
42
  * {@link WebViewRef}.
43
+ * @throws An `Error` as it renders when the app was built without the package's native module: on iOS, below the
44
+ * deployment target 17.0.
36
45
  * @group WebView
37
46
  */
38
47
  export declare function WebView(props: WebViewProps): import("react").JSX.Element;
@@ -48,7 +57,7 @@ export declare const AndroidWebView: {
48
57
  * Android's default user agent, for `android.settings.userAgentString` with a suffix.
49
58
  *
50
59
  * The first read loads WebView's code, on the JS thread: read it once `warmUp()` has had time or a WebView is
51
- * mounted.
60
+ * mounted. It is null while Android System WebView is missing, disabled or updating, and a later read tries again.
52
61
  * @android
53
62
  */
54
63
  readonly defaultUserAgent: string | null;
@@ -1 +1 @@
1
- {"version":3,"file":"WebView.d.ts","sourceRoot":"","sources":["../src/WebView.tsx"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAQV,YAAY,EAEb,MAAM,SAAS,CAAC;AASjB;;;GAGG;AACH,MAAM,MAAM,YAAY,GAAG;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACjC,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAoEF,MAAM,MAAM,aAAa,GAAG;IAC1B,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACxB,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3B,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACjC,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACxB,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAC7B,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3C,6DAA6D;IAC7D,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;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