react-native-minimal-webview 1.2.1 → 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 (96) hide show
  1. package/android/build.gradle +1 -1
  2. package/android/src/main/java/expo/modules/minimalwebview/Asks.kt +5 -11
  3. package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +17 -11
  4. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +64 -119
  5. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +16 -31
  6. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +4 -16
  7. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +24 -38
  8. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +24 -36
  9. package/android/src/main/java/expo/modules/minimalwebview/NavigationRules.kt +19 -20
  10. package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +25 -37
  11. package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +14 -18
  12. package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +12 -23
  13. package/android/src/main/java/expo/modules/minimalwebview/requests/FileUpload.kt +0 -1
  14. package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +1 -4
  15. package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +34 -24
  16. package/build/WebView.d.ts +8 -1
  17. package/build/WebView.d.ts.map +1 -1
  18. package/build/WebView.js +22 -68
  19. package/build/WebView.js.map +1 -1
  20. package/build/bridge/createBridge.d.ts +1 -5
  21. package/build/bridge/createBridge.d.ts.map +1 -1
  22. package/build/bridge/createBridge.js +3 -15
  23. package/build/bridge/createBridge.js.map +1 -1
  24. package/build/bridge/endpoint.d.ts +1 -2
  25. package/build/bridge/endpoint.d.ts.map +1 -1
  26. package/build/bridge/endpoint.js +5 -6
  27. package/build/bridge/endpoint.js.map +1 -1
  28. package/build/bridge/matchesOrigin.d.ts +11 -0
  29. package/build/bridge/matchesOrigin.d.ts.map +1 -0
  30. package/build/bridge/matchesOrigin.js +26 -0
  31. package/build/bridge/matchesOrigin.js.map +1 -0
  32. package/build/bridge/origins.d.ts +2 -13
  33. package/build/bridge/origins.d.ts.map +1 -1
  34. package/build/bridge/origins.js +1 -30
  35. package/build/bridge/origins.js.map +1 -1
  36. package/build/bridge/pageClient.generated.d.ts +1 -1
  37. package/build/bridge/pageClient.generated.d.ts.map +1 -1
  38. package/build/bridge/pageClient.generated.js +2 -2
  39. package/build/bridge/pageClient.generated.js.map +1 -1
  40. package/build/bridge/protocol.d.ts +3 -5
  41. package/build/bridge/protocol.d.ts.map +1 -1
  42. package/build/bridge/protocol.js +12 -14
  43. package/build/bridge/protocol.js.map +1 -1
  44. package/build/index.d.ts +1 -1
  45. package/build/index.js +1 -1
  46. package/build/navigationRules.d.ts +0 -5
  47. package/build/navigationRules.d.ts.map +1 -1
  48. package/build/navigationRules.js +3 -12
  49. package/build/navigationRules.js.map +1 -1
  50. package/build/reactNativeWebViewDefaults.d.ts +0 -4
  51. package/build/reactNativeWebViewDefaults.d.ts.map +1 -1
  52. package/build/reactNativeWebViewDefaults.js +0 -4
  53. package/build/reactNativeWebViewDefaults.js.map +1 -1
  54. package/build/reactNativeWebViewMessages.d.ts.map +1 -1
  55. package/build/reactNativeWebViewMessages.js +0 -1
  56. package/build/reactNativeWebViewMessages.js.map +1 -1
  57. package/build/refStore.d.ts +0 -2
  58. package/build/refStore.d.ts.map +1 -1
  59. package/build/refStore.js +0 -6
  60. package/build/refStore.js.map +1 -1
  61. package/build/types.d.ts +25 -12
  62. package/build/types.d.ts.map +1 -1
  63. package/ios/Asks.swift +6 -9
  64. package/ios/DelegateProxy.swift +2 -19
  65. package/ios/DownloadName.swift +0 -2
  66. package/ios/Downloads.swift +0 -2
  67. package/ios/Hooks.swift +4 -6
  68. package/ios/Loads.swift +37 -19
  69. package/ios/MinimalWebView+Dialogs.swift +2 -6
  70. package/ios/MinimalWebView+Navigation.swift +17 -50
  71. package/ios/MinimalWebView+Scripts.swift +4 -16
  72. package/ios/MinimalWebView.podspec +1 -2
  73. package/ios/MinimalWebView.swift +62 -132
  74. package/ios/MinimalWebViewModule.swift +1 -18
  75. package/ios/NavigationRules.swift +2 -9
  76. package/ios/OriginRules.swift +4 -13
  77. package/ios/PlatformSettings.swift +9 -30
  78. package/ios/ReadAccess.swift +0 -2
  79. package/ios/Records.swift +18 -0
  80. package/ios/Recovery.swift +2 -8
  81. package/ios/SharedCookies.swift +10 -25
  82. package/package.json +4 -4
  83. package/src/WebView.tsx +34 -77
  84. package/src/bridge/createBridge.ts +5 -20
  85. package/src/bridge/endpoint.ts +6 -9
  86. package/src/bridge/matchesOrigin.ts +27 -0
  87. package/src/bridge/origins.ts +2 -30
  88. package/src/bridge/pageClient.generated.ts +2 -2
  89. package/src/bridge/pageClient.ts +1 -7
  90. package/src/bridge/protocol.ts +16 -18
  91. package/src/index.ts +1 -1
  92. package/src/navigationRules.ts +6 -12
  93. package/src/reactNativeWebViewDefaults.ts +0 -4
  94. package/src/reactNativeWebViewMessages.ts +0 -1
  95. package/src/refStore.ts +0 -7
  96. package/src/types.ts +25 -12
