react-native-minimal-webview 1.2.1 → 1.3.1
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.
- package/android/build.gradle +1 -1
- package/android/src/main/java/expo/modules/minimalwebview/Asks.kt +5 -11
- package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +17 -11
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +67 -120
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +23 -32
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +8 -18
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +30 -49
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +48 -36
- package/android/src/main/java/expo/modules/minimalwebview/NavigationRules.kt +19 -20
- package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +30 -40
- package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +14 -18
- package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +12 -23
- package/android/src/main/java/expo/modules/minimalwebview/requests/FileUpload.kt +0 -1
- package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +1 -4
- package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +34 -24
- package/build/WebView.d.ts +8 -1
- package/build/WebView.d.ts.map +1 -1
- package/build/WebView.js +30 -80
- package/build/WebView.js.map +1 -1
- package/build/bridge/createBridge.d.ts +1 -5
- package/build/bridge/createBridge.d.ts.map +1 -1
- package/build/bridge/createBridge.js +3 -15
- package/build/bridge/createBridge.js.map +1 -1
- package/build/bridge/endpoint.d.ts +1 -2
- package/build/bridge/endpoint.d.ts.map +1 -1
- package/build/bridge/endpoint.js +5 -6
- package/build/bridge/endpoint.js.map +1 -1
- package/build/bridge/matchesOrigin.d.ts +11 -0
- package/build/bridge/matchesOrigin.d.ts.map +1 -0
- package/build/bridge/matchesOrigin.js +26 -0
- package/build/bridge/matchesOrigin.js.map +1 -0
- package/build/bridge/origins.d.ts +2 -13
- package/build/bridge/origins.d.ts.map +1 -1
- package/build/bridge/origins.js +1 -30
- package/build/bridge/origins.js.map +1 -1
- package/build/bridge/pageClient.generated.d.ts +1 -1
- package/build/bridge/pageClient.generated.d.ts.map +1 -1
- package/build/bridge/pageClient.generated.js +2 -2
- package/build/bridge/pageClient.generated.js.map +1 -1
- package/build/bridge/protocol.d.ts +3 -5
- package/build/bridge/protocol.d.ts.map +1 -1
- package/build/bridge/protocol.js +12 -14
- package/build/bridge/protocol.js.map +1 -1
- package/build/index.d.ts +1 -1
- package/build/index.js +1 -1
- package/build/navigationRules.d.ts +0 -5
- package/build/navigationRules.d.ts.map +1 -1
- package/build/navigationRules.js +3 -12
- package/build/navigationRules.js.map +1 -1
- package/build/reactNativeWebViewDefaults.d.ts +0 -4
- package/build/reactNativeWebViewDefaults.d.ts.map +1 -1
- package/build/reactNativeWebViewDefaults.js +0 -4
- package/build/reactNativeWebViewDefaults.js.map +1 -1
- package/build/reactNativeWebViewMessages.d.ts.map +1 -1
- package/build/reactNativeWebViewMessages.js +0 -1
- package/build/reactNativeWebViewMessages.js.map +1 -1
- package/build/refStore.d.ts +0 -2
- package/build/refStore.d.ts.map +1 -1
- package/build/refStore.js +0 -6
- package/build/refStore.js.map +1 -1
- package/build/types.d.ts +33 -16
- package/build/types.d.ts.map +1 -1
- package/ios/Asks.swift +6 -9
- package/ios/DelegateProxy.swift +6 -20
- package/ios/DownloadName.swift +0 -2
- package/ios/Downloads.swift +0 -2
- package/ios/Hooks.swift +6 -7
- package/ios/Loads.swift +37 -19
- package/ios/MinimalWebView+Dialogs.swift +2 -6
- package/ios/MinimalWebView+Navigation.swift +25 -57
- package/ios/MinimalWebView+Scripts.swift +4 -16
- package/ios/MinimalWebView.podspec +1 -2
- package/ios/MinimalWebView.swift +58 -144
- package/ios/MinimalWebViewModule.swift +1 -18
- package/ios/NavigationRules.swift +2 -9
- package/ios/OriginRules.swift +4 -13
- package/ios/PlatformSettings.swift +19 -38
- package/ios/ReadAccess.swift +0 -2
- package/ios/Records.swift +18 -0
- package/ios/Recovery.swift +2 -8
- package/ios/SharedCookies.swift +10 -25
- package/package.json +4 -4
- package/src/WebView.tsx +45 -95
- package/src/bridge/createBridge.ts +5 -20
- package/src/bridge/endpoint.ts +6 -9
- package/src/bridge/matchesOrigin.ts +27 -0
- package/src/bridge/origins.ts +2 -30
- package/src/bridge/pageClient.generated.ts +2 -2
- package/src/bridge/pageClient.ts +1 -7
- package/src/bridge/protocol.ts +16 -18
- package/src/index.ts +1 -1
- package/src/navigationRules.ts +6 -12
- package/src/reactNativeWebViewDefaults.ts +0 -4
- package/src/reactNativeWebViewMessages.ts +0 -1
- package/src/refStore.ts +0 -7
- package/src/types.ts +33 -16
|
@@ -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,22 @@ 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
|
-
//
|
|
58
|
-
|
|
59
|
-
if (navigation.didCommit() && !navigation.isSameDocument) owner.
|
|
51
|
+
// A dead renderer's WebView reports the navigation it cut off as not committed, before processGone fails it.
|
|
52
|
+
if (owner.rendererGone) return
|
|
53
|
+
if (navigation.didCommit() && !navigation.isSameDocument) owner.documents.end(DocumentEnd.COMMITTED)
|
|
60
54
|
if (navigation.didCommit()) owner.url = navigation.url
|
|
61
55
|
if (!navigation.isSameDocument) {
|
|
62
56
|
owner.pendingUrl = null
|
|
63
|
-
//
|
|
64
|
-
//
|
|
65
|
-
owner.
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
57
|
+
// Chromium's error page for an HTTP status (a 404 with an empty body) is the server's answer: "finished", as on
|
|
58
|
+
// iOS.
|
|
59
|
+
owner.settleOutcome(
|
|
60
|
+
when {
|
|
61
|
+
!navigation.didCommit() -> LoadOutcome.CANCELLED
|
|
62
|
+
navigation.didCommitErrorPage() && navigation.statusCode < 400 -> LoadOutcome.FAILED
|
|
63
|
+
else -> LoadOutcome.FINISHED
|
|
64
|
+
}
|
|
65
|
+
)
|
|
70
66
|
// A page restored from the back-forward cache (its Page, already loaded) gets no onPageLoadEvent again.
|
|
71
67
|
if (!navigation.didCommit() || navigation.page?.let { it in loadedPages } == true) owner.loadEnded()
|
|
72
68
|
}
|
|
@@ -87,16 +83,12 @@ private val BOOLEAN = java.lang.Boolean.TYPE
|
|
|
87
83
|
private val FLOAT = java.lang.Float.TYPE
|
|
88
84
|
|
|
89
85
|
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
86
|
private fun deciding(name: String, vararg types: Class<*>, lost: String? = null) =
|
|
92
87
|
owner.deciders.first(name, owner.clients, lost) { it.overrides(name, *types) }
|
|
93
88
|
|
|
94
|
-
/** Every hook client that overrides an observation callback, after the core. */
|
|
95
89
|
private inline fun observing(name: String, vararg types: Class<*>, block: (WebViewClient) -> Unit) =
|
|
96
90
|
owner.clients.forEach { if (it.overrides(name, *types)) block(it) }
|
|
97
91
|
|
|
98
|
-
// Without NavigationListener: the last main-frame URL allowed to load (a page's navigation or a redirect), for
|
|
99
|
-
// onReceivedSslError.
|
|
100
92
|
private var allowedMainFrameUrl: String? = null
|
|
101
93
|
|
|
102
94
|
// Not called for POST, the initial loadUrl, or reissued loads; called again for their redirects.
|
|
@@ -116,7 +108,8 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
|
|
|
116
108
|
// blocked redirect) gets no load events and no outcome here.
|
|
117
109
|
override fun onPageStarted(view: WebView, url: String?, favicon: Bitmap?) {
|
|
118
110
|
if (!owner.hasNavigationListener) {
|
|
119
|
-
owner.
|
|
111
|
+
owner.documents.end(DocumentEnd.COMMITTED)
|
|
112
|
+
if (url != null) owner.url = url
|
|
120
113
|
owner.loadStarted()
|
|
121
114
|
}
|
|
122
115
|
observing("onPageStarted", WEB_VIEW, STRING, Bitmap::class.java) { it.onPageStarted(view, url, favicon) }
|
|
@@ -124,7 +117,7 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
|
|
|
124
117
|
|
|
125
118
|
override fun onPageFinished(view: WebView, url: String?) {
|
|
126
119
|
if (!owner.hasNavigationListener) {
|
|
127
|
-
owner.
|
|
120
|
+
owner.settleOutcome(LoadOutcome.FINISHED)
|
|
128
121
|
owner.loadEnded()
|
|
129
122
|
}
|
|
130
123
|
observing("onPageFinished", WEB_VIEW, STRING) { it.onPageFinished(view, url) }
|
|
@@ -139,7 +132,6 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
|
|
|
139
132
|
override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? =
|
|
140
133
|
deciding("shouldInterceptRequest", WEB_VIEW, WebResourceRequest::class.java)?.shouldInterceptRequest(view, request)
|
|
141
134
|
|
|
142
|
-
// Main frame only: a subresource that fails to load (an ad) is the page's business.
|
|
143
135
|
override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) {
|
|
144
136
|
val description = error.description.toString()
|
|
145
137
|
if (request.isForMainFrame && !description.contains("ERR_ABORTED")) {
|
|
@@ -158,7 +150,6 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
|
|
|
158
150
|
if (hook != null) hook.onFormResubmission(view, dontResend, resend) else super.onFormResubmission(view, dontResend, resend)
|
|
159
151
|
}
|
|
160
152
|
|
|
161
|
-
// Without NavigationListener (WebView older than 146): best-effort URL tracking.
|
|
162
153
|
override fun doUpdateVisitedHistory(view: WebView, url: String?, isReload: Boolean) {
|
|
163
154
|
if (!owner.hasNavigationListener && url != null) {
|
|
164
155
|
owner.url = url
|
|
@@ -167,7 +158,6 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
|
|
|
167
158
|
observing("doUpdateVisitedHistory", WEB_VIEW, STRING, BOOLEAN) { it.doUpdateVisitedHistory(view, url, isReload) }
|
|
168
159
|
}
|
|
169
160
|
|
|
170
|
-
@SuppressLint("WebViewClientOnReceivedSslError") // because the core always cancels; it only reports the error
|
|
171
161
|
override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, sslError: SslError) {
|
|
172
162
|
val hook = deciding(
|
|
173
163
|
"onReceivedSslError", WEB_VIEW, SslErrorHandler::class.java, SslError::class.java,
|
|
@@ -175,8 +165,8 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
|
|
|
175
165
|
)
|
|
176
166
|
if (hook != null) return hook.onReceivedSslError(view, handler, sslError)
|
|
177
167
|
handler.cancel()
|
|
178
|
-
// Also called for subresources (an ad image): only the main frame's URL is a page error.
|
|
179
|
-
// there
|
|
168
|
+
// Also called for subresources (an ad image): only the main frame's URL is a page error.
|
|
169
|
+
// Without a NavigationListener there is no pendingUrl: WebView's url shows a loadUrl in progress.
|
|
180
170
|
val mainFrame = if (owner.hasNavigationListener) setOf(owner.pendingUrl ?: owner.url) else setOf(view.url, allowedMainFrameUrl)
|
|
181
171
|
if (sslError.url in mainFrame) {
|
|
182
172
|
owner.reportError("ssl", sslError.url, sslError.primaryError, "SSL error ${sslError.primaryError}")
|
|
@@ -188,7 +178,6 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
|
|
|
188
178
|
if (hook != null) hook.onReceivedClientCertRequest(view, request) else super.onReceivedClientCertRequest(view, request)
|
|
189
179
|
}
|
|
190
180
|
|
|
191
|
-
// Basic and digest auth: a hook client, else cancel (the page shows its 401).
|
|
192
181
|
override fun onReceivedHttpAuthRequest(view: WebView, handler: HttpAuthHandler, host: String, realm: String) {
|
|
193
182
|
val hook = deciding("onReceivedHttpAuthRequest", WEB_VIEW, HttpAuthHandler::class.java, STRING, STRING)
|
|
194
183
|
if (hook != null) hook.onReceivedHttpAuthRequest(view, handler, host, realm) else handler.cancel()
|
|
@@ -210,10 +199,13 @@ internal class Client(private val owner: MinimalWebView, private val navigation:
|
|
|
210
199
|
observing("onReceivedLoginRequest", WEB_VIEW, STRING, STRING, STRING) { it.onReceivedLoginRequest(view, realm, account, args) }
|
|
211
200
|
|
|
212
201
|
override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {
|
|
213
|
-
// Returning true keeps the app alive
|
|
202
|
+
// Returning true keeps the app alive.
|
|
214
203
|
// Timed here: every WebView on the renderer hears of its death back to back, before any recovery runs.
|
|
215
204
|
val at = SystemClock.elapsedRealtime()
|
|
216
|
-
if (view === owner.webView)
|
|
205
|
+
if (view === owner.webView) {
|
|
206
|
+
owner.rendererGone = true
|
|
207
|
+
mainHandler.post { owner.processGone(if (detail.didCrash()) "crash" else "memory", at) }
|
|
208
|
+
}
|
|
217
209
|
observing("onRenderProcessGone", WEB_VIEW, RenderProcessGoneDetail::class.java) { it.onRenderProcessGone(view, detail) }
|
|
218
210
|
return true
|
|
219
211
|
}
|
|
@@ -239,7 +231,7 @@ internal class ChromeClient(private val owner: MinimalWebView, private val navig
|
|
|
239
231
|
?: navigation.createWindow(isUserGesture, resultMsg)
|
|
240
232
|
|
|
241
233
|
override fun onShowFileChooser(view: WebView, callback: ValueCallback<Array<Uri>>, params: FileChooserParams): Boolean {
|
|
242
|
-
val once = owner.fileUpload.hold(callback)
|
|
234
|
+
val once = owner.fileUpload.hold(callback)
|
|
243
235
|
val hook = deciding(
|
|
244
236
|
"onShowFileChooser", WEB_VIEW, ValueCallback::class.java, FileChooserParams::class.java,
|
|
245
237
|
lost = "onFileRequest doesn't apply"
|
|
@@ -249,7 +241,6 @@ internal class ChromeClient(private val owner: MinimalWebView, private val navig
|
|
|
249
241
|
return true
|
|
250
242
|
}
|
|
251
243
|
|
|
252
|
-
// Without a hook client or the app's prop: deny (never grant device access by default).
|
|
253
244
|
override fun onPermissionRequest(request: PermissionRequest) {
|
|
254
245
|
val hook = deciding("onPermissionRequest", PermissionRequest::class.java, lost = "onPermissionRequest and the default deny don't apply")
|
|
255
246
|
when {
|
|
@@ -41,9 +41,9 @@ class MinimalWebViewModule : Module() {
|
|
|
41
41
|
private var chooserOpen = false
|
|
42
42
|
|
|
43
43
|
/**
|
|
44
|
-
* Opens the system file chooser
|
|
45
|
-
*
|
|
46
|
-
*
|
|
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
|
|
@@ -64,10 +64,11 @@ class MinimalWebViewModule : Module() {
|
|
|
64
64
|
override fun definition() = ModuleDefinition {
|
|
65
65
|
Name("MinimalWebView")
|
|
66
66
|
|
|
67
|
-
//
|
|
68
|
-
//
|
|
67
|
+
// Expo runs this again for each new activity and registers under a new key, so a chooser the destroyed activity
|
|
68
|
+
// launched never reports back. Its fallback gets only a result from before a process restart: nothing waits then.
|
|
69
69
|
RegisterActivityContracts {
|
|
70
|
-
|
|
70
|
+
chooserOpen = false
|
|
71
|
+
fileChooser = registerForActivityResult(FileChooserContract) { _, _ -> }
|
|
71
72
|
}
|
|
72
73
|
|
|
73
74
|
// Cookies live in memory until flushed; persist them before the process can be killed. Only once a WebView was
|
|
@@ -76,7 +77,6 @@ class MinimalWebViewModule : Module() {
|
|
|
76
77
|
if (webViewCreated) flushCookies()
|
|
77
78
|
}
|
|
78
79
|
|
|
79
|
-
// Best effort: an error only means the first WebView starts WebView as before.
|
|
80
80
|
Function("warmUp") { warmUp(appContext.reactContext ?: throw Exceptions.ReactContextLost()) }
|
|
81
81
|
|
|
82
82
|
// ProfileStore wants the UI thread, and starts WebView there.
|
|
@@ -96,7 +96,6 @@ class MinimalWebViewModule : Module() {
|
|
|
96
96
|
Prop("bridgeScript") { view: MinimalWebView, script: String? -> view.bridgeScript = script }
|
|
97
97
|
Prop("bridgeOrigins") { view: MinimalWebView, origins: List<String>? -> view.bridgeOrigins = origins }
|
|
98
98
|
Prop("hookOptions") { view: MinimalWebView, options: Map<String, Any?>? -> view.hookOptions = options.orEmpty() }
|
|
99
|
-
// The JSON is always an object (JS builds it).
|
|
100
99
|
Prop("settings") { view: MinimalWebView, json: String? -> view.settings = json?.let { JSONObject(it).toMap() } }
|
|
101
100
|
Prop("pullToRefresh") { view: MinimalWebView, value: Boolean? -> view.pullToRefresh = value ?: false }
|
|
102
101
|
Prop("injectedScripts") { view: MinimalWebView, value: List<InjectedScript>? -> view.injectedScripts = value }
|
|
@@ -117,7 +116,6 @@ class MinimalWebViewModule : Module() {
|
|
|
117
116
|
native(view, promise) {
|
|
118
117
|
view.platformSettings.call(path, fromJson(JSONArray(argsJson)) as List<Any?>) { json -> native(view, promise) { promise.resolve(json()) } }
|
|
119
118
|
}
|
|
120
|
-
// A call can change what the state shows (clearHistory, canGoBack); an unchanged state isn't sent.
|
|
121
119
|
view.stateChanged()
|
|
122
120
|
}.runOnQueue(Queues.MAIN)
|
|
123
121
|
AsyncFunction("bridgePost") { view: MinimalWebView, message: String -> view.scripts.post(message) }.runOnQueue(Queues.MAIN)
|
|
@@ -145,10 +143,6 @@ private fun preconnect(url: String) {
|
|
|
145
143
|
}
|
|
146
144
|
}
|
|
147
145
|
|
|
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
146
|
private fun flushCookies() {
|
|
153
147
|
CookieManager.getInstance().flush()
|
|
154
148
|
if (!WebViewFeature.isFeatureSupported(WebViewFeature.MULTI_PROFILE)) return
|
|
@@ -183,7 +177,6 @@ private fun warmUp(context: Context) {
|
|
|
183
177
|
WebViewCompat.startUpWebView(context, config, outcome)
|
|
184
178
|
}
|
|
185
179
|
|
|
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
180
|
private fun live(view: MinimalWebView, action: (WebView) -> Unit) {
|
|
188
181
|
if (!view.recovering) action(view.webView)
|
|
189
182
|
}
|
|
@@ -228,7 +221,7 @@ private fun fromJson(value: Any?): Any? = when (value) {
|
|
|
228
221
|
else -> value
|
|
229
222
|
}
|
|
230
223
|
|
|
231
|
-
/**
|
|
224
|
+
/** Serializable because the registry persists launch inputs; it never relaunches a restored one. */
|
|
232
225
|
private class ChooserIntent(@Transient val intent: Intent? = null) : Serializable
|
|
233
226
|
|
|
234
227
|
private object FileChooserContract : AppContextActivityResultContract<ChooserIntent, Array<Uri>?> {
|
|
@@ -238,13 +231,10 @@ private object FileChooserContract : AppContextActivityResultContract<ChooserInt
|
|
|
238
231
|
FileChooserParams.parseResult(resultCode, intent)
|
|
239
232
|
}
|
|
240
233
|
|
|
241
|
-
// Data classes, so the skip checks in applyProps compare them with ==. Every field is optional, as on iOS.
|
|
242
|
-
|
|
243
234
|
internal data class WebViewSource(
|
|
244
235
|
@Field val uri: String? = null,
|
|
245
236
|
@Field val headers: Map<String, String>? = null,
|
|
246
237
|
@Field val body: String? = null,
|
|
247
|
-
// Unused on Android: here so that a change loads the source again, as on iOS.
|
|
248
238
|
@Field val readAccessRoot: String? = null,
|
|
249
239
|
@Field val html: String? = null,
|
|
250
240
|
@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
|
-
|
|
26
|
-
private val children = mutableSetOf<WebView>()
|
|
23
|
+
private val pendingWindows = mutableSetOf<WebView>()
|
|
27
24
|
|
|
28
25
|
fun documentEnded() {
|
|
29
26
|
askedAndAllowed.clear()
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
children.clear()
|
|
27
|
+
val ended = pendingWindows.toList()
|
|
28
|
+
pendingWindows.clear()
|
|
33
29
|
ended.forEach { it.destroy() }
|
|
34
30
|
}
|
|
35
31
|
|
|
@@ -37,23 +33,18 @@ 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
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
}
|
|
51
|
-
if (action == "external") {
|
|
52
|
-
openExternal(request, decision.rule)
|
|
53
|
-
return true
|
|
36
|
+
when (decision.action) {
|
|
37
|
+
NavigationRules.Action.ASK -> if (request.mainFrame) {
|
|
38
|
+
ask(request, decision.rule)
|
|
39
|
+
} else {
|
|
40
|
+
// loadUrl reissues only a main-frame navigation.
|
|
41
|
+
Log.w(TAG, "`ask` only works for main-frame navigations on Android; blocked ${request.url}")
|
|
42
|
+
notifyNavigation(request, NavigationRules.Action.BLOCK, decision.rule)
|
|
43
|
+
}
|
|
44
|
+
NavigationRules.Action.EXTERNAL -> openExternal(request, decision.rule)
|
|
45
|
+
else -> notifyNavigation(request, decision.action, decision.rule)
|
|
54
46
|
}
|
|
55
|
-
|
|
56
|
-
return action != "allow"
|
|
47
|
+
return decision.action != NavigationRules.Action.ALLOW
|
|
57
48
|
}
|
|
58
49
|
|
|
59
50
|
private fun fields(request: NavigationRules.Request) = mapOf(
|
|
@@ -63,23 +54,21 @@ internal class MinimalWebViewNavigation(
|
|
|
63
54
|
"userInitiated" to request.userInitiated
|
|
64
55
|
)
|
|
65
56
|
|
|
66
|
-
private fun notifyNavigation(request: NavigationRules.Request, action:
|
|
67
|
-
if ("onNavigation" in owner.requestHandlers) onNavigation(fields(request) + mapOf("action" to action, "rule" to rule))
|
|
57
|
+
private fun notifyNavigation(request: NavigationRules.Request, action: NavigationRules.Action, rule: Int?) {
|
|
58
|
+
if ("onNavigation" in owner.requestHandlers) onNavigation(fields(request) + mapOf("action" to action.jsName, "rule" to rule))
|
|
68
59
|
}
|
|
69
60
|
|
|
70
|
-
// Cancel now, ask JS, reissue on allow; the redirect chain is lost.
|
|
71
61
|
private fun ask(request: NavigationRules.Request, rule: Int?) {
|
|
72
62
|
val referrer = webView.url
|
|
73
63
|
val id = owner.asks.ask("core", "onNavigationRequest", fields(request)) { answer ->
|
|
74
64
|
val action = NavigationRules.answer(answer)
|
|
75
|
-
if (action ==
|
|
65
|
+
if (action == NavigationRules.Action.ALLOW) {
|
|
76
66
|
askedAndAllowed += request.url
|
|
77
67
|
reissue(request.url, referrer)
|
|
78
68
|
}
|
|
79
|
-
if (action ==
|
|
69
|
+
if (action == NavigationRules.Action.EXTERNAL) openExternal(request, rule) else notifyNavigation(request, action, rule)
|
|
80
70
|
}
|
|
81
|
-
|
|
82
|
-
mainHandler.postDelayed({ owner.asks.cancel(id) }, ASK_TIMEOUT_MS)
|
|
71
|
+
if (id != null) mainHandler.postDelayed({ owner.asks.cancel(id) }, ASK_TIMEOUT_MS)
|
|
83
72
|
}
|
|
84
73
|
|
|
85
74
|
// WebView's request headers on a navigation are empty, so the page's URL goes as the Referer, trimmed by WebView's
|
|
@@ -87,7 +76,6 @@ internal class MinimalWebViewNavigation(
|
|
|
87
76
|
// reissued URL isn't asked again (its redirects still go to decide).
|
|
88
77
|
private fun reissue(url: String, referrer: String?) = webView.loadUrl(url, referrer?.let { mapOf("Referer" to it) }.orEmpty())
|
|
89
78
|
|
|
90
|
-
/** A download no `onDownload` takes. */
|
|
91
79
|
fun openDownload(url: String) {
|
|
92
80
|
if (url.startsWith("http:") || url.startsWith("https:")) {
|
|
93
81
|
openExternal(NavigationRules.Request(url, true, false, false), null)
|
|
@@ -96,23 +84,21 @@ internal class MinimalWebViewNavigation(
|
|
|
96
84
|
}
|
|
97
85
|
}
|
|
98
86
|
|
|
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
87
|
private fun openExternal(request: NavigationRules.Request, rule: Int?) {
|
|
104
|
-
val report = { opened: Boolean ->
|
|
88
|
+
val report = { opened: Boolean ->
|
|
89
|
+
notifyNavigation(request, if (opened) NavigationRules.Action.EXTERNAL else NavigationRules.Action.BLOCK, rule)
|
|
90
|
+
}
|
|
105
91
|
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
92
|
owner.asks.ask("core", "onOpenExternal", fields(request)) { answer ->
|
|
108
|
-
|
|
93
|
+
val appDeclined = answer == false
|
|
94
|
+
report(if (appDeclined) open(request.url) else true)
|
|
109
95
|
}
|
|
110
96
|
}
|
|
111
97
|
|
|
112
98
|
/**
|
|
113
|
-
*
|
|
114
|
-
*
|
|
115
|
-
*
|
|
99
|
+
* Returns false when it could not be opened (the caller reports `block`): a page controls the URL, so a malformed
|
|
100
|
+
* intent (bad syntax, launchFlags=zz), a refused activity or a `file:` URL (which Android refuses to hand to another
|
|
101
|
+
* app) must not crash the app.
|
|
116
102
|
*/
|
|
117
103
|
private fun open(url: String): Boolean {
|
|
118
104
|
val intent = try {
|
|
@@ -149,28 +135,23 @@ internal class MinimalWebViewNavigation(
|
|
|
149
135
|
return intent
|
|
150
136
|
}
|
|
151
137
|
|
|
152
|
-
// No app for the link: an intent may name a web fallback, as Chrome supports.
|
|
153
|
-
// other navigation. Otherwise nothing happens.
|
|
138
|
+
// No app for the link: an intent may name a web fallback, as Chrome supports.
|
|
154
139
|
private fun openFallback(intent: Intent, url: String, error: ActivityNotFoundException): Boolean {
|
|
155
140
|
val fallback = intent.getStringExtra("browser_fallback_url")?.takeIf { it.startsWith("https://") || it.startsWith("http://") }
|
|
156
141
|
?: return failed("no app opens $url", error)
|
|
157
142
|
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
143
|
return false
|
|
160
144
|
}
|
|
161
145
|
|
|
162
|
-
// Never a second WebView: a popup model is more than almost any app wants, so a throwaway one only catches the URL.
|
|
163
146
|
fun createWindow(isUserGesture: Boolean, resultMsg: Message): Boolean {
|
|
164
147
|
val child = WebView(owner.context)
|
|
165
|
-
// It only catches a URL: none of the page's access, and no JS of its own.
|
|
166
148
|
child.settings.allowFileAccess = false
|
|
167
149
|
child.settings.allowContentAccess = false
|
|
168
150
|
child.settings.javaScriptEnabled = false
|
|
169
|
-
|
|
170
|
-
// Finishes once, whichever comes first: the first URL, the timeout, a crash, the Document's end (documentEnded).
|
|
151
|
+
pendingWindows += child
|
|
171
152
|
// Destroyed later: this may run inside the child's own callback.
|
|
172
153
|
fun finish(): Boolean {
|
|
173
|
-
val wasPending =
|
|
154
|
+
val wasPending = pendingWindows.remove(child)
|
|
174
155
|
if (wasPending) mainHandler.post { child.destroy() }
|
|
175
156
|
return wasPending
|
|
176
157
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
package expo.modules.minimalwebview
|
|
2
2
|
|
|
3
|
+
import android.webkit.WebSettings
|
|
3
4
|
import androidx.webkit.JavaScriptReplyProxy
|
|
4
5
|
import androidx.webkit.ScriptHandler
|
|
5
6
|
import androidx.webkit.WebMessageCompat
|
|
@@ -8,28 +9,32 @@ 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()
|
|
19
|
+
private val webViewCallsListenersDirectly by lazy { callsListenersDirectly(WebSettings.getDefaultUserAgent(owner.context)) }
|
|
20
20
|
|
|
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
21
|
fun install() {
|
|
26
22
|
// After a crash they are the destroyed WebView's: removing them would call into it.
|
|
27
23
|
scriptHandlers.clear()
|
|
28
24
|
installEvaluate()
|
|
25
|
+
installFrameHistory()
|
|
29
26
|
installBridge()
|
|
30
27
|
update(force = true)
|
|
31
28
|
}
|
|
32
29
|
|
|
30
|
+
// WebView reports no iframe navigation, though its history entries change canGoBack and canGoForward.
|
|
31
|
+
private fun installFrameHistory() {
|
|
32
|
+
val features = listOf(WebViewFeature.WEB_MESSAGE_LISTENER, WebViewFeature.DOCUMENT_START_SCRIPT)
|
|
33
|
+
if (!features.all(WebViewFeature::isFeatureSupported)) return
|
|
34
|
+
WebViewCompat.addWebMessageListener(webView, FRAME_NAVIGATED, setOf("*")) { _, _, _, _, _ -> owner.stateChanged() }
|
|
35
|
+
WebViewCompat.addDocumentStartJavaScript(webView, FRAME_NAVIGATED_SCRIPT, setOf("*"))
|
|
36
|
+
}
|
|
37
|
+
|
|
33
38
|
private fun installBridge() {
|
|
34
39
|
val script = owner.bridgeScript ?: return
|
|
35
40
|
val bridgeFeatures = listOf(WebViewFeature.WEB_MESSAGE_LISTENER, WebViewFeature.DOCUMENT_START_SCRIPT)
|
|
@@ -38,18 +43,19 @@ internal class MinimalWebViewScripts(private val owner: MinimalWebView, private
|
|
|
38
43
|
return
|
|
39
44
|
}
|
|
40
45
|
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
46
|
try {
|
|
44
47
|
WebViewCompat.addWebMessageListener(webView, "nativeBridgeTransport", origins) { _, message, sourceOrigin, isMainFrame, proxy ->
|
|
45
|
-
// Main frame only, like iOS. The origin rules already filtered the sender.
|
|
46
48
|
if (!isMainFrame) return@addWebMessageListener
|
|
47
|
-
// An ArrayBuffer has no string data
|
|
49
|
+
// An ArrayBuffer message has no string data: WebMessageCompat.getData throws for it.
|
|
48
50
|
if (message.type != WebMessageCompat.TYPE_STRING) return@addWebMessageListener
|
|
49
|
-
|
|
50
|
-
|
|
51
|
+
val data = message.data
|
|
52
|
+
val deliver = Runnable {
|
|
53
|
+
replyProxy = proxy
|
|
54
|
+
onBridge(mapOf("message" to data, "origin" to sourceOrigin.toString()))
|
|
55
|
+
}
|
|
56
|
+
// Chromium before 119 calls this as the message arrives, ahead of the onPageStarted it posted at the commit.
|
|
57
|
+
if (webViewCallsListenersDirectly) mainHandler.postDelayed(deliver, this, 0) else deliver.run()
|
|
51
58
|
}
|
|
52
|
-
// Runs before the page's own scripts, after the transport object exists.
|
|
53
59
|
WebViewCompat.addDocumentStartJavaScript(webView, script, origins)
|
|
54
60
|
} catch (e: IllegalArgumentException) {
|
|
55
61
|
failed("bridge not installed: invalid allowedOrigins $origins", e)
|
|
@@ -78,51 +84,36 @@ internal class MinimalWebViewScripts(private val owner: MinimalWebView, private
|
|
|
78
84
|
replyProxy?.postMessage(message)
|
|
79
85
|
}
|
|
80
86
|
|
|
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
87
|
fun documentEnded(reason: DocumentEnd) {
|
|
86
88
|
evaluations.failAll()
|
|
87
|
-
|
|
88
|
-
// relies on landing before the new page's first message sets replyProxy (the bridge suite's head-script call).
|
|
89
|
+
if (reason != DocumentEnd.COMMITTED) mainHandler.removeCallbacksAndMessages(this)
|
|
89
90
|
replyProxy = null
|
|
90
91
|
if (reason == DocumentEnd.COMMITTED && owner.bridgeScript != null) onBridge(mapOf("navigated" to true))
|
|
91
92
|
if (reason == DocumentEnd.CRASHED && owner.bridgeScript != null) onBridge(mapOf("crashed" to true))
|
|
92
93
|
}
|
|
93
94
|
|
|
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
95
|
private fun installEvaluate() {
|
|
99
96
|
if (!WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) return
|
|
100
97
|
WebViewCompat.addWebMessageListener(webView, EVALUATE, setOf("*")) { _, message, _, isMainFrame, _ ->
|
|
101
|
-
// As in installBridge: only string messages.
|
|
102
98
|
if (message.type == WebMessageCompat.TYPE_STRING) evaluations.settle(message.data, isMainFrame)
|
|
103
99
|
}
|
|
104
100
|
}
|
|
105
101
|
|
|
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
|
-
*/
|
|
102
|
+
/** A new Document rejects what is still waiting: WebView drops the callback when the document is replaced first. */
|
|
110
103
|
fun evaluate(script: String, onResult: (Result<String>) -> Unit) {
|
|
111
104
|
if (!WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) {
|
|
112
105
|
return onResult(failure("unavailable", "evaluate needs WEB_MESSAGE_LISTENER; update Android System WebView"))
|
|
113
106
|
}
|
|
114
107
|
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
108
|
val code = """typeof $EVALUATE === 'object' ? ((t, p) => (p.then(
|
|
117
109
|
(v) => { try { v = JSON.stringify(v) } catch { v = null } t.postMessage(JSON.stringify([$id, v ?? 'null'])) },
|
|
118
110
|
(e) => { try { e = String(e) } catch { e = 'Error' } t.postMessage(JSON.stringify([$id, null, e])) }
|
|
119
|
-
),
|
|
111
|
+
), $STARTED))($EVALUATE, (async () => (
|
|
120
112
|
$script
|
|
121
|
-
))()) :
|
|
113
|
+
))()) : $NO_CHANNEL"""
|
|
122
114
|
webView.evaluateJavascript(code) { value ->
|
|
123
|
-
if (value ==
|
|
124
|
-
|
|
125
|
-
evaluations.fail(id, if (value == "0") "no evaluate channel in this page" else "the script did not run (a syntax error?)")
|
|
115
|
+
if (value == STARTED) return@evaluateJavascript
|
|
116
|
+
evaluations.fail(id, if (value == NO_CHANNEL) "no evaluate channel in this page" else "the script did not run (a syntax error?)")
|
|
126
117
|
}
|
|
127
118
|
}
|
|
128
119
|
|
|
@@ -146,8 +137,7 @@ $script
|
|
|
146
137
|
}
|
|
147
138
|
|
|
148
139
|
/**
|
|
149
|
-
*
|
|
150
|
-
* run, or the Document's end. Main thread only.
|
|
140
|
+
* Each evaluation settles once: by the page's reply, a script that didn't run, or the Document's end. Main thread only.
|
|
151
141
|
*/
|
|
152
142
|
internal class Evaluations {
|
|
153
143
|
private val waiting = mutableMapOf<Int, (Result<String>) -> Unit>()
|
|
@@ -192,4 +182,26 @@ internal class EvaluateError(code: String, message: String) : CodedException(cod
|
|
|
192
182
|
|
|
193
183
|
private fun failure(code: String, message: String) = Result.failure<String>(EvaluateError(code, message))
|
|
194
184
|
|
|
185
|
+
/**
|
|
186
|
+
* Whether the WebView whose default user agent is [defaultUserAgent] calls web message listeners as the message
|
|
187
|
+
* arrives: Chromium before 119 does. Its `Chrome/` token names the Chromium base; a vendor's WebView package (Huawei's
|
|
188
|
+
* is 11.x to 15.x) numbers itself apart from it.
|
|
189
|
+
*/
|
|
190
|
+
internal fun callsListenersDirectly(defaultUserAgent: String?): Boolean {
|
|
191
|
+
val major = defaultUserAgent?.let { CHROME_MAJOR.find(it) }?.groupValues?.get(1)?.toIntOrNull()
|
|
192
|
+
return major != null && major < FIRST_CHROMIUM_POSTING_LISTENER_CALLS
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
private val CHROME_MAJOR = Regex("""Chrome/(\d+)""")
|
|
196
|
+
private const val FIRST_CHROMIUM_POSTING_LISTENER_CALLS = 119
|
|
195
197
|
private const val EVALUATE = "nativeEvaluateResult"
|
|
198
|
+
private const val FRAME_NAVIGATED = "nativeFrameNavigated"
|
|
199
|
+
|
|
200
|
+
// A new document, then each same-document navigation (Navigation API, WebView 102 and later).
|
|
201
|
+
private const val FRAME_NAVIGATED_SCRIPT = """if (window !== window.top) {
|
|
202
|
+
const navigated = () => $FRAME_NAVIGATED.postMessage('');
|
|
203
|
+
navigated();
|
|
204
|
+
window.navigation?.addEventListener('currententrychange', navigated);
|
|
205
|
+
}"""
|
|
206
|
+
private const val STARTED = "1"
|
|
207
|
+
private const val NO_CHANNEL = "0"
|