react-native-minimal-webview 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.md +150 -2
- package/android/build.gradle +26 -0
- package/android/consumer-rules.pro +4 -0
- package/android/src/main/AndroidManifest.xml +2 -0
- package/android/src/main/java/expo/modules/minimalwebview/Asks.kt +44 -0
- package/android/src/main/java/expo/modules/minimalwebview/DocumentEnd.kt +31 -0
- package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +487 -0
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +507 -0
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +358 -0
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +245 -0
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +199 -0
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +197 -0
- package/android/src/main/java/expo/modules/minimalwebview/NavigationRules.kt +113 -0
- package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +303 -0
- package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +76 -0
- package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +259 -0
- package/android/src/main/java/expo/modules/minimalwebview/requests/FileUpload.kt +44 -0
- package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +87 -0
- package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +77 -0
- package/build/WebView.d.ts +96 -0
- package/build/WebView.d.ts.map +1 -0
- package/build/WebView.js +453 -0
- package/build/WebView.js.map +1 -0
- package/build/bridge/createBridge.d.ts +32 -0
- package/build/bridge/createBridge.d.ts.map +1 -0
- package/build/bridge/createBridge.js +137 -0
- package/build/bridge/createBridge.js.map +1 -0
- package/build/bridge/endpoint.d.ts +33 -0
- package/build/bridge/endpoint.d.ts.map +1 -0
- package/build/bridge/endpoint.js +105 -0
- package/build/bridge/endpoint.js.map +1 -0
- package/build/bridge/origins.d.ts +25 -0
- package/build/bridge/origins.d.ts.map +1 -0
- package/build/bridge/origins.js +59 -0
- package/build/bridge/origins.js.map +1 -0
- package/build/bridge/pageClient.generated.d.ts +3 -0
- package/build/bridge/pageClient.generated.d.ts.map +1 -0
- package/build/bridge/pageClient.generated.js +4 -0
- package/build/bridge/pageClient.generated.js.map +1 -0
- package/build/bridge/protocol.d.ts +50 -0
- package/build/bridge/protocol.d.ts.map +1 -0
- package/build/bridge/protocol.js +52 -0
- package/build/bridge/protocol.js.map +1 -0
- package/build/defaultNavigationRules.d.ts +15 -0
- package/build/defaultNavigationRules.d.ts.map +1 -0
- package/build/defaultNavigationRules.js +22 -0
- package/build/defaultNavigationRules.js.map +1 -0
- package/build/index.d.ts +31 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +30 -0
- package/build/index.js.map +1 -0
- package/build/platform.generated.d.ts +701 -0
- package/build/platform.generated.d.ts.map +1 -0
- package/build/platform.generated.js +201 -0
- package/build/platform.generated.js.map +1 -0
- package/build/reactNativeWebViewDefaults.d.ts +21 -0
- package/build/reactNativeWebViewDefaults.d.ts.map +1 -0
- package/build/reactNativeWebViewDefaults.js +12 -0
- package/build/reactNativeWebViewDefaults.js.map +1 -0
- package/build/reactNativeWebViewMessages.d.ts +16 -0
- package/build/reactNativeWebViewMessages.d.ts.map +1 -0
- package/build/reactNativeWebViewMessages.js +24 -0
- package/build/reactNativeWebViewMessages.js.map +1 -0
- package/build/refStore.d.ts +32 -0
- package/build/refStore.d.ts.map +1 -0
- package/build/refStore.js +115 -0
- package/build/refStore.js.map +1 -0
- package/build/types.d.ts +1173 -0
- package/build/types.d.ts.map +1 -0
- package/build/types.defaults.d.ts +8 -0
- package/build/types.defaults.d.ts.map +1 -0
- package/build/types.defaults.js +17 -0
- package/build/types.defaults.js.map +1 -0
- package/build/types.js +2 -0
- package/build/types.js.map +1 -0
- package/expo-module.config.json +9 -0
- package/ios/Asks.swift +45 -0
- package/ios/DelegateProxy.swift +158 -0
- package/ios/DocumentEnd.swift +22 -0
- package/ios/DownloadName.swift +10 -0
- package/ios/Downloads.swift +51 -0
- package/ios/Hooks.swift +310 -0
- package/ios/Loads.swift +44 -0
- package/ios/MRWExceptions.h +9 -0
- package/ios/MRWExceptions.m +10 -0
- package/ios/MRWInvoke.h +38 -0
- package/ios/MRWInvoke.m +187 -0
- package/ios/MinimalWebView+Dialogs.swift +96 -0
- package/ios/MinimalWebView+Navigation.swift +243 -0
- package/ios/MinimalWebView+Scripts.swift +92 -0
- package/ios/MinimalWebView.docc/MinimalWebView.md +13 -0
- package/ios/MinimalWebView.podspec +32 -0
- package/ios/MinimalWebView.swift +513 -0
- package/ios/MinimalWebViewModule.swift +110 -0
- package/ios/NavigationRules.swift +123 -0
- package/ios/OriginRules.swift +36 -0
- package/ios/PlatformCompletions.generated.swift +39 -0
- package/ios/PlatformSettings.swift +252 -0
- package/ios/ReadAccess.swift +19 -0
- package/ios/Recovery.swift +25 -0
- package/ios/SharedCookies.swift +59 -0
- package/package.json +99 -4
- package/src/WebView.tsx +626 -0
- package/src/bridge/createBridge.ts +178 -0
- package/src/bridge/endpoint.ts +123 -0
- package/src/bridge/origins.ts +61 -0
- package/src/bridge/pageClient.generated.ts +5 -0
- package/src/bridge/pageClient.ts +67 -0
- package/src/bridge/protocol.ts +78 -0
- package/src/defaultNavigationRules.ts +24 -0
- package/src/index.ts +37 -0
- package/src/platform.generated.ts +693 -0
- package/src/reactNativeWebViewDefaults.ts +13 -0
- package/src/reactNativeWebViewMessages.ts +26 -0
- package/src/refStore.ts +165 -0
- package/src/types.defaults.ts +24 -0
- package/src/types.ts +1240 -0
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
package expo.modules.minimalwebview
|
|
2
|
+
|
|
3
|
+
import android.content.ActivityNotFoundException
|
|
4
|
+
import android.content.Intent
|
|
5
|
+
import android.net.Uri
|
|
6
|
+
import android.os.FileUriExposedException
|
|
7
|
+
import android.os.Message
|
|
8
|
+
import android.util.Log
|
|
9
|
+
import android.webkit.RenderProcessGoneDetail
|
|
10
|
+
import android.webkit.WebResourceRequest
|
|
11
|
+
import android.webkit.WebView
|
|
12
|
+
import android.webkit.WebViewClient
|
|
13
|
+
import java.net.URISyntaxException
|
|
14
|
+
|
|
15
|
+
/** Navigation decisions: the rules, `ask`, external links and new windows. */
|
|
16
|
+
internal class MinimalWebViewNavigation(
|
|
17
|
+
private val owner: MinimalWebView,
|
|
18
|
+
private val onNavigation: (Map<String, Any?>) -> Unit
|
|
19
|
+
) {
|
|
20
|
+
private val webView get() = owner.webView
|
|
21
|
+
|
|
22
|
+
// URLs an `ask` allowed in this Document: a redirect back to one is not asked again (a later tap on it is).
|
|
23
|
+
private val askedAndAllowed = mutableSetOf<String>()
|
|
24
|
+
|
|
25
|
+
// New windows still waiting for their first URL (createWindow).
|
|
26
|
+
private val children = mutableSetOf<WebView>()
|
|
27
|
+
|
|
28
|
+
fun documentEnded() {
|
|
29
|
+
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()
|
|
33
|
+
ended.forEach { it.destroy() }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Returns true to cancel the navigation (shouldOverrideUrlLoading's meaning). */
|
|
37
|
+
fun decide(request: NavigationRules.Request): Boolean {
|
|
38
|
+
val asked = if (request.isRedirect) askedAndAllowed else emptySet()
|
|
39
|
+
val decision = NavigationRules.decide(owner.navigationRules, request, asked, "onNavigationRequest" in owner.requestHandlers)
|
|
40
|
+
val action = if (decision.action == "ask" && !request.mainFrame) {
|
|
41
|
+
// Android can't hold a navigation, so `ask` cancels and reissues it: a subframe's can't be reissued.
|
|
42
|
+
Log.w(TAG, "`ask` only works for main-frame navigations on Android; blocked ${request.url}")
|
|
43
|
+
"block"
|
|
44
|
+
} else {
|
|
45
|
+
decision.action
|
|
46
|
+
}
|
|
47
|
+
if (action == "ask") {
|
|
48
|
+
ask(request, decision.rule)
|
|
49
|
+
return true
|
|
50
|
+
}
|
|
51
|
+
if (action == "external") {
|
|
52
|
+
openExternal(request, decision.rule)
|
|
53
|
+
return true
|
|
54
|
+
}
|
|
55
|
+
notifyNavigation(request, action, decision.rule)
|
|
56
|
+
return action != "allow"
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
private fun fields(request: NavigationRules.Request) = mapOf(
|
|
60
|
+
"url" to request.url,
|
|
61
|
+
"mainFrame" to request.mainFrame,
|
|
62
|
+
"newWindow" to request.newWindow,
|
|
63
|
+
"userInitiated" to request.userInitiated
|
|
64
|
+
)
|
|
65
|
+
|
|
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))
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Cancel now, ask JS, reissue on allow. Never blocks the UI thread. Loses the gesture flag and the redirect chain.
|
|
71
|
+
private fun ask(request: NavigationRules.Request, rule: Int?) {
|
|
72
|
+
val referrer = webView.url
|
|
73
|
+
val id = owner.asks.ask("core", "onNavigationRequest", fields(request)) { answer ->
|
|
74
|
+
val action = NavigationRules.answer(answer)
|
|
75
|
+
if (action == "allow") {
|
|
76
|
+
askedAndAllowed += request.url
|
|
77
|
+
reissue(request.url, referrer)
|
|
78
|
+
}
|
|
79
|
+
if (action == "external") openExternal(request, rule) else notifyNavigation(request, action, rule)
|
|
80
|
+
}
|
|
81
|
+
// Unanswered after the timeout: block (the answer callback runs with null). A late answer finds nothing.
|
|
82
|
+
owner.mainHandler.postDelayed({ owner.asks.cancel(id) }, ASK_TIMEOUT_MS)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// WebView's request headers on a navigation are empty, so the page's URL goes as the referrer. WebView applies its
|
|
86
|
+
// default policy to it (origin only cross-origin, none from https to http); the page's own referrer policy is lost.
|
|
87
|
+
// loadUrl skips shouldOverrideUrlLoading, so the reissued URL isn't asked again (its redirects still go to decide).
|
|
88
|
+
private fun reissue(url: String, referrer: String?) = webView.loadUrl(url, referrer?.let { mapOf("Referer" to it) }.orEmpty())
|
|
89
|
+
|
|
90
|
+
/** A download no `onDownload` takes. */
|
|
91
|
+
fun openDownload(url: String) {
|
|
92
|
+
if (url.startsWith("http:") || url.startsWith("https:")) {
|
|
93
|
+
openExternal(NavigationRules.Request(url, true, false, false), null)
|
|
94
|
+
} else {
|
|
95
|
+
Log.w(TAG, "dropped a download from ${url.take(40)}")
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
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
|
+
private fun openExternal(request: NavigationRules.Request, rule: Int?) {
|
|
104
|
+
val report = { opened: Boolean -> notifyNavigation(request, if (opened) "external" else "block", rule) }
|
|
105
|
+
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
|
+
owner.asks.ask("core", "onOpenExternal", fields(request)) { answer ->
|
|
108
|
+
report(answer != false || open(request.url))
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
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.
|
|
116
|
+
*/
|
|
117
|
+
private fun open(url: String): Boolean {
|
|
118
|
+
val intent = try {
|
|
119
|
+
browsableIntent(url)
|
|
120
|
+
} catch (e: URISyntaxException) {
|
|
121
|
+
return failed("malformed external URL $url", e)
|
|
122
|
+
} catch (e: IllegalArgumentException) {
|
|
123
|
+
return failed("malformed external URL $url", e)
|
|
124
|
+
}
|
|
125
|
+
return try {
|
|
126
|
+
owner.context.startActivity(intent)
|
|
127
|
+
true
|
|
128
|
+
} catch (e: ActivityNotFoundException) {
|
|
129
|
+
openFallback(intent, url, e)
|
|
130
|
+
} catch (e: SecurityException) {
|
|
131
|
+
failed("not allowed to open $url", e)
|
|
132
|
+
} catch (e: FileUriExposedException) {
|
|
133
|
+
failed("not allowed to open $url", e)
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Only what a browser would allow: BROWSABLE, no explicit component or selector, and no URI permission grants. */
|
|
138
|
+
private fun browsableIntent(url: String): Intent {
|
|
139
|
+
val intent = if (url.startsWith("intent:", ignoreCase = true)) {
|
|
140
|
+
Intent.parseUri(url, Intent.URI_INTENT_SCHEME).apply {
|
|
141
|
+
component = null
|
|
142
|
+
selector = null
|
|
143
|
+
}
|
|
144
|
+
} else {
|
|
145
|
+
Intent(Intent.ACTION_VIEW, Uri.parse(url))
|
|
146
|
+
}
|
|
147
|
+
intent.addCategory(Intent.CATEGORY_BROWSABLE)
|
|
148
|
+
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
|
|
149
|
+
return intent
|
|
150
|
+
}
|
|
151
|
+
|
|
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.
|
|
154
|
+
private fun openFallback(intent: Intent, url: String, error: ActivityNotFoundException): Boolean {
|
|
155
|
+
val fallback = intent.getStringExtra("browser_fallback_url")?.takeIf { it.startsWith("https://") || it.startsWith("http://") }
|
|
156
|
+
?: return failed("no app opens $url", error)
|
|
157
|
+
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
|
+
return false
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Never a second WebView: a popup model is more than almost any app wants, so a throwaway one only catches the URL.
|
|
163
|
+
fun createWindow(isUserGesture: Boolean, resultMsg: Message): Boolean {
|
|
164
|
+
val child = WebView(owner.context)
|
|
165
|
+
// It only catches a URL: none of the page's access, and no JS of its own.
|
|
166
|
+
child.settings.allowFileAccess = false
|
|
167
|
+
child.settings.allowContentAccess = false
|
|
168
|
+
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).
|
|
171
|
+
// Destroyed later: this may run inside the child's own callback.
|
|
172
|
+
fun finish(): Boolean {
|
|
173
|
+
val wasPending = children.remove(child)
|
|
174
|
+
if (wasPending) owner.mainHandler.post { child.destroy() }
|
|
175
|
+
return wasPending
|
|
176
|
+
}
|
|
177
|
+
child.webViewClient = object : WebViewClient() {
|
|
178
|
+
// A renderer crash in the throwaway window must not take the app down.
|
|
179
|
+
override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {
|
|
180
|
+
finish()
|
|
181
|
+
return true
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
|
|
185
|
+
val target = request.url.toString()
|
|
186
|
+
if (finish() && !decide(NavigationRules.Request(target, true, true, isUserGesture))) reissue(target, webView.url)
|
|
187
|
+
return true
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
// window.open('') or about:blank never navigates: give up on it.
|
|
191
|
+
owner.mainHandler.postDelayed({ finish() }, NEW_WINDOW_TIMEOUT_MS)
|
|
192
|
+
(resultMsg.obj as WebView.WebViewTransport).webView = child
|
|
193
|
+
resultMsg.sendToTarget()
|
|
194
|
+
return true
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
private const val ASK_TIMEOUT_MS = 1000L
|
|
199
|
+
private const val NEW_WINDOW_TIMEOUT_MS = 5000L
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
package expo.modules.minimalwebview
|
|
2
|
+
|
|
3
|
+
import androidx.webkit.JavaScriptReplyProxy
|
|
4
|
+
import androidx.webkit.ScriptHandler
|
|
5
|
+
import androidx.webkit.WebMessageCompat
|
|
6
|
+
import androidx.webkit.WebViewCompat
|
|
7
|
+
import androidx.webkit.WebViewFeature
|
|
8
|
+
import expo.modules.kotlin.exception.CodedException
|
|
9
|
+
import org.json.JSONArray
|
|
10
|
+
|
|
11
|
+
/** Scripts in the page: the bridge transport, `injectedScripts` and `evaluate`. */
|
|
12
|
+
internal class MinimalWebViewScripts(private val owner: MinimalWebView, private val onBridge: (Map<String, Any?>) -> Unit) {
|
|
13
|
+
private val webView get() = owner.webView
|
|
14
|
+
|
|
15
|
+
// Bridge: the page posts through `window.nativeBridgeTransport`; replies go to the main frame's latest proxy.
|
|
16
|
+
private var replyProxy: JavaScriptReplyProxy? = null
|
|
17
|
+
private var installedScripts: List<InjectedScript>? = null
|
|
18
|
+
private val scriptHandlers = mutableListOf<ScriptHandler>()
|
|
19
|
+
private val evaluations = Evaluations()
|
|
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
|
+
fun install() {
|
|
26
|
+
// After a crash they are the destroyed WebView's: removing them would call into it.
|
|
27
|
+
scriptHandlers.clear()
|
|
28
|
+
installEvaluate()
|
|
29
|
+
installBridge()
|
|
30
|
+
installScripts(force = true)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** A later prop batch: only `injectedScripts` can change. */
|
|
34
|
+
fun update() = installScripts()
|
|
35
|
+
|
|
36
|
+
private fun installBridge() {
|
|
37
|
+
val script = owner.bridgeScript ?: return
|
|
38
|
+
val bridgeFeatures = listOf(WebViewFeature.WEB_MESSAGE_LISTENER, WebViewFeature.DOCUMENT_START_SCRIPT)
|
|
39
|
+
if (lacks("bridge", bridgeFeatures, "bridge calls reject with `unavailable`")) {
|
|
40
|
+
onBridge(mapOf("unavailable" to true))
|
|
41
|
+
return
|
|
42
|
+
}
|
|
43
|
+
val origins = owner.bridgeOrigins.orEmpty().toSet()
|
|
44
|
+
// A malformed origin rule makes WebView throw; createBridge validates them, so this only guards against misuse.
|
|
45
|
+
// JS learns of it: calls reject with `unavailable`.
|
|
46
|
+
try {
|
|
47
|
+
WebViewCompat.addWebMessageListener(webView, "nativeBridgeTransport", origins) { _, message, sourceOrigin, isMainFrame, proxy ->
|
|
48
|
+
// Main frame only, like iOS. The origin rules already filtered the sender.
|
|
49
|
+
if (!isMainFrame) return@addWebMessageListener
|
|
50
|
+
// An ArrayBuffer has no string data (`data` throws); iOS drops a non-string message too.
|
|
51
|
+
if (message.type != WebMessageCompat.TYPE_STRING) return@addWebMessageListener
|
|
52
|
+
replyProxy = proxy
|
|
53
|
+
onBridge(mapOf("message" to message.data, "origin" to sourceOrigin.toString()))
|
|
54
|
+
}
|
|
55
|
+
// Runs before the page's own scripts, after the transport object exists.
|
|
56
|
+
WebViewCompat.addDocumentStartJavaScript(webView, script, origins)
|
|
57
|
+
} catch (e: IllegalArgumentException) {
|
|
58
|
+
failed("bridge not installed: invalid allowedOrigins $origins", e)
|
|
59
|
+
onBridge(mapOf("unavailable" to true))
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Changed scripts take effect from the next navigation. */
|
|
64
|
+
private fun installScripts(force: Boolean = false) {
|
|
65
|
+
val scripts = owner.injectedScripts.orEmpty()
|
|
66
|
+
if (!force && scripts == installedScripts) return
|
|
67
|
+
installedScripts = scripts
|
|
68
|
+
scriptHandlers.forEach { it.remove() }
|
|
69
|
+
scriptHandlers.clear()
|
|
70
|
+
if (scripts.isEmpty() || lacks("injectedScripts", listOf(WebViewFeature.DOCUMENT_START_SCRIPT), "injected scripts don't run")) return
|
|
71
|
+
for (script in scripts) {
|
|
72
|
+
val code = script.code ?: continue
|
|
73
|
+
// No frame selector in androidx.webkit 1.17: main-frame-only scripts guard themselves.
|
|
74
|
+
// A prefix, not a wrapping block: top-level const/let/class in the script must stay global.
|
|
75
|
+
val source = if (script.allFrames != true) "if (window !== window.top) throw 0;\n$code" else code
|
|
76
|
+
scriptHandlers += WebViewCompat.addDocumentStartJavaScript(webView, source, setOf("*"))
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
fun post(message: String) {
|
|
81
|
+
replyProxy?.postMessage(message)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The Document ended: its evaluations fail and its reply proxy is gone. JS queues bridge messages until the next
|
|
86
|
+
* page is ready; at unmount it rejects what is in flight itself.
|
|
87
|
+
*/
|
|
88
|
+
fun documentEnded(reason: DocumentEnd) {
|
|
89
|
+
evaluations.failAll()
|
|
90
|
+
// At a commit this runs one main-thread hop after Chromium's (the NavigationListener's executor posts it), and
|
|
91
|
+
// relies on landing before the new page's first message sets replyProxy (the bridge suite's head-script call).
|
|
92
|
+
replyProxy = null
|
|
93
|
+
if (reason != DocumentEnd.CLOSING && owner.bridgeScript != null) onBridge(mapOf("navigated" to true))
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* `evaluate` results come back through one global in every frame (`*`, before the first document). A page can forge
|
|
98
|
+
* them, as it can already shape any value its own world returns.
|
|
99
|
+
*/
|
|
100
|
+
private fun installEvaluate() {
|
|
101
|
+
if (!WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) return
|
|
102
|
+
WebViewCompat.addWebMessageListener(webView, EVALUATE, setOf("*")) { _, message, _, isMainFrame, _ ->
|
|
103
|
+
// As in installBridge: only string messages.
|
|
104
|
+
if (message.type == WebMessageCompat.TYPE_STRING) evaluations.settle(message.data, isMainFrame)
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* The `evaluate` ref method. A new Document rejects what is still waiting: WebView drops the callback when the
|
|
110
|
+
* document is replaced first.
|
|
111
|
+
*/
|
|
112
|
+
fun evaluate(script: String, onResult: (Result<String>) -> Unit) {
|
|
113
|
+
if (!WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) {
|
|
114
|
+
return onResult(failure("unavailable", "evaluate needs WEB_MESSAGE_LISTENER; update Android System WebView"))
|
|
115
|
+
}
|
|
116
|
+
val id = evaluations.add(onResult)
|
|
117
|
+
// The script sits in a scope of its own (no wrapper names shadow the page's); the sync value is 1 once it started.
|
|
118
|
+
val code = """typeof $EVALUATE === 'object' ? ((t, p) => (p.then(
|
|
119
|
+
(v) => { try { v = JSON.stringify(v) } catch { v = null } t.postMessage(JSON.stringify([$id, v ?? 'null'])) },
|
|
120
|
+
(e) => { try { e = String(e) } catch { e = 'Error' } t.postMessage(JSON.stringify([$id, null, e])) }
|
|
121
|
+
), 1))($EVALUATE, (async () => (
|
|
122
|
+
$script
|
|
123
|
+
))()) : 0"""
|
|
124
|
+
webView.evaluateJavascript(code) { value ->
|
|
125
|
+
if (value == "1") return@evaluateJavascript
|
|
126
|
+
// 0: the page has no channel (it loaded before the listener); null: the script didn't parse.
|
|
127
|
+
evaluations.fail(id, if (value == "0") "no evaluate channel in this page" else "the script did not run (a syntax error?)")
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Whether this device's WebView lacks one of [features] that [prop] needs; warns about it once per process. */
|
|
132
|
+
private fun lacks(prop: String, features: List<String>, lost: String): Boolean {
|
|
133
|
+
val missing = features.filterNot(WebViewFeature::isFeatureSupported)
|
|
134
|
+
if (missing.isEmpty()) return false
|
|
135
|
+
if (warnedProps.add(prop)) {
|
|
136
|
+
val provider = WebViewCompat.getCurrentWebViewPackage(owner.context)
|
|
137
|
+
owner.warn(
|
|
138
|
+
"$prop needs WebView features ${missing.joinToString()}, missing in ${provider?.packageName} ${provider?.versionName}: $lost. " +
|
|
139
|
+
"Update Android System WebView."
|
|
140
|
+
)
|
|
141
|
+
}
|
|
142
|
+
return true
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
private companion object {
|
|
146
|
+
val warnedProps = mutableSetOf<String>()
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* The `evaluate` calls waiting for their result, by id. Each settles once: by the page's reply, a script that didn't
|
|
152
|
+
* run, or the Document's end. Main thread only.
|
|
153
|
+
*/
|
|
154
|
+
internal class Evaluations {
|
|
155
|
+
private val waiting = mutableMapOf<Int, (Result<String>) -> Unit>()
|
|
156
|
+
private var next = 0
|
|
157
|
+
|
|
158
|
+
/** Keeps [onResult] until its evaluation settles; returns the id the page's reply carries. */
|
|
159
|
+
fun add(onResult: (Result<String>) -> Unit): Int {
|
|
160
|
+
val id = next++
|
|
161
|
+
waiting[id] = onResult
|
|
162
|
+
return id
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* The page's [reply], `[id, valueJson]` or `[id, null, errorMessage]`, settles evaluation `id` with the value or a
|
|
167
|
+
* `script_error`. Only the main frame's replies count; a malformed one, or one for an id not waiting, is dropped.
|
|
168
|
+
*/
|
|
169
|
+
fun settle(reply: String?, mainFrame: Boolean) {
|
|
170
|
+
if (!mainFrame) return
|
|
171
|
+
val parts = runCatching { JSONArray(reply) }.getOrNull() ?: return
|
|
172
|
+
val onResult = waiting.remove(parts.optInt(0, -1)) ?: return
|
|
173
|
+
onResult(
|
|
174
|
+
if (parts.length() > 2) failure("script_error", parts.optString(2))
|
|
175
|
+
else Result.success(parts.optString(1, "null"))
|
|
176
|
+
)
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** The script didn't run: evaluation [id] fails with a `script_error` saying [why], unless it settled already. */
|
|
180
|
+
fun fail(id: Int, why: String) {
|
|
181
|
+
waiting.remove(id)?.invoke(failure("script_error", why))
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** The Document ended: every waiting evaluation fails with `navigated`. */
|
|
185
|
+
fun failAll() {
|
|
186
|
+
val all = waiting.values.toList()
|
|
187
|
+
waiting.clear()
|
|
188
|
+
all.forEach { it(failure("navigated", "the page navigated before the script finished")) }
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Why an `evaluate` failed; its code is the JS error code (`script_error`, `navigated`, `unavailable`). */
|
|
193
|
+
internal class EvaluateError(code: String, message: String) : CodedException(code, message, null)
|
|
194
|
+
|
|
195
|
+
private fun failure(code: String, message: String) = Result.failure<String>(EvaluateError(code, message))
|
|
196
|
+
|
|
197
|
+
private const val EVALUATE = "nativeEvaluateResult"
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
package expo.modules.minimalwebview
|
|
2
|
+
|
|
3
|
+
/** The structured navigation rules. Semantics and cases: src/__tests__/vectors/navigation-rules.json (shared with Swift). */
|
|
4
|
+
internal object NavigationRules {
|
|
5
|
+
data class Request(
|
|
6
|
+
val url: String,
|
|
7
|
+
val mainFrame: Boolean,
|
|
8
|
+
val newWindow: Boolean,
|
|
9
|
+
val userInitiated: Boolean,
|
|
10
|
+
val isRedirect: Boolean = false
|
|
11
|
+
)
|
|
12
|
+
|
|
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?)
|
|
15
|
+
|
|
16
|
+
/** Load in place without the rules. */
|
|
17
|
+
private val internalSchemes = setOf("about", "data", "javascript")
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Never open as a new window, whatever the rules say: the core loads an allowed new window in the main frame itself,
|
|
21
|
+
* past the engine's limits on what a page may navigate the top frame to.
|
|
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")
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The rules' decision, gated for `ask`: blocked when nothing can answer it ([canAsk] false), allowed when its URL is
|
|
29
|
+
* in [asked] (URLs an `ask` already allowed). An unknown rule action blocks.
|
|
30
|
+
*/
|
|
31
|
+
fun decide(rules: List<Map<String, Any?>>?, request: Request, asked: Set<String>, canAsk: Boolean): Decision {
|
|
32
|
+
val decision = match(rules, request)
|
|
33
|
+
return when {
|
|
34
|
+
decision.action != "ask" -> decision
|
|
35
|
+
!canAsk -> Decision("block", decision.rule)
|
|
36
|
+
request.url in asked -> Decision("allow", decision.rule)
|
|
37
|
+
else -> decision
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
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"
|
|
43
|
+
|
|
44
|
+
private fun match(rules: List<Map<String, Any?>>?, request: Request): Decision {
|
|
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)
|
|
50
|
+
val parts = (if (scheme == "blob") blobOrigin(request.url) else parts(scheme, request.url))
|
|
51
|
+
?: return Decision("block", null)
|
|
52
|
+
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)
|
|
54
|
+
}
|
|
55
|
+
|
|
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.
|
|
58
|
+
private val urlParts = Regex("^([a-zA-Z][a-zA-Z0-9+.-]*):(?://([^/?#]*))?([^?#]*)(?:\\?([^#]*))?")
|
|
59
|
+
|
|
60
|
+
private data class Parts(val scheme: String, val host: String?, val path: String, val params: List<String>)
|
|
61
|
+
|
|
62
|
+
private fun parts(scheme: String, url: String): Parts {
|
|
63
|
+
val match = urlParts.find(url) ?: return Parts(scheme, null, "/", emptyList())
|
|
64
|
+
val authority = match.groups[2]?.value
|
|
65
|
+
val path = match.groupValues[3]
|
|
66
|
+
val params = match.groups[4]?.value?.split('&')?.filter { it.isNotEmpty() }.orEmpty()
|
|
67
|
+
return Parts(scheme, hostOf(authority), if (authority != null && path.isNotEmpty()) path else "/", params)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* A blob: document has the origin its URL carries (`blob:https://a.test/…`), so the rules see that origin, with
|
|
72
|
+
* path "/"; null for an opaque one (`blob:null/…`), which no rule describes.
|
|
73
|
+
*/
|
|
74
|
+
private fun blobOrigin(url: String): Parts? {
|
|
75
|
+
val match = urlParts.find(url.substringAfter(':')) ?: return null
|
|
76
|
+
return Parts(match.groupValues[1].lowercase(), hostOf(match.groups[2]?.value), "/", emptyList())
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Host without userinfo, port or a trailing dot, lowercased; null when there is none. */
|
|
80
|
+
private fun hostOf(authority: String?): String? {
|
|
81
|
+
if (authority.isNullOrEmpty()) return null
|
|
82
|
+
val withoutUser = authority.substringAfterLast('@')
|
|
83
|
+
val host = if (withoutUser.startsWith("[")) withoutUser.substringBefore(']') + "]" else withoutUser.replace(Regex(":\\d*$"), "")
|
|
84
|
+
return host.lowercase().removeSuffix(".").ifEmpty { null }
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** null when the field is unset; a value that isn't a list (a string from untyped JS) matches nothing. */
|
|
88
|
+
private fun list(value: Any?): List<String>? = value?.let { (it as? List<*>)?.map(Any?::toString).orEmpty() }
|
|
89
|
+
|
|
90
|
+
private fun matches(rule: Map<String, Any?>, parts: Parts, request: Request): Boolean {
|
|
91
|
+
val (scheme, host, path, params) = parts
|
|
92
|
+
val schemes = list(rule["scheme"])
|
|
93
|
+
val hosts = list(rule["host"])
|
|
94
|
+
val paths = list(rule["path"])
|
|
95
|
+
val queries = list(rule["query"])
|
|
96
|
+
return (schemes == null || schemes.any { it.equals(scheme, ignoreCase = true) }) &&
|
|
97
|
+
(hosts == null || host != null && hosts.any { hostMatches(it.lowercase(), host) }) &&
|
|
98
|
+
(paths == null || paths.any { path.startsWith(it) }) &&
|
|
99
|
+
(queries == null || queries.any { paramMatches(it, params) }) &&
|
|
100
|
+
flag(rule, "mainFrame", request.mainFrame) &&
|
|
101
|
+
flag(rule, "newWindow", request.newWindow) &&
|
|
102
|
+
flag(rule, "userInitiated", request.userInitiated)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** `name=value` matches that exact parameter; `name` matches a parameter with that name, whatever its value. */
|
|
106
|
+
private fun paramMatches(entry: String, params: List<String>) =
|
|
107
|
+
params.any { if ('=' in entry) it == entry else it.substringBefore('=') == entry }
|
|
108
|
+
|
|
109
|
+
private fun flag(rule: Map<String, Any?>, name: String, value: Boolean) = (rule[name] as? Boolean)?.let { it == value } ?: true
|
|
110
|
+
|
|
111
|
+
private fun hostMatches(pattern: String, host: String) =
|
|
112
|
+
if (pattern.startsWith("*.")) host.endsWith(pattern.substring(1)) else host == pattern
|
|
113
|
+
}
|