@@ -1,6 +1,5 @@
1
1
  package expo.modules.minimalwebview
2
2
 
3
- import android.annotation.SuppressLint
4
3
  import android.graphics.Bitmap
5
4
  import android.net.Uri
6
5
  import android.net.http.SslError
@@ -29,11 +28,7 @@ import androidx.webkit.Navigation
29
28
  import androidx.webkit.NavigationListener
30
29
  import androidx.webkit.Page
31
30
 
32
- // WebView's callbacks, a new set for each WebView. Each one routes by the rule on WebViewContext.clients: a decision
33
- // callback through `deciding`, the rest through `observing`.
34
-
35
31
  internal class Listener(private val owner: MinimalWebView) : NavigationListener {
36
- /** Pages that fired their load event and are still alive (current or in the back-forward cache). */
37
32
  private val loadedPages = mutableSetOf<Page>()
38
33
 
39
34
  override fun onPageDeleted(page: Page) {
@@ -52,21 +47,20 @@ internal class Listener(private val owner: MinimalWebView) : NavigationListener
52
47
  owner.stateChanged()
53
48
  }
54
49
 
55
- // A failed main-frame load commits an error page at the failed URL: `url` becomes that URL, as on iOS.
56
50
  override fun onNavigationCompleted(navigation: Navigation) {
57
- // The Document ends before `url` moves on, so its handlers see the page that ended: as on iOS, and before 146,
58
- // where onPageStarted comes ahead of doUpdateVisitedHistory.
59
- if (navigation.didCommit() && !navigation.isSameDocument) owner.endDocument(DocumentEnd.COMMITTED)
51
+ if (navigation.didCommit() && !navigation.isSameDocument) owner.documents.end(DocumentEnd.COMMITTED)
60
52
  if (navigation.didCommit()) owner.url = navigation.url
61
53
  if (!navigation.isSameDocument) {
62
54
  owner.pendingUrl = null
63
- // A reported network or SSL error already made it "failed". Chromium's error page for an HTTP status (a 404 with
64
- // an empty body) is the server's answer: "finished", as on iOS.
65
- owner.outcome = owner.outcome ?: when {
66
- !navigation.didCommit() -> "cancelled" // a stop, a download, a 204, a blocked redirect, a newer load
67
- navigation.didCommitErrorPage() && navigation.statusCode < 400 -> "failed"
68
- else -> "finished"
69
- }
55
+ // Chromium's error page for an HTTP status (a 404 with an empty body) is the server's answer: "finished", as on
56
+ // iOS.
57
+ owner.settleOutcome(
58
+ when {
59
+ !navigation.didCommit() -> LoadOutcome.CANCELLED
60
+ navigation.didCommitErrorPage() && navigation.statusCode < 400 -> LoadOutcome.FAILED
61
+ else -> LoadOutcome.FINISHED
62
+ }
63
+ )
70
64
  // A page restored from the back-forward cache (its Page, already loaded) gets no onPageLoadEvent again.
71
65
  if (!navigation.didCommit() || navigation.page?.let { it in loadedPages } == true) owner.loadEnded()
72
66
  }
@@ -87,16 +81,12 @@ private val BOOLEAN = java.lang.Boolean.TYPE
87
81
  private val FLOAT = java.lang.Float.TYPE
88
82
 
89
83
  internal class Client(private val owner: MinimalWebView, private val navigation: MinimalWebViewNavigation) : WebViewClient() {
90
- /** The first hook client that overrides a decision callback, or null: the core decides. */
91
84
  private fun deciding(name: String, vararg types: Class<*>, lost: String? = null) =
92
85
  owner.deciders.first(name, owner.clients, lost) { it.overrides(name, *types) }
93
86
 
94
- /** Every hook client that overrides an observation callback, after the core. */
95
87
  private inline fun observing(name: String, vararg types: Class<*>, block: (WebViewClient) -> Unit) =
96
88
  owner.clients.forEach { if (it.overrides(name, *types)) block(it) }
97
89
 
98
- // Without NavigationListener: the last main-frame URL allowed to load (a page's navigation or a redirect), for
99
- // onReceivedSslError.
100
90
  private var allowedMainFrameUrl: String? = null
101
91
 
102
92
  // Not called for POST, the initial loadUrl, or reissued loads; called again for their redirects.
@@ -116,7 +106,7 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
116
106
  // blocked redirect) gets no load events and no outcome here.
117
107
  override fun onPageStarted(view: WebView, url: String?, favicon: Bitmap?) {
118
108
  if (!owner.hasNavigationListener) {
119
- owner.endDocument(DocumentEnd.COMMITTED)
109
+ owner.documents.end(DocumentEnd.COMMITTED)
120
110
  owner.loadStarted()
121
111
  }
122
112
  observing("onPageStarted", WEB_VIEW, STRING, Bitmap::class.java) { it.onPageStarted(view, url, favicon) }
@@ -124,7 +114,7 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
124
114
 
125
115
  override fun onPageFinished(view: WebView, url: String?) {
126
116
  if (!owner.hasNavigationListener) {
127
- owner.outcome = owner.outcome ?: "finished" // "failed" when a main-frame error came first
117
+ owner.settleOutcome(LoadOutcome.FINISHED)
128
118
  owner.loadEnded()
129
119
  }
130
120
  observing("onPageFinished", WEB_VIEW, STRING) { it.onPageFinished(view, url) }
@@ -139,7 +129,6 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
139
129
  override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? =
140
130
  deciding("shouldInterceptRequest", WEB_VIEW, WebResourceRequest::class.java)?.shouldInterceptRequest(view, request)
141
131
 
142
- // Main frame only: a subresource that fails to load (an ad) is the page's business.
143
132
  override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) {
144
133
  val description = error.description.toString()
145
134
  if (request.isForMainFrame && !description.contains("ERR_ABORTED")) {
@@ -158,7 +147,6 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
158
147
  if (hook != null) hook.onFormResubmission(view, dontResend, resend) else super.onFormResubmission(view, dontResend, resend)
159
148
  }
160
149
 
161
- // Without NavigationListener (WebView older than 146): best-effort URL tracking.
162
150
  override fun doUpdateVisitedHistory(view: WebView, url: String?, isReload: Boolean) {
163
151
  if (!owner.hasNavigationListener && url != null) {
164
152
  owner.url = url
@@ -167,7 +155,6 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
167
155
  observing("doUpdateVisitedHistory", WEB_VIEW, STRING, BOOLEAN) { it.doUpdateVisitedHistory(view, url, isReload) }
168
156
  }
169
157
 
170
- @SuppressLint("WebViewClientOnReceivedSslError") // because the core always cancels; it only reports the error
171
158
  override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, sslError: SslError) {
172
159
  val hook = deciding(
173
160
  "onReceivedSslError", WEB_VIEW, SslErrorHandler::class.java, SslError::class.java,
@@ -175,8 +162,8 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
175
162
  )
176
163
  if (hook != null) return hook.onReceivedSslError(view, handler, sslError)
177
164
  handler.cancel()
178
- // Also called for subresources (an ad image): only the main frame's URL is a page error. Without NavigationListener
179
- // there's no pendingUrl: view.url shows a loadUrl in progress (back/forward stays unreported).
165
+ // Also called for subresources (an ad image): only the main frame's URL is a page error.
166
+ // Without a NavigationListener there is no pendingUrl: WebView's url shows a loadUrl in progress.
180
167
  val mainFrame = if (owner.hasNavigationListener) setOf(owner.pendingUrl ?: owner.url) else setOf(view.url, allowedMainFrameUrl)
181
168
  if (sslError.url in mainFrame) {
182
169
  owner.reportError("ssl", sslError.url, sslError.primaryError, "SSL error ${sslError.primaryError}")
@@ -188,7 +175,6 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
188
175
  if (hook != null) hook.onReceivedClientCertRequest(view, request) else super.onReceivedClientCertRequest(view, request)
189
176
  }
190
177
 
191
- // Basic and digest auth: a hook client, else cancel (the page shows its 401).
192
178
  override fun onReceivedHttpAuthRequest(view: WebView, handler: HttpAuthHandler, host: String, realm: String) {
193
179
  val hook = deciding("onReceivedHttpAuthRequest", WEB_VIEW, HttpAuthHandler::class.java, STRING, STRING)
194
180
  if (hook != null) hook.onReceivedHttpAuthRequest(view, handler, host, realm) else handler.cancel()
@@ -210,7 +196,7 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
210
196
  observing("onReceivedLoginRequest", WEB_VIEW, STRING, STRING, STRING) { it.onReceivedLoginRequest(view, realm, account, args) }
211
197
 
212
198
  override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {
213
- // Returning true keeps the app alive; a stale WebView (already replaced) needs nothing more.
199
+ // Returning true keeps the app alive.
214
200
  // Timed here: every WebView on the renderer hears of its death back to back, before any recovery runs.
215
201
  val at = SystemClock.elapsedRealtime()
216
202
  if (view === owner.webView) mainHandler.post { owner.processGone(if (detail.didCrash()) "crash" else "memory", at) }
@@ -239,7 +225,7 @@ internal class ChromeClient(private val owner: MinimalWebView, private val navig
239
225
  ?: navigation.createWindow(isUserGesture, resultMsg)
240
226
 
241
227
  override fun onShowFileChooser(view: WebView, callback: ValueCallback<Array<Uri>>, params: FileChooserParams): Boolean {
242
- val once = owner.fileUpload.hold(callback) // before the hook branch: a hook's chooser is held too
228
+ val once = owner.fileUpload.hold(callback)
243
229
  val hook = deciding(
244
230
  "onShowFileChooser", WEB_VIEW, ValueCallback::class.java, FileChooserParams::class.java,
245
231
  lost = "onFileRequest doesn't apply"
@@ -249,7 +235,6 @@ internal class ChromeClient(private val owner: MinimalWebView, private val navig
249
235
  return true
250
236
  }
251
237
 
252
- // Without a hook client or the app's prop: deny (never grant device access by default).
253
238
  override fun onPermissionRequest(request: PermissionRequest) {
254
239
  val hook = deciding("onPermissionRequest", PermissionRequest::class.java, lost = "onPermissionRequest and the default deny don't apply")
255
240
  when {
@@ -41,9 +41,9 @@ class MinimalWebViewModule : Module() {
41
41
  private var chooserOpen = false
42
42
 
43
43
  /**
44
- * Opens the system file chooser (from ChromeClient.onShowFileChooser) and calls [onResult] with the picked URIs, or
45
- * null on cancel. One chooser is open app-wide: the launcher keeps one callback, so [onResult] gets null at once
46
- * while one is open, before the launcher is registered, or without an activity.
44
+ * Opens the system file chooser and calls [onResult] with the picked URIs, or null on cancel. One chooser is open
45
+ * app-wide: the launcher keeps one callback, so [onResult] gets null at once while one is open, before the launcher
46
+ * is registered, or without an activity.
47
47
  */
48
48
  internal fun openFileChooser(intent: Intent, onResult: (Array<Uri>?) -> Unit) {
49
49
  val launcher = fileChooser
@@ -65,7 +65,6 @@ class MinimalWebViewModule : Module() {
65
65
  Name("MinimalWebView")
66
66
 
67
67
  // The fallback runs when the result reaches a recreated activity: the WebView that asked is gone.
68
- // shortcut: choosers stay cancelled after an activity dies without a result, track the request if apps hit it
69
68
  RegisterActivityContracts {
70
69
  fileChooser = registerForActivityResult(FileChooserContract) { _, _ -> chooserOpen = false }
71
70
  }
@@ -76,7 +75,6 @@ class MinimalWebViewModule : Module() {
76
75
  if (webViewCreated) flushCookies()
77
76
  }
78
77
 
79
- // Best effort: an error only means the first WebView starts WebView as before.
80
78
  Function("warmUp") { warmUp(appContext.reactContext ?: throw Exceptions.ReactContextLost()) }
81
79
 
82
80
  // ProfileStore wants the UI thread, and starts WebView there.
@@ -96,7 +94,6 @@ class MinimalWebViewModule : Module() {
96
94
  Prop("bridgeScript") { view: MinimalWebView, script: String? -> view.bridgeScript = script }
97
95
  Prop("bridgeOrigins") { view: MinimalWebView, origins: List<String>? -> view.bridgeOrigins = origins }
98
96
  Prop("hookOptions") { view: MinimalWebView, options: Map<String, Any?>? -> view.hookOptions = options.orEmpty() }
99
- // The JSON is always an object (JS builds it).
100
97
  Prop("settings") { view: MinimalWebView, json: String? -> view.settings = json?.let { JSONObject(it).toMap() } }
101
98
  Prop("pullToRefresh") { view: MinimalWebView, value: Boolean? -> view.pullToRefresh = value ?: false }
102
99
  Prop("injectedScripts") { view: MinimalWebView, value: List<InjectedScript>? -> view.injectedScripts = value }
@@ -117,7 +114,6 @@ class MinimalWebViewModule : Module() {
117
114
  native(view, promise) {
118
115
  view.platformSettings.call(path, fromJson(JSONArray(argsJson)) as List<Any?>) { json -> native(view, promise) { promise.resolve(json()) } }
119
116
  }
120
- // A call can change what the state shows (clearHistory, canGoBack); an unchanged state isn't sent.
121
117
  view.stateChanged()
122
118
  }.runOnQueue(Queues.MAIN)
123
119
  AsyncFunction("bridgePost") { view: MinimalWebView, message: String -> view.scripts.post(message) }.runOnQueue(Queues.MAIN)
@@ -145,10 +141,6 @@ private fun preconnect(url: String) {
145
141
  }
146
142
  }
147
143
 
148
- /**
149
- * Writes the cookies of the default profile and every other one to disk: a WebView on another `android.webView.profile`
150
- * keeps its own.
151
- */
152
144
  private fun flushCookies() {
153
145
  CookieManager.getInstance().flush()
154
146
  if (!WebViewFeature.isFeatureSupported(WebViewFeature.MULTI_PROFILE)) return
@@ -183,7 +175,6 @@ private fun warmUp(context: Context) {
183
175
  WebViewCompat.startUpWebView(context, config, outcome)
184
176
  }
185
177
 
186
- /** Runs [action] on the WebView, unless it's recovering: `webView` is then the destroyed one, and only reload acts, by building the new one. */
187
178
  private fun live(view: MinimalWebView, action: (WebView) -> Unit) {
188
179
  if (!view.recovering) action(view.webView)
189
180
  }
@@ -228,7 +219,7 @@ private fun fromJson(value: Any?): Any? = when (value) {
228
219
  else -> value
229
220
  }
230
221
 
231
- /** The chooser's intent. Serializable because the registry persists launch inputs; it never relaunches a restored one. */
222
+ /** Serializable because the registry persists launch inputs; it never relaunches a restored one. */
232
223
  private class ChooserIntent(@Transient val intent: Intent? = null) : Serializable
233
224
 
234
225
  private object FileChooserContract : AppContextActivityResultContract<ChooserIntent, Array<Uri>?> {
@@ -238,13 +229,10 @@ private object FileChooserContract : AppContextActivityResultContract<ChooserInt
238
229
  FileChooserParams.parseResult(resultCode, intent)
239
230
  }
240
231
 
241
- // Data classes, so the skip checks in applyProps compare them with ==. Every field is optional, as on iOS.
242
-
243
232
  internal data class WebViewSource(
244
233
  @Field val uri: String? = null,
245
234
  @Field val headers: Map<String, String>? = null,
246
235
  @Field val body: String? = null,
247
- // Unused on Android: here so that a change loads the source again, as on iOS.
248
236
  @Field val readAccessRoot: String? = null,
249
237
  @Field val html: String? = null,
250
238
  @Field val baseUrl: String? = null
@@ -12,24 +12,20 @@ import android.webkit.WebView
12
12
  import android.webkit.WebViewClient
13
13
  import java.net.URISyntaxException
14
14
 
15
- /** Navigation decisions: the rules, `ask`, external links and new windows. */
16
15
  internal class MinimalWebViewNavigation(
17
16
  private val owner: MinimalWebView,
18
17
  private val onNavigation: (Map<String, Any?>) -> Unit
19
18
  ) {
20
19
  private val webView get() = owner.webView
21
20
 
22
- // URLs an `ask` allowed in this Document: a redirect back to one is not asked again (a later tap on it is).
23
21
  private val askedAndAllowed = mutableSetOf<String>()
24
22
 
25
- // New windows still waiting for their first URL (createWindow).
26
- private val children = mutableSetOf<WebView>()
23
+ private val pendingWindows = mutableSetOf<WebView>()
27
24
 
28
25
  fun documentEnded() {
29
26
  askedAndAllowed.clear()
30
- // Not on a child's stack (a commit, a crash, destroy): destroy them now. Cleared first, so a finish() finds none.
31
- val ended = children.toList()
32
- children.clear()
27
+ val ended = pendingWindows.toList()
28
+ pendingWindows.clear()
33
29
  ended.forEach { it.destroy() }
34
30
  }
35
31
 
@@ -37,23 +33,23 @@ internal class MinimalWebViewNavigation(
37
33
  fun decide(request: NavigationRules.Request): Boolean {
38
34
  val asked = if (request.isRedirect) askedAndAllowed else emptySet()
39
35
  val decision = NavigationRules.decide(owner.navigationRules, request, asked, "onNavigationRequest" in owner.requestHandlers)
40
- val action = if (decision.action == "ask" && !request.mainFrame) {
36
+ val action = if (decision.action == NavigationRules.Action.ASK && !request.mainFrame) {
41
37
  // loadUrl reissues only a main-frame navigation.
42
38
  Log.w(TAG, "`ask` only works for main-frame navigations on Android; blocked ${request.url}")
43
- "block"
39
+ NavigationRules.Action.BLOCK
44
40
  } else {
45
41
  decision.action
46
42
  }
47
- if (action == "ask") {
43
+ if (action == NavigationRules.Action.ASK) {
48
44
  ask(request, decision.rule)
49
45
  return true
50
46
  }
51
- if (action == "external") {
47
+ if (action == NavigationRules.Action.EXTERNAL) {
52
48
  openExternal(request, decision.rule)
53
49
  return true
54
50
  }
55
51
  notifyNavigation(request, action, decision.rule)
56
- return action != "allow"
52
+ return action != NavigationRules.Action.ALLOW
57
53
  }
58
54
 
59
55
  private fun fields(request: NavigationRules.Request) = mapOf(
@@ -63,23 +59,21 @@ internal class MinimalWebViewNavigation(
63
59
  "userInitiated" to request.userInitiated
64
60
  )
65
61
 
66
- private fun notifyNavigation(request: NavigationRules.Request, action: String, rule: Int?) {
67
- if ("onNavigation" in owner.requestHandlers) onNavigation(fields(request) + mapOf("action" to action, "rule" to rule))
62
+ private fun notifyNavigation(request: NavigationRules.Request, action: NavigationRules.Action, rule: Int?) {
63
+ if ("onNavigation" in owner.requestHandlers) onNavigation(fields(request) + mapOf("action" to action.jsName, "rule" to rule))
68
64
  }
69
65
 
70
- // Cancel now, ask JS, reissue on allow; the redirect chain is lost.
71
66
  private fun ask(request: NavigationRules.Request, rule: Int?) {
72
67
  val referrer = webView.url
73
68
  val id = owner.asks.ask("core", "onNavigationRequest", fields(request)) { answer ->
74
69
  val action = NavigationRules.answer(answer)
75
- if (action == "allow") {
70
+ if (action == NavigationRules.Action.ALLOW) {
76
71
  askedAndAllowed += request.url
77
72
  reissue(request.url, referrer)
78
73
  }
79
- if (action == "external") openExternal(request, rule) else notifyNavigation(request, action, rule)
74
+ if (action == NavigationRules.Action.EXTERNAL) openExternal(request, rule) else notifyNavigation(request, action, rule)
80
75
  }
81
- // Unanswered after the timeout: block (the answer callback runs with null). A late answer finds nothing.
82
- mainHandler.postDelayed({ owner.asks.cancel(id) }, ASK_TIMEOUT_MS)
76
+ if (id != null) mainHandler.postDelayed({ owner.asks.cancel(id) }, ASK_TIMEOUT_MS)
83
77
  }
84
78
 
85
79
  // WebView's request headers on a navigation are empty, so the page's URL goes as the Referer, trimmed by WebView's
@@ -87,7 +81,6 @@ internal class MinimalWebViewNavigation(
87
81
  // reissued URL isn't asked again (its redirects still go to decide).
88
82
  private fun reissue(url: String, referrer: String?) = webView.loadUrl(url, referrer?.let { mapOf("Referer" to it) }.orEmpty())
89
83
 
90
- /** A download no `onDownload` takes. */
91
84
  fun openDownload(url: String) {
92
85
  if (url.startsWith("http:") || url.startsWith("https:")) {
93
86
  openExternal(NavigationRules.Request(url, true, false, false), null)
@@ -96,23 +89,21 @@ internal class MinimalWebViewNavigation(
96
89
  }
97
90
  }
98
91
 
99
- /**
100
- * Opens an `external` navigation and reports it (`block` when nothing opened it): the app's `onOpenExternal` if set,
101
- * and [open] when it isn't or answers false.
102
- */
103
92
  private fun openExternal(request: NavigationRules.Request, rule: Int?) {
104
- val report = { opened: Boolean -> notifyNavigation(request, if (opened) "external" else "block", rule) }
93
+ val report = { opened: Boolean ->
94
+ notifyNavigation(request, if (opened) NavigationRules.Action.EXTERNAL else NavigationRules.Action.BLOCK, rule)
95
+ }
105
96
  if ("onOpenExternal" !in owner.requestHandlers) return report(open(request.url))
106
- // A page that moved on first answers null, which counts as opened. No timeout: nothing waits for the answer.
107
97
  owner.asks.ask("core", "onOpenExternal", fields(request)) { answer ->
108
- report(answer != false || open(request.url))
98
+ val appDeclined = answer == false
99
+ report(if (appDeclined) open(request.url) else true)
109
100
  }
110
101
  }
111
102
 
112
103
  /**
113
- * Opens a URL outside the WebView. Returns false when it could not be opened (the caller reports `block`): a page
114
- * controls the URL, so a malformed intent (bad syntax, launchFlags=zz), a refused activity or a `file:` URL (which
115
- * Android refuses to hand to another app) must not crash the app.
104
+ * Returns false when it could not be opened (the caller reports `block`): a page controls the URL, so a malformed
105
+ * intent (bad syntax, launchFlags=zz), a refused activity or a `file:` URL (which Android refuses to hand to another
106
+ * app) must not crash the app.
116
107
  */
117
108
  private fun open(url: String): Boolean {
118
109
  val intent = try {
@@ -149,28 +140,23 @@ internal class MinimalWebViewNavigation(
149
140
  return intent
150
141
  }
151
142
 
152
- // No app for the link: an intent may name a web fallback, as Chrome supports. It goes through the rules like any
153
- // other navigation. Otherwise nothing happens.
143
+ // No app for the link: an intent may name a web fallback, as Chrome supports.
154
144
  private fun openFallback(intent: Intent, url: String, error: ActivityNotFoundException): Boolean {
155
145
  val fallback = intent.getStringExtra("browser_fallback_url")?.takeIf { it.startsWith("https://") || it.startsWith("http://") }
156
146
  ?: return failed("no app opens $url", error)
157
147
  if (!decide(NavigationRules.Request(fallback, true, false, false))) webView.loadUrl(fallback)
158
- // Nothing opened externally: the intent is reported as blocked, the fallback by its own decision.
159
148
  return false
160
149
  }
161
150
 
162
- // Never a second WebView: a popup model is more than almost any app wants, so a throwaway one only catches the URL.
163
151
  fun createWindow(isUserGesture: Boolean, resultMsg: Message): Boolean {
164
152
  val child = WebView(owner.context)
165
- // It only catches a URL: none of the page's access, and no JS of its own.
166
153
  child.settings.allowFileAccess = false
167
154
  child.settings.allowContentAccess = false
168
155
  child.settings.javaScriptEnabled = false
169
- children += child
170
- // Finishes once, whichever comes first: the first URL, the timeout, a crash, the Document's end (documentEnded).
156
+ pendingWindows += child
171
157
  // Destroyed later: this may run inside the child's own callback.
172
158
  fun finish(): Boolean {
173
- val wasPending = children.remove(child)
159
+ val wasPending = pendingWindows.remove(child)
174
160
  if (wasPending) mainHandler.post { child.destroy() }
175
161
  return wasPending
176
162
  }
@@ -1,5 +1,6 @@
1
1
  package expo.modules.minimalwebview
2
2
 
3
+ import android.webkit.WebView
3
4
  import androidx.webkit.JavaScriptReplyProxy
4
5
  import androidx.webkit.ScriptHandler
5
6
  import androidx.webkit.WebMessageCompat
@@ -8,20 +9,14 @@ import androidx.webkit.WebViewFeature
8
9
  import expo.modules.kotlin.exception.CodedException
9
10
  import org.json.JSONArray
10
11
 
11
- /** Scripts in the page: the bridge transport, `injectedScripts` and `evaluate`. */
12
12
  internal class MinimalWebViewScripts(private val owner: MinimalWebView, private val onBridge: (Map<String, Any?>) -> Unit) {
13
13
  private val webView get() = owner.webView
14
14
 
15
- // Bridge: the page posts through `window.nativeBridgeTransport`; replies go to the main frame's latest proxy.
16
15
  private var replyProxy: JavaScriptReplyProxy? = null
17
16
  private var installedScripts: List<InjectedScript>? = null
18
17
  private val scriptHandlers = mutableListOf<ScriptHandler>()
19
18
  private val evaluations = Evaluations()
20
19
 
21
- /**
22
- * Installs everything into a new WebView, the first or the one after a crash. The evaluate channel and the bridge go
23
- * in only here: JS fixes `bridge` at mount.
24
- */
25
20
  fun install() {
26
21
  // After a crash they are the destroyed WebView's: removing them would call into it.
27
22
  scriptHandlers.clear()
@@ -38,18 +33,19 @@ internal class MinimalWebViewScripts(private val owner: MinimalWebView, private
38
33
  return
39
34
  }
40
35
  val origins = owner.bridgeOrigins.orEmpty().toSet()
41
- // A malformed origin rule makes WebView throw; createBridge validates them, so this only guards against misuse.
42
- // JS learns of it: calls reject with `unavailable`.
43
36
  try {
44
37
  WebViewCompat.addWebMessageListener(webView, "nativeBridgeTransport", origins) { _, message, sourceOrigin, isMainFrame, proxy ->
45
- // Main frame only, like iOS. The origin rules already filtered the sender.
46
38
  if (!isMainFrame) return@addWebMessageListener
47
- // An ArrayBuffer has no string data (`data` throws); iOS drops a non-string message too.
39
+ // An ArrayBuffer message has no string data: WebMessageCompat.getData throws for it.
48
40
  if (message.type != WebMessageCompat.TYPE_STRING) return@addWebMessageListener
49
- replyProxy = proxy
50
- onBridge(mapOf("message" to message.data, "origin" to sourceOrigin.toString()))
41
+ val data = message.data
42
+ val deliver = Runnable {
43
+ replyProxy = proxy
44
+ onBridge(mapOf("message" to data, "origin" to sourceOrigin.toString()))
45
+ }
46
+ // WebView before 119 calls this as the message arrives, ahead of the onPageStarted it posted at the commit.
47
+ if (webViewCallsListenersDirectly) mainHandler.postDelayed(deliver, this, 0) else deliver.run()
51
48
  }
52
- // Runs before the page's own scripts, after the transport object exists.
53
49
  WebViewCompat.addDocumentStartJavaScript(webView, script, origins)
54
50
  } catch (e: IllegalArgumentException) {
55
51
  failed("bridge not installed: invalid allowedOrigins $origins", e)
@@ -78,51 +74,36 @@ internal class MinimalWebViewScripts(private val owner: MinimalWebView, private
78
74
  replyProxy?.postMessage(message)
79
75
  }
80
76
 
81
- /**
82
- * The Document ended: its evaluations fail and its reply proxy is gone. JS queues bridge messages until the next
83
- * page is ready; at unmount it rejects what is in flight itself.
84
- */
85
77
  fun documentEnded(reason: DocumentEnd) {
86
78
  evaluations.failAll()
87
- // At a commit this runs one main-thread hop after Chromium's (the NavigationListener's executor posts it), and
88
- // relies on landing before the new page's first message sets replyProxy (the bridge suite's head-script call).
79
+ if (reason != DocumentEnd.COMMITTED) mainHandler.removeCallbacksAndMessages(this)
89
80
  replyProxy = null
90
81
  if (reason == DocumentEnd.COMMITTED && owner.bridgeScript != null) onBridge(mapOf("navigated" to true))
91
82
  if (reason == DocumentEnd.CRASHED && owner.bridgeScript != null) onBridge(mapOf("crashed" to true))
92
83
  }
93
84
 
94
- /**
95
- * `evaluate` results come back through one global in every frame (`*`, before the first document). A page can forge
96
- * them, as it can already shape any value its own world returns.
97
- */
98
85
  private fun installEvaluate() {
99
86
  if (!WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) return
100
87
  WebViewCompat.addWebMessageListener(webView, EVALUATE, setOf("*")) { _, message, _, isMainFrame, _ ->
101
- // As in installBridge: only string messages.
102
88
  if (message.type == WebMessageCompat.TYPE_STRING) evaluations.settle(message.data, isMainFrame)
103
89
  }
104
90
  }
105
91
 
106
- /**
107
- * The `evaluate` ref method. A new Document rejects what is still waiting: WebView drops the callback when the
108
- * document is replaced first.
109
- */
92
+ /** A new Document rejects what is still waiting: WebView drops the callback when the document is replaced first. */
110
93
  fun evaluate(script: String, onResult: (Result<String>) -> Unit) {
111
94
  if (!WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) {
112
95
  return onResult(failure("unavailable", "evaluate needs WEB_MESSAGE_LISTENER; update Android System WebView"))
113
96
  }
114
97
  val id = evaluations.add(onResult)
115
- // The script sits in a scope of its own (no wrapper names shadow the page's); the sync value is 1 once it started.
116
98
  val code = """typeof $EVALUATE === 'object' ? ((t, p) => (p.then(
117
99
  (v) => { try { v = JSON.stringify(v) } catch { v = null } t.postMessage(JSON.stringify([$id, v ?? 'null'])) },
118
100
  (e) => { try { e = String(e) } catch { e = 'Error' } t.postMessage(JSON.stringify([$id, null, e])) }
119
- ), 1))($EVALUATE, (async () => (
101
+ ), $STARTED))($EVALUATE, (async () => (
120
102
  $script
121
- ))()) : 0"""
103
+ ))()) : $NO_CHANNEL"""
122
104
  webView.evaluateJavascript(code) { value ->
123
- if (value == "1") return@evaluateJavascript
124
- // 0: the page has no channel (it loaded before the listener); null: the script didn't parse.
125
- evaluations.fail(id, if (value == "0") "no evaluate channel in this page" else "the script did not run (a syntax error?)")
105
+ if (value == STARTED) return@evaluateJavascript
106
+ evaluations.fail(id, if (value == NO_CHANNEL) "no evaluate channel in this page" else "the script did not run (a syntax error?)")
126
107
  }
127
108
  }
128
109
 
@@ -146,8 +127,7 @@ $script
146
127
  }
147
128
 
148
129
  /**
149
- * The `evaluate` calls waiting for their result, by id. Each settles once: by the page's reply, a script that didn't
150
- * run, or the Document's end. Main thread only.
130
+ * Each evaluation settles once: by the page's reply, a script that didn't run, or the Document's end. Main thread only.
151
131
  */
152
132
  internal class Evaluations {
153
133
  private val waiting = mutableMapOf<Int, (Result<String>) -> Unit>()
@@ -192,4 +172,12 @@ internal class EvaluateError(code: String, message: String) : CodedException(cod
192
172
 
193
173
  private fun failure(code: String, message: String) = Result.failure<String>(EvaluateError(code, message))
194
174
 
175
+ private val webViewCallsListenersDirectly by lazy {
176
+ val major = WebView.getCurrentWebViewPackage()?.versionName?.substringBefore('.')?.toIntOrNull()
177
+ major != null && major < FIRST_WEBVIEW_POSTING_LISTENER_CALLS
178
+ }
179
+
180
+ private const val FIRST_WEBVIEW_POSTING_LISTENER_CALLS = 119
195
181
  private const val EVALUATE = "nativeEvaluateResult"
182
+ private const val STARTED = "1"
183
+ private const val NO_CHANNEL = "0"
@@ -1,6 +1,5 @@
1
1
  package expo.modules.minimalwebview
2
2
 
3
- /** The structured navigation rules. Semantics and cases: src/__tests__/vectors/navigation-rules.json (shared with Swift). */
4
3
  internal object NavigationRules {
5
4
  data class Request(
6
5
  val url: String,
@@ -10,19 +9,20 @@ internal object NavigationRules {
10
9
  val isRedirect: Boolean = false
11
10
  )
12
11
 
13
- /** [action] is allow, block, external or ask; [rule] is the matching rule's index, null when a default decided. */
14
- data class Decision(val action: String, val rule: Int?)
12
+ enum class Action(val jsName: String) { ALLOW("allow"), BLOCK("block"), EXTERNAL("external"), ASK("ask") }
15
13
 
16
- /** Load in place without the rules. */
17
- private val internalSchemes = setOf("about", "data", "javascript")
14
+ /** [rule] is the index of the rule that decided, null when a default did. */
15
+ data class Decision(val action: Action, val rule: Int?)
16
+
17
+ private val schemesAllowedWithoutRules = setOf("about", "data", "javascript")
18
18
 
19
19
  /**
20
20
  * Never open as a new window, whatever the rules say: the core loads an allowed new window in the main frame itself,
21
21
  * past the engine's limits on what a page may navigate the top frame to.
22
22
  */
23
- private val noNewWindowSchemes = internalSchemes + setOf("blob", "file")
24
- private val actions = setOf("allow", "block", "external", "ask")
25
- private val answers = setOf("allow", "block", "external")
23
+ private val noNewWindowSchemes = schemesAllowedWithoutRules + setOf("blob", "file")
24
+
25
+ private fun actionOf(value: Any?) = Action.entries.find { it.jsName == value }
26
26
 
27
27
  /**
28
28
  * The rules' decision, gated for `ask`: blocked when nothing can answer it ([canAsk] false), allowed when its URL is
@@ -31,30 +31,29 @@ internal object NavigationRules {
31
31
  fun decide(rules: List<Map<String, Any?>>?, request: Request, asked: Set<String>, canAsk: Boolean): Decision {
32
32
  val decision = match(rules, request)
33
33
  return when {
34
- decision.action != "ask" -> decision
35
- !canAsk -> Decision("block", decision.rule)
36
- request.url in asked -> Decision("allow", decision.rule)
34
+ decision.action != Action.ASK -> decision
35
+ !canAsk -> Decision(Action.BLOCK, decision.rule)
36
+ request.url in asked -> Decision(Action.ALLOW, decision.rule)
37
37
  else -> decision
38
38
  }
39
39
  }
40
40
 
41
41
  /** An `ask` answer: allow, block or external; anything else (null on a timeout) blocks. */
42
- fun answer(value: Any?): String = (value as? String)?.takeIf { it in answers } ?: "block"
42
+ fun answer(value: Any?): Action = actionOf(value)?.takeIf { it != Action.ASK } ?: Action.BLOCK
43
43
 
44
44
  private fun match(rules: List<Map<String, Any?>>?, request: Request): Decision {
45
45
  val scheme = request.url.substringBefore(':', "").lowercase()
46
- if (request.newWindow && scheme in noNewWindowSchemes) return Decision("block", null)
47
- if (scheme in internalSchemes) return Decision("allow", null)
48
- // JS sends defaultNavigationRules when the prop is unset; no rules, null or empty, match nothing.
49
- if (rules.isNullOrEmpty()) return Decision("block", null)
46
+ if (request.newWindow && scheme in noNewWindowSchemes) return Decision(Action.BLOCK, null)
47
+ if (scheme in schemesAllowedWithoutRules) return Decision(Action.ALLOW, null)
48
+ if (rules.isNullOrEmpty()) return Decision(Action.BLOCK, null)
50
49
  val parts = (if (scheme == "blob") blobOrigin(request.url) else parts(scheme, request.url))
51
- ?: return Decision("block", null)
50
+ ?: return Decision(Action.BLOCK, null)
52
51
  val index = rules.indexOfFirst { matches(it, parts, request) }
53
- return if (index < 0) Decision("block", null) else Decision((rules[index]["action"] as? String)?.takeIf { it in actions } ?: "block", index)
52
+ return if (index < 0) Decision(Action.BLOCK, null) else Decision(actionOf(rules[index]["action"]) ?: Action.BLOCK, index)
54
53
  }
55
54
 
56
- // scheme ":" ["//" authority] path ["?" query]. java.net.URI rejects URLs Chromium accepts (a raw `|` in the query,
57
- // `_` in a host), so the parts are split with a regex.
55
+ // java.net.URI rejects URLs Chromium accepts (a raw `|` in the query, `_` in a host), so the parts are split with a
56
+ // regex.
58
57
  private val urlParts = Regex("^([a-zA-Z][a-zA-Z0-9+.-]*):(?://([^/?#]*))?([^?#]*)(?:\\?([^#]*))?")
59
58
 
60
59
  private data class Parts(val scheme: String, val host: String?, val path: String, val params: List<String>)