react-native-minimal-webview 1.2.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -31
- 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 +83 -125
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +16 -31
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +18 -19
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +24 -38
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +24 -36
- package/android/src/main/java/expo/modules/minimalwebview/NavigationRules.kt +19 -20
- package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +41 -37
- 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 +11 -2
- package/build/WebView.d.ts.map +1 -1
- package/build/WebView.js +45 -71
- 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 +55 -39
- package/build/types.d.ts.map +1 -1
- package/ios/Asks.swift +6 -9
- package/ios/DelegateProxy.swift +4 -18
- package/ios/DownloadName.swift +0 -2
- package/ios/Downloads.swift +0 -2
- package/ios/Hooks.swift +4 -6
- package/ios/Loads.swift +37 -19
- package/ios/MinimalWebView+Dialogs.swift +5 -7
- package/ios/MinimalWebView+Navigation.swift +23 -49
- package/ios/MinimalWebView+Scripts.swift +10 -17
- package/ios/MinimalWebView.podspec +1 -2
- package/ios/MinimalWebView.swift +63 -128
- package/ios/MinimalWebViewModule.swift +1 -18
- package/ios/NavigationRules.swift +2 -9
- package/ios/OriginRules.swift +4 -13
- package/ios/PlatformSettings.swift +9 -30
- 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/mocks/MinimalWebView.ts +5 -0
- package/package.json +11 -10
- package/src/WebView.tsx +58 -80
- 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 +55 -39
|
@@ -3,6 +3,7 @@ package expo.modules.minimalwebview
|
|
|
3
3
|
import android.content.Context
|
|
4
4
|
import android.content.Intent
|
|
5
5
|
import android.net.Uri
|
|
6
|
+
import android.util.AndroidRuntimeException
|
|
6
7
|
import android.util.Log
|
|
7
8
|
import android.webkit.CookieManager
|
|
8
9
|
import android.webkit.WebChromeClient.FileChooserParams
|
|
@@ -40,9 +41,9 @@ class MinimalWebViewModule : Module() {
|
|
|
40
41
|
private var chooserOpen = false
|
|
41
42
|
|
|
42
43
|
/**
|
|
43
|
-
* Opens the system file chooser
|
|
44
|
-
*
|
|
45
|
-
*
|
|
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.
|
|
46
47
|
*/
|
|
47
48
|
internal fun openFileChooser(intent: Intent, onResult: (Array<Uri>?) -> Unit) {
|
|
48
49
|
val launcher = fileChooser
|
|
@@ -64,7 +65,6 @@ class MinimalWebViewModule : Module() {
|
|
|
64
65
|
Name("MinimalWebView")
|
|
65
66
|
|
|
66
67
|
// The fallback runs when the result reaches a recreated activity: the WebView that asked is gone.
|
|
67
|
-
// shortcut: choosers stay cancelled after an activity dies without a result, track the request if apps hit it
|
|
68
68
|
RegisterActivityContracts {
|
|
69
69
|
fileChooser = registerForActivityResult(FileChooserContract) { _, _ -> chooserOpen = false }
|
|
70
70
|
}
|
|
@@ -75,7 +75,6 @@ class MinimalWebViewModule : Module() {
|
|
|
75
75
|
if (webViewCreated) flushCookies()
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
-
// Best effort: an error only means the first WebView starts WebView as before.
|
|
79
78
|
Function("warmUp") { warmUp(appContext.reactContext ?: throw Exceptions.ReactContextLost()) }
|
|
80
79
|
|
|
81
80
|
// ProfileStore wants the UI thread, and starts WebView there.
|
|
@@ -95,7 +94,6 @@ class MinimalWebViewModule : Module() {
|
|
|
95
94
|
Prop("bridgeScript") { view: MinimalWebView, script: String? -> view.bridgeScript = script }
|
|
96
95
|
Prop("bridgeOrigins") { view: MinimalWebView, origins: List<String>? -> view.bridgeOrigins = origins }
|
|
97
96
|
Prop("hookOptions") { view: MinimalWebView, options: Map<String, Any?>? -> view.hookOptions = options.orEmpty() }
|
|
98
|
-
// The JSON is always an object (JS builds it).
|
|
99
97
|
Prop("settings") { view: MinimalWebView, json: String? -> view.settings = json?.let { JSONObject(it).toMap() } }
|
|
100
98
|
Prop("pullToRefresh") { view: MinimalWebView, value: Boolean? -> view.pullToRefresh = value ?: false }
|
|
101
99
|
Prop("injectedScripts") { view: MinimalWebView, value: List<InjectedScript>? -> view.injectedScripts = value }
|
|
@@ -116,7 +114,6 @@ class MinimalWebViewModule : Module() {
|
|
|
116
114
|
native(view, promise) {
|
|
117
115
|
view.platformSettings.call(path, fromJson(JSONArray(argsJson)) as List<Any?>) { json -> native(view, promise) { promise.resolve(json()) } }
|
|
118
116
|
}
|
|
119
|
-
// A call can change what the state shows (clearHistory, canGoBack); an unchanged state isn't sent.
|
|
120
117
|
view.stateChanged()
|
|
121
118
|
}.runOnQueue(Queues.MAIN)
|
|
122
119
|
AsyncFunction("bridgePost") { view: MinimalWebView, message: String -> view.scripts.post(message) }.runOnQueue(Queues.MAIN)
|
|
@@ -144,10 +141,6 @@ private fun preconnect(url: String) {
|
|
|
144
141
|
}
|
|
145
142
|
}
|
|
146
143
|
|
|
147
|
-
/**
|
|
148
|
-
* Writes the cookies of the default profile and every other one to disk: a WebView on another `android.webView.profile`
|
|
149
|
-
* keeps its own.
|
|
150
|
-
*/
|
|
151
144
|
private fun flushCookies() {
|
|
152
145
|
CookieManager.getInstance().flush()
|
|
153
146
|
if (!WebViewFeature.isFeatureSupported(WebViewFeature.MULTI_PROFILE)) return
|
|
@@ -162,17 +155,26 @@ private fun setWebContentsDebugging(enabled: Boolean) {
|
|
|
162
155
|
}
|
|
163
156
|
|
|
164
157
|
private fun warmUp(context: Context) {
|
|
165
|
-
val
|
|
166
|
-
WebViewCompat.startUpWebView(context, config, object : WebViewOutcomeReceiver<WebViewStartUpResult, WebViewStartupException> {
|
|
158
|
+
val outcome = object : WebViewOutcomeReceiver<WebViewStartUpResult, WebViewStartupException> {
|
|
167
159
|
override fun onResult(result: WebViewStartUpResult) = Unit
|
|
168
160
|
|
|
169
161
|
override fun onError(error: WebViewStartupException) {
|
|
170
162
|
Log.w(TAG, "WebView warm-up failed", error)
|
|
171
163
|
}
|
|
172
|
-
}
|
|
164
|
+
}
|
|
165
|
+
// startUpWebView doesn't catch its task's throw, which on this thread would crash the app without a WebView provider.
|
|
166
|
+
val config = WebViewStartUpConfig.Builder { task ->
|
|
167
|
+
Thread({
|
|
168
|
+
try {
|
|
169
|
+
task.run()
|
|
170
|
+
} catch (e: AndroidRuntimeException) {
|
|
171
|
+
outcome.onError(WebViewStartupException("no WebView provider").apply { initCause(e) })
|
|
172
|
+
}
|
|
173
|
+
}, "WebViewWarmUp").start()
|
|
174
|
+
}.build()
|
|
175
|
+
WebViewCompat.startUpWebView(context, config, outcome)
|
|
173
176
|
}
|
|
174
177
|
|
|
175
|
-
/** Runs [action] on the WebView, unless it's recovering: `webView` is then the destroyed one, and only reload acts, by building the new one. */
|
|
176
178
|
private fun live(view: MinimalWebView, action: (WebView) -> Unit) {
|
|
177
179
|
if (!view.recovering) action(view.webView)
|
|
178
180
|
}
|
|
@@ -217,7 +219,7 @@ private fun fromJson(value: Any?): Any? = when (value) {
|
|
|
217
219
|
else -> value
|
|
218
220
|
}
|
|
219
221
|
|
|
220
|
-
/**
|
|
222
|
+
/** Serializable because the registry persists launch inputs; it never relaunches a restored one. */
|
|
221
223
|
private class ChooserIntent(@Transient val intent: Intent? = null) : Serializable
|
|
222
224
|
|
|
223
225
|
private object FileChooserContract : AppContextActivityResultContract<ChooserIntent, Array<Uri>?> {
|
|
@@ -227,13 +229,10 @@ private object FileChooserContract : AppContextActivityResultContract<ChooserInt
|
|
|
227
229
|
FileChooserParams.parseResult(resultCode, intent)
|
|
228
230
|
}
|
|
229
231
|
|
|
230
|
-
// Data classes, so the skip checks in applyProps compare them with ==. Every field is optional, as on iOS.
|
|
231
|
-
|
|
232
232
|
internal data class WebViewSource(
|
|
233
233
|
@Field val uri: String? = null,
|
|
234
234
|
@Field val headers: Map<String, String>? = null,
|
|
235
235
|
@Field val body: String? = null,
|
|
236
|
-
// Unused on Android: here so that a change loads the source again, as on iOS.
|
|
237
236
|
@Field val readAccessRoot: String? = null,
|
|
238
237
|
@Field val html: String? = null,
|
|
239
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
|
-
|
|
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,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 ==
|
|
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
|
-
|
|
39
|
+
NavigationRules.Action.BLOCK
|
|
44
40
|
} else {
|
|
45
41
|
decision.action
|
|
46
42
|
}
|
|
47
|
-
if (action ==
|
|
43
|
+
if (action == NavigationRules.Action.ASK) {
|
|
48
44
|
ask(request, decision.rule)
|
|
49
45
|
return true
|
|
50
46
|
}
|
|
51
|
-
if (action ==
|
|
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 !=
|
|
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:
|
|
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 ==
|
|
70
|
+
if (action == NavigationRules.Action.ALLOW) {
|
|
76
71
|
askedAndAllowed += request.url
|
|
77
72
|
reissue(request.url, referrer)
|
|
78
73
|
}
|
|
79
|
-
if (action ==
|
|
74
|
+
if (action == NavigationRules.Action.EXTERNAL) openExternal(request, rule) else notifyNavigation(request, action, rule)
|
|
80
75
|
}
|
|
81
|
-
|
|
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 ->
|
|
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
|
-
|
|
98
|
+
val appDeclined = answer == false
|
|
99
|
+
report(if (appDeclined) open(request.url) else true)
|
|
109
100
|
}
|
|
110
101
|
}
|
|
111
102
|
|
|
112
103
|
/**
|
|
113
|
-
*
|
|
114
|
-
*
|
|
115
|
-
*
|
|
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.
|
|
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
|
-
|
|
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 =
|
|
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
|
|
39
|
+
// An ArrayBuffer message has no string data: WebMessageCompat.getData throws for it.
|
|
48
40
|
if (message.type != WebMessageCompat.TYPE_STRING) return@addWebMessageListener
|
|
49
|
-
|
|
50
|
-
|
|
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
|
-
|
|
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
|
-
),
|
|
101
|
+
), $STARTED))($EVALUATE, (async () => (
|
|
120
102
|
$script
|
|
121
|
-
))()) :
|
|
103
|
+
))()) : $NO_CHANNEL"""
|
|
122
104
|
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?)")
|
|
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
|
-
*
|
|
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
|
-
|
|
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
|
-
/**
|
|
17
|
-
|
|
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 =
|
|
24
|
-
|
|
25
|
-
private
|
|
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 !=
|
|
35
|
-
!canAsk -> Decision(
|
|
36
|
-
request.url in asked -> Decision(
|
|
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?):
|
|
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(
|
|
47
|
-
if (scheme in
|
|
48
|
-
|
|
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(
|
|
50
|
+
?: return Decision(Action.BLOCK, null)
|
|
52
51
|
val index = rules.indexOfFirst { matches(it, parts, request) }
|
|
53
|
-
return if (index < 0) Decision(
|
|
52
|
+
return if (index < 0) Decision(Action.BLOCK, null) else Decision(actionOf(rules[index]["action"]) ?: Action.BLOCK, index)
|
|
54
53
|
}
|
|
55
54
|
|
|
56
|
-
//
|
|
57
|
-
//
|
|
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>)
|