react-native-minimal-webview 1.1.0 → 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 (70) hide show
  1. package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +1 -6
  2. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +34 -22
  3. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +3 -2
  4. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +2 -1
  5. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +3 -3
  6. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +5 -7
  7. package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +29 -34
  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 -100
  15. package/build/WebView.js.map +1 -1
  16. package/build/bridge/createBridge.d.ts +17 -11
  17. package/build/bridge/createBridge.d.ts.map +1 -1
  18. package/build/bridge/createBridge.js +32 -44
  19. package/build/bridge/createBridge.js.map +1 -1
  20. package/build/bridge/endpoint.d.ts +1 -3
  21. package/build/bridge/endpoint.d.ts.map +1 -1
  22. package/build/bridge/endpoint.js +2 -2
  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 -17
  42. package/build/refStore.js.map +1 -1
  43. package/build/types.d.ts +39 -16
  44. package/build/types.d.ts.map +1 -1
  45. package/ios/DelegateProxy.swift +32 -30
  46. package/ios/Loads.swift +4 -4
  47. package/ios/MRWInvoke.h +8 -0
  48. package/ios/MRWInvoke.m +39 -24
  49. package/ios/MinimalWebView+Navigation.swift +17 -14
  50. package/ios/MinimalWebView.swift +72 -28
  51. package/ios/MinimalWebViewModule.swift +1 -0
  52. package/ios/NavigationRules.swift +15 -15
  53. package/ios/PlatformSettings.swift +2 -13
  54. package/ios/SharedCookies.swift +1 -2
  55. package/package.json +1 -1
  56. package/src/WebView.tsx +50 -114
  57. package/src/bridge/createBridge.ts +45 -53
  58. package/src/bridge/endpoint.ts +3 -5
  59. package/src/bridge/origins.ts +18 -6
  60. package/src/bridge/pageClient.generated.ts +1 -1
  61. package/src/index.ts +1 -1
  62. package/src/navigationRules.ts +111 -0
  63. package/src/refStore.ts +15 -19
  64. package/src/types.ts +39 -16
  65. package/build/defaultNavigationRules.d.ts.map +0 -1
  66. package/build/defaultNavigationRules.js +0 -22
  67. package/build/defaultNavigationRules.js.map +0 -1
  68. package/ios/MRWExceptions.h +0 -9
  69. package/ios/MRWExceptions.m +0 -10
  70. 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
@@ -422,11 +421,7 @@ internal class HookContext(val hook: MinimalWebViewHooks.Hook, view: MinimalWebV
422
421
 
423
422
  // A hook's shouldInterceptRequest runs on Chromium's IO thread; the view's events and asks are main-thread state.
424
423
  private fun onMain(block: () -> Unit) {
425
- if (Looper.myLooper() == Looper.getMainLooper()) block() else main.post { block() }
426
- }
427
-
428
- private companion object {
429
- val main = Handler(Looper.getMainLooper())
424
+ if (Looper.myLooper() == Looper.getMainLooper()) block() else mainHandler.post { block() }
430
425
  }
431
426
  }
432
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
@@ -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,6 +463,12 @@ 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
474
  /** Whether this process has made a WebView. */
@@ -504,7 +516,7 @@ private fun canonicalUrl(url: String): String {
504
516
  private val urlAuthority = Regex("^([a-zA-Z][a-zA-Z0-9+.-]*)://([^/?#@]*@)?(\\[[^\\]/?#]*]|[^/?#:]*)(?::(\\d*))?(.*)$")
505
517
 
506
518
  /** The special schemes' default ports (the WHATWG URL Standard's), as on iOS (Loads.swift). */
507
- private val defaultPorts = mapOf("http" to 80, "https" to 443, "ws" to 80, "wss" to 443, "ftp" to 21)
519
+ internal val defaultPorts = mapOf("http" to 80, "https" to 443, "ws" to 80, "wss" to 443, "ftp" to 21)
508
520
 
509
521
  /**
510
522
  * Records a renderer death at [now] in [times] and says whether to reload after it: not after more than
@@ -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
 
@@ -212,7 +213,7 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
212
213
  // Returning true keeps the app alive; a stale WebView (already replaced) needs nothing more.
213
214
  // Timed here: every WebView on the renderer hears of its death back to back, before any recovery runs.
214
215
  val at = SystemClock.elapsedRealtime()
215
- 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) }
216
217
  observing("onRenderProcessGone", WEB_VIEW, RenderProcessGoneDetail::class.java) { it.onRenderProcessGone(view, detail) }
217
218
  return true
218
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)
@@ -79,7 +79,7 @@ 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
85
  // WebView's request headers on a navigation are empty, so the page's URL goes as the Referer, trimmed by WebView's
@@ -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
  /**
@@ -109,12 +109,17 @@ internal class PlatformSettings(private val targets: (root: String) -> List<Targ
109
109
  fun call(path: String, args: List<Any?>, reply: (() -> String) -> Unit) {
110
110
  val (targets, name) = resolve(path)
111
111
  if (name in OWNED) throw problem("$name is ${owned(name)}")
112
- val result = invokeFirst(targets, name, args) { true }
113
- 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
+ }
114
117
  // The callback runs later, outside the caller's try: the receiver converts, so it can reject instead of crashing.
115
118
  val callback = ValueCallback<Any?> { value -> reply { toJson(value) } }
116
- val awaiting = invokeFirst(targets, name, args + callback) { it.parameterTypes.lastOrNull() == ValueCallback::class.java }
117
- 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()
118
123
  }
119
124
 
120
125
  /** The targets of `root.key` and the key; throws for a malformed path or an unknown root. */
@@ -156,16 +161,16 @@ internal class PlatformSettings(private val targets: (root: String) -> List<Targ
156
161
  "setWebContentsDebuggingEnabled", "setOnTouchListener", "setOnScrollChangeListener", "addNavigationListener"
157
162
  )
158
163
 
159
- /** The result of the first method [name] of [targets] that [accepts] and takes [values], or [NONE] when none does. */
160
- 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?)? {
161
166
  for (target in targets) {
162
167
  for (method in target.cls.methods) {
163
- if (method.name != name || !accepts(method)) continue
164
- val arguments = arguments(method, target, values) ?: continue
165
- return invoke(method, target, arguments)
168
+ if (!accepts(method)) continue
169
+ val args = arguments(method, target, values) ?: continue
170
+ return { invoke(method, target, args) }
166
171
  }
167
172
  }
168
- return NONE
173
+ return null
169
174
  }
170
175
 
171
176
  private fun owned(name: String) =
@@ -183,36 +188,26 @@ internal class PlatformSettings(private val targets: (root: String) -> List<Targ
183
188
  if (key.isEmpty() || key.startsWith("_")) return "not a public setter"
184
189
  val setter = "set" + key.replaceFirstChar { it.uppercaseChar() }
185
190
  if (setter in OWNED) return owned(setter)
186
- var seen = false
187
- for (target in targets) {
188
- for (method in target.cls.methods) {
189
- if (method.name != setter) continue
190
- seen = true
191
- val args = arguments(method, target, listOf(value)) ?: continue
192
- return try {
193
- before()
194
- invoke(method, target, args)
195
- null
196
- } catch (e: IllegalArgumentException) { // a PlatformException from invoke is one, so its reason is the message
197
- e.message
198
- }
199
- }
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
200
201
  }
201
- return if (seen) "no public setter takes a ${value?.javaClass?.simpleName ?: "null"}" else "no public setter"
202
202
  }
203
203
 
204
204
  /** The value of [key]'s getter on the first target that has one, or [NONE]. */
205
205
  private fun read(targets: List<Target>, key: String): Any? {
206
206
  val capital = key.replaceFirstChar { it.uppercaseChar() }
207
- for (target in targets) {
208
- for (method in target.cls.methods) {
209
- val getter = method.name == "get$capital" || method.name == "is$capital"
210
- if (!getter && (method.name != key || method.returnType == Void.TYPE)) continue
211
- val args = arguments(method, target, emptyList()) ?: continue
212
- return invoke(method, target, args)
213
- }
214
- }
215
- 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()
216
211
  }
217
212
 
218
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) {
@@ -4,6 +4,7 @@ import android.net.Uri
4
4
  import android.webkit.GeolocationPermissions
5
5
  import android.webkit.PermissionRequest
6
6
  import expo.modules.minimalwebview.MinimalWebView
7
+ import expo.modules.minimalwebview.defaultPorts
7
8
 
8
9
  /** The `onPermissionRequest` prop. */
9
10
  internal class Permissions(private val owner: MinimalWebView) {
@@ -40,7 +41,7 @@ internal class Permissions(private val owner: MinimalWebView) {
40
41
  private fun decide(key: Any, origin: String, resources: List<String>, deny: () -> Unit, grant: () -> Unit): Boolean {
41
42
  if ("onPermissionRequest" !in owner.requestHandlers) return false
42
43
  val value = originOf(origin)
43
- if (resources.isEmpty() || value != originOf(owner.webView.url)) {
44
+ if (resources.isEmpty() || value != originOf(owner.url)) {
44
45
  deny()
45
46
  return true
46
47
  }
@@ -69,9 +70,7 @@ internal class Permissions(private val owner: MinimalWebView) {
69
70
  }
70
71
 
71
72
  /** [originOf] from the scheme, host and port (-1 for none) that `Uri` parses. */
72
- fun origin(scheme: String?, host: String?, port: Int): String {
73
- val defaultPort = if (scheme == "https") 443 else 80
74
- return "$scheme://$host" + if (port == -1 || port == defaultPort) "" else ":$port"
75
- }
73
+ fun origin(scheme: String?, host: String?, port: Int) =
74
+ "$scheme://$host" + if (port == -1 || port == defaultPorts[scheme]) "" else ":$port"
76
75
  }
77
76
  }
@@ -1,13 +1,4 @@
1
1
  import type { WebViewProps } from './types';
2
- /** A page's message comes with its origin, as native verified it (`location.origin` form). */
3
- export type BridgeEvent = {
4
- message: string;
5
- origin: string;
6
- } | {
7
- navigated: true;
8
- } | {
9
- unavailable: true;
10
- };
11
2
  /**
12
3
  * An event as native sends it: `key` is the hook's key, `core` for the core's own. `askId` is set when native waits for
13
4
  * the answer.
@@ -21,6 +12,7 @@ export type AskableEvent = {
21
12
  export type NativeMethods = {
22
13
  goBack(): Promise<void>;
23
14
  goForward(): Promise<void>;
15
+ load(url: string): Promise<void>;
24
16
  reload(): Promise<void>;
25
17
  stopLoading(): Promise<void>;
26
18
  bridgePost(message: string): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"WebView.d.ts","sourceRoot":"","sources":["../src/WebView.tsx"],"names":[],"mappings":"AASA,OAAO,KAAK,EASV,YAAY,EAEb,MAAM,SAAS,CAAC;AASjB,8FAA8F;AAC9F,MAAM,MAAM,WAAW,GACrB;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,SAAS,EAAE,IAAI,CAAA;CAAE,GAAG;IAAE,WAAW,EAAE,IAAI,CAAA;CAAE,CAAC;AAEpF;;;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,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;IACnD,+BAA+B;IAC/B,QAAQ,CAAC,MAAM,EAAE,M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