react-native-minimal-webview 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +130 -2
  3. package/android/build.gradle +26 -0
  4. package/android/consumer-rules.pro +4 -0
  5. package/android/src/main/AndroidManifest.xml +2 -0
  6. package/android/src/main/java/expo/modules/minimalwebview/Asks.kt +44 -0
  7. package/android/src/main/java/expo/modules/minimalwebview/DocumentEnd.kt +31 -0
  8. package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +496 -0
  9. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +510 -0
  10. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +359 -0
  11. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +245 -0
  12. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +199 -0
  13. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +191 -0
  14. package/android/src/main/java/expo/modules/minimalwebview/NavigationRules.kt +113 -0
  15. package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +306 -0
  16. package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +76 -0
  17. package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +258 -0
  18. package/android/src/main/java/expo/modules/minimalwebview/requests/FileUpload.kt +44 -0
  19. package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +87 -0
  20. package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +77 -0
  21. package/build/WebView.d.ts +99 -0
  22. package/build/WebView.d.ts.map +1 -0
  23. package/build/WebView.js +448 -0
  24. package/build/WebView.js.map +1 -0
  25. package/build/bridge/createBridge.d.ts +32 -0
  26. package/build/bridge/createBridge.d.ts.map +1 -0
  27. package/build/bridge/createBridge.js +135 -0
  28. package/build/bridge/createBridge.js.map +1 -0
  29. package/build/bridge/endpoint.d.ts +35 -0
  30. package/build/bridge/endpoint.d.ts.map +1 -0
  31. package/build/bridge/endpoint.js +100 -0
  32. package/build/bridge/endpoint.js.map +1 -0
  33. package/build/bridge/origins.d.ts +25 -0
  34. package/build/bridge/origins.d.ts.map +1 -0
  35. package/build/bridge/origins.js +60 -0
  36. package/build/bridge/origins.js.map +1 -0
  37. package/build/bridge/pageClient.generated.d.ts +3 -0
  38. package/build/bridge/pageClient.generated.d.ts.map +1 -0
  39. package/build/bridge/pageClient.generated.js +4 -0
  40. package/build/bridge/pageClient.generated.js.map +1 -0
  41. package/build/bridge/protocol.d.ts +50 -0
  42. package/build/bridge/protocol.d.ts.map +1 -0
  43. package/build/bridge/protocol.js +52 -0
  44. package/build/bridge/protocol.js.map +1 -0
  45. package/build/defaultNavigationRules.d.ts +16 -0
  46. package/build/defaultNavigationRules.d.ts.map +1 -0
  47. package/build/defaultNavigationRules.js +23 -0
  48. package/build/defaultNavigationRules.js.map +1 -0
  49. package/build/index.d.ts +31 -0
  50. package/build/index.d.ts.map +1 -0
  51. package/build/index.js +30 -0
  52. package/build/index.js.map +1 -0
  53. package/build/platform.generated.d.ts +702 -0
  54. package/build/platform.generated.d.ts.map +1 -0
  55. package/build/platform.generated.js +199 -0
  56. package/build/platform.generated.js.map +1 -0
  57. package/build/reactNativeWebViewDefaults.d.ts +21 -0
  58. package/build/reactNativeWebViewDefaults.d.ts.map +1 -0
  59. package/build/reactNativeWebViewDefaults.js +12 -0
  60. package/build/reactNativeWebViewDefaults.js.map +1 -0
  61. package/build/reactNativeWebViewMessages.d.ts +22 -0
  62. package/build/reactNativeWebViewMessages.d.ts.map +1 -0
  63. package/build/reactNativeWebViewMessages.js +30 -0
  64. package/build/reactNativeWebViewMessages.js.map +1 -0
  65. package/build/refStore.d.ts +31 -0
  66. package/build/refStore.d.ts.map +1 -0
  67. package/build/refStore.js +113 -0
  68. package/build/refStore.js.map +1 -0
  69. package/build/types.d.ts +1127 -0
  70. package/build/types.d.ts.map +1 -0
  71. package/build/types.defaults.d.ts +8 -0
  72. package/build/types.defaults.d.ts.map +1 -0
  73. package/build/types.defaults.js +17 -0
  74. package/build/types.defaults.js.map +1 -0
  75. package/build/types.js +2 -0
  76. package/build/types.js.map +1 -0
  77. package/expo-module.config.json +9 -0
  78. package/ios/Asks.swift +45 -0
  79. package/ios/DelegateProxy.swift +162 -0
  80. package/ios/DocumentEnd.swift +23 -0
  81. package/ios/DownloadName.swift +12 -0
  82. package/ios/Downloads.swift +51 -0
  83. package/ios/Hooks.swift +308 -0
  84. package/ios/Loads.swift +44 -0
  85. package/ios/MRWExceptions.h +9 -0
  86. package/ios/MRWExceptions.m +10 -0
  87. package/ios/MRWInvoke.h +23 -0
  88. package/ios/MRWInvoke.m +187 -0
  89. package/ios/MinimalWebView+Dialogs.swift +99 -0
  90. package/ios/MinimalWebView+Navigation.swift +244 -0
  91. package/ios/MinimalWebView+Scripts.swift +92 -0
  92. package/ios/MinimalWebView.docc/MinimalWebView.md +13 -0
  93. package/ios/MinimalWebView.podspec +32 -0
  94. package/ios/MinimalWebView.swift +512 -0
  95. package/ios/MinimalWebViewModule.swift +110 -0
  96. package/ios/NavigationRules.swift +123 -0
  97. package/ios/OriginRules.swift +35 -0
  98. package/ios/PlatformCompletions.generated.swift +39 -0
  99. package/ios/PlatformSettings.swift +247 -0
  100. package/ios/ReadAccess.swift +19 -0
  101. package/ios/Recovery.swift +25 -0
  102. package/ios/SharedCookies.swift +59 -0
  103. package/package.json +94 -4
  104. package/src/WebView.tsx +623 -0
  105. package/src/bridge/createBridge.ts +176 -0
  106. package/src/bridge/endpoint.ts +119 -0
  107. package/src/bridge/origins.ts +62 -0
  108. package/src/bridge/pageClient.generated.ts +5 -0
  109. package/src/bridge/pageClient.ts +68 -0
  110. package/src/bridge/protocol.ts +78 -0
  111. package/src/defaultNavigationRules.ts +25 -0
  112. package/src/index.ts +37 -0
  113. package/src/platform.generated.ts +694 -0
  114. package/src/reactNativeWebViewDefaults.ts +13 -0
  115. package/src/reactNativeWebViewMessages.ts +32 -0
  116. package/src/refStore.ts +164 -0
  117. package/src/types.defaults.ts +24 -0
  118. package/src/types.ts +1194 -0
@@ -0,0 +1,359 @@
1
+ package expo.modules.minimalwebview
2
+
3
+ import android.annotation.SuppressLint
4
+ import android.graphics.Bitmap
5
+ import android.net.Uri
6
+ import android.net.http.SslError
7
+ import android.os.Message
8
+ import android.os.SystemClock
9
+ import android.view.KeyEvent
10
+ import android.view.View
11
+ import android.webkit.ClientCertRequest
12
+ import android.webkit.ConsoleMessage
13
+ import android.webkit.GeolocationPermissions
14
+ import android.webkit.HttpAuthHandler
15
+ import android.webkit.JsPromptResult
16
+ import android.webkit.JsResult
17
+ import android.webkit.PermissionRequest
18
+ import android.webkit.RenderProcessGoneDetail
19
+ import android.webkit.SafeBrowsingResponse
20
+ import android.webkit.SslErrorHandler
21
+ import android.webkit.ValueCallback
22
+ import android.webkit.WebChromeClient
23
+ import android.webkit.WebResourceError
24
+ import android.webkit.WebResourceRequest
25
+ import android.webkit.WebResourceResponse
26
+ import android.webkit.WebView
27
+ import android.webkit.WebViewClient
28
+ import androidx.webkit.Navigation
29
+ import androidx.webkit.NavigationListener
30
+ import androidx.webkit.Page
31
+
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` (with no hook client, the core or WebView's default decides), the rest through `observing`.
34
+
35
+ 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
+ private val loadedPages = mutableSetOf<Page>()
38
+
39
+ override fun onPageDeleted(page: Page) {
40
+ loadedPages -= page
41
+ }
42
+
43
+ override fun onNavigationStarted(navigation: Navigation) {
44
+ if (navigation.isSameDocument) return
45
+ owner.fileUpload.cancel()
46
+ owner.pendingUrl = navigation.url
47
+ owner.loadStarted()
48
+ }
49
+
50
+ override fun onNavigationRedirected(navigation: Navigation) {
51
+ owner.pendingUrl = navigation.url
52
+ owner.stateChanged()
53
+ }
54
+
55
+ // A failed main-frame load commits an error page at the failed URL: `url` becomes that URL, as on iOS.
56
+ override fun onNavigationCompleted(navigation: Navigation) {
57
+ // The Document ends before `url` moves on, so its handlers see the page that ended: as on iOS, and before 146,
58
+ // where onPageStarted comes ahead of doUpdateVisitedHistory.
59
+ if (navigation.didCommit() && !navigation.isSameDocument) owner.endDocument(DocumentEnd.COMMITTED)
60
+ if (navigation.didCommit()) owner.url = navigation.url
61
+ if (!navigation.isSameDocument) {
62
+ owner.pendingUrl = null
63
+ // A reported network or SSL error already made it "failed". Chromium's error page for an HTTP status (a 404 with
64
+ // an empty body) is the server's answer: "finished", as on iOS.
65
+ owner.outcome = owner.outcome ?: when {
66
+ !navigation.didCommit() -> "cancelled" // a stop, a download, a 204, a blocked redirect, a newer load
67
+ navigation.didCommitErrorPage() && navigation.statusCode < 400 -> "failed"
68
+ else -> "finished"
69
+ }
70
+ // A page restored from the back-forward cache (its Page, already loaded) gets no onPageLoadEvent again.
71
+ if (!navigation.didCommit() || navigation.page?.let { it in loadedPages } == true) owner.loadEnded()
72
+ }
73
+ owner.stateChanged()
74
+ }
75
+
76
+ override fun onPageLoadEvent(page: Page) {
77
+ loadedPages += page
78
+ owner.loadEnded()
79
+ }
80
+ }
81
+
82
+ private val WEB_VIEW = WebView::class.java
83
+ private val STRING = String::class.java
84
+ private val INT = Integer.TYPE
85
+ private val BOOLEAN = java.lang.Boolean.TYPE
86
+ private val FLOAT = java.lang.Float.TYPE
87
+
88
+ internal class Client(private val owner: MinimalWebView, private val navigation: MinimalWebViewNavigation) : WebViewClient() {
89
+ /** The first hook client that overrides a decision callback, or null: the core decides. */
90
+ private fun deciding(name: String, vararg types: Class<*>, lost: String? = null) =
91
+ owner.deciders.first(name, owner.clients, lost) { it.overrides(name, *types) }
92
+
93
+ /** Every hook client that overrides an observation callback, after the core. */
94
+ private inline fun observing(name: String, vararg types: Class<*>, block: (WebViewClient) -> Unit) =
95
+ owner.clients.forEach { if (it.overrides(name, *types)) block(it) }
96
+
97
+ // Without NavigationListener: the last main-frame URL allowed to load (a page's navigation or a redirect), which
98
+ // onReceivedSslError can't otherwise tell from a subresource.
99
+ private var allowedMainFrameUrl: String? = null
100
+
101
+ // Not called for POST, the initial loadUrl, or reissued loads; called again for their redirects.
102
+ override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
103
+ val url = request.url.toString()
104
+ val override = deciding(
105
+ "shouldOverrideUrlLoading", WEB_VIEW, WebResourceRequest::class.java,
106
+ lost = "navigationRules, their defaults and onNavigationRequest don't apply to navigations"
107
+ )?.shouldOverrideUrlLoading(view, request)
108
+ ?: navigation.decide(NavigationRules.Request(url, request.isForMainFrame, false, request.hasGesture(), request.isRedirect))
109
+ if (!override && request.isForMainFrame) allowedMainFrameUrl = url
110
+ return override
111
+ }
112
+
113
+ // Without NavigationListener (WebView older than 146): a main-frame document commits here.
114
+ // Chromium calls it at commit (for every app but old GMS), so a load that never commits (a stop, a download, a 204, a
115
+ // blocked redirect) gets no load events and no outcome here.
116
+ override fun onPageStarted(view: WebView, url: String?, favicon: Bitmap?) {
117
+ if (!owner.hasNavigationListener) {
118
+ owner.endDocument(DocumentEnd.COMMITTED)
119
+ owner.loadStarted()
120
+ }
121
+ observing("onPageStarted", WEB_VIEW, STRING, Bitmap::class.java) { it.onPageStarted(view, url, favicon) }
122
+ }
123
+
124
+ override fun onPageFinished(view: WebView, url: String?) {
125
+ if (!owner.hasNavigationListener) {
126
+ owner.outcome = owner.outcome ?: "finished" // "failed" when a main-frame error came first
127
+ owner.loadEnded()
128
+ }
129
+ observing("onPageFinished", WEB_VIEW, STRING) { it.onPageFinished(view, url) }
130
+ }
131
+
132
+ override fun onLoadResource(view: WebView, url: String?) =
133
+ observing("onLoadResource", WEB_VIEW, STRING) { it.onLoadResource(view, url) }
134
+
135
+ override fun onPageCommitVisible(view: WebView, url: String?) =
136
+ observing("onPageCommitVisible", WEB_VIEW, STRING) { it.onPageCommitVisible(view, url) }
137
+
138
+ // On a background thread, as WebView calls it: a hook client that overrides it runs there too.
139
+ override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? =
140
+ deciding("shouldInterceptRequest", WEB_VIEW, WebResourceRequest::class.java)?.shouldInterceptRequest(view, request)
141
+
142
+ // Main frame only: subresource failures (an ad's 404) are the page's business.
143
+ override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) {
144
+ val description = error.description.toString()
145
+ if (request.isForMainFrame && !description.contains("ERR_ABORTED")) {
146
+ owner.reportError("network", request.url.toString(), error.errorCode, description)
147
+ }
148
+ observing("onReceivedError", WEB_VIEW, WebResourceRequest::class.java, WebResourceError::class.java) { it.onReceivedError(view, request, error) }
149
+ }
150
+
151
+ override fun onReceivedHttpError(view: WebView, request: WebResourceRequest, response: WebResourceResponse) {
152
+ if (request.isForMainFrame) owner.reportHttpError(request.url.toString(), response.statusCode)
153
+ observing("onReceivedHttpError", WEB_VIEW, WebResourceRequest::class.java, WebResourceResponse::class.java) { it.onReceivedHttpError(view, request, response) }
154
+ }
155
+
156
+ override fun onFormResubmission(view: WebView, dontResend: Message, resend: Message) {
157
+ val hook = deciding("onFormResubmission", WEB_VIEW, Message::class.java, Message::class.java)
158
+ if (hook != null) hook.onFormResubmission(view, dontResend, resend) else super.onFormResubmission(view, dontResend, resend)
159
+ }
160
+
161
+ // Best-effort URL tracking when WebView updates are disabled and NAVIGATION_LISTENER is missing.
162
+ override fun doUpdateVisitedHistory(view: WebView, url: String?, isReload: Boolean) {
163
+ if (!owner.hasNavigationListener && url != null) {
164
+ owner.url = url
165
+ owner.stateChanged()
166
+ }
167
+ observing("doUpdateVisitedHistory", WEB_VIEW, STRING, BOOLEAN) { it.doUpdateVisitedHistory(view, url, isReload) }
168
+ }
169
+
170
+ @SuppressLint("WebViewClientOnReceivedSslError") // because the core always cancels; it only reports the error
171
+ override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, sslError: SslError) {
172
+ val hook = deciding(
173
+ "onReceivedSslError", WEB_VIEW, SslErrorHandler::class.java, SslError::class.java,
174
+ lost = "the core doesn't cancel SSL errors or report them to onError"
175
+ )
176
+ if (hook != null) return hook.onReceivedSslError(view, handler, sslError)
177
+ handler.cancel()
178
+ // Also called for subresources (an ad image): only the main frame's URL is a page error. Without NavigationListener
179
+ // there's no pendingUrl: view.url shows a loadUrl in progress (back/forward stays unreported).
180
+ val mainFrame = if (owner.hasNavigationListener) setOf(owner.pendingUrl ?: owner.url) else setOf(view.url, allowedMainFrameUrl)
181
+ if (sslError.url in mainFrame) {
182
+ owner.reportError("ssl", sslError.url, sslError.primaryError, "SSL error ${sslError.primaryError}")
183
+ }
184
+ }
185
+
186
+ override fun onReceivedClientCertRequest(view: WebView, request: ClientCertRequest) {
187
+ val hook = deciding("onReceivedClientCertRequest", WEB_VIEW, ClientCertRequest::class.java)
188
+ if (hook != null) hook.onReceivedClientCertRequest(view, request) else super.onReceivedClientCertRequest(view, request)
189
+ }
190
+
191
+ // Basic and digest auth: a hook client, else cancel (the page shows its 401).
192
+ override fun onReceivedHttpAuthRequest(view: WebView, handler: HttpAuthHandler, host: String, realm: String) {
193
+ val hook = deciding("onReceivedHttpAuthRequest", WEB_VIEW, HttpAuthHandler::class.java, STRING, STRING)
194
+ if (hook != null) hook.onReceivedHttpAuthRequest(view, handler, host, realm) else handler.cancel()
195
+ }
196
+
197
+ override fun shouldOverrideKeyEvent(view: WebView, event: KeyEvent): Boolean =
198
+ deciding("shouldOverrideKeyEvent", WEB_VIEW, KeyEvent::class.java)?.shouldOverrideKeyEvent(view, event)
199
+ ?: super.shouldOverrideKeyEvent(view, event)
200
+
201
+ override fun onUnhandledKeyEvent(view: WebView, event: KeyEvent) {
202
+ super.onUnhandledKeyEvent(view, event)
203
+ observing("onUnhandledKeyEvent", WEB_VIEW, KeyEvent::class.java) { it.onUnhandledKeyEvent(view, event) }
204
+ }
205
+
206
+ override fun onScaleChanged(view: WebView, oldScale: Float, newScale: Float) =
207
+ observing("onScaleChanged", WEB_VIEW, FLOAT, FLOAT) { it.onScaleChanged(view, oldScale, newScale) }
208
+
209
+ override fun onReceivedLoginRequest(view: WebView, realm: String, account: String?, args: String?) =
210
+ observing("onReceivedLoginRequest", WEB_VIEW, STRING, STRING, STRING) { it.onReceivedLoginRequest(view, realm, account, args) }
211
+
212
+ override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {
213
+ // Returning true keeps the app alive; a stale WebView (already replaced) needs nothing more.
214
+ // Timed here: every WebView on the renderer hears of its death back to back, before any recovery runs.
215
+ val at = SystemClock.elapsedRealtime()
216
+ if (view === owner.webView) owner.mainHandler.post { owner.processGone(if (detail.didCrash()) "crash" else "memory", at) }
217
+ observing("onRenderProcessGone", WEB_VIEW, RenderProcessGoneDetail::class.java) { it.onRenderProcessGone(view, detail) }
218
+ return true
219
+ }
220
+
221
+ override fun onSafeBrowsingHit(view: WebView, request: WebResourceRequest, threatType: Int, callback: SafeBrowsingResponse) {
222
+ val hook = deciding("onSafeBrowsingHit", WEB_VIEW, WebResourceRequest::class.java, INT, SafeBrowsingResponse::class.java)
223
+ if (hook != null) hook.onSafeBrowsingHit(view, request, threatType, callback) else super.onSafeBrowsingHit(view, request, threatType, callback)
224
+ }
225
+ }
226
+
227
+ internal class ChromeClient(private val owner: MinimalWebView, private val navigation: MinimalWebViewNavigation) : WebChromeClient() {
228
+ private fun deciding(name: String, vararg types: Class<*>, lost: String? = null) =
229
+ owner.deciders.first(name, owner.chromeClients, lost) { it.overrides(name, *types) }
230
+
231
+ private inline fun observing(name: String, vararg types: Class<*>, block: (WebChromeClient) -> Unit) =
232
+ owner.chromeClients.forEach { if (it.overrides(name, *types)) block(it) }
233
+
234
+ override fun onCreateWindow(view: WebView, isDialog: Boolean, isUserGesture: Boolean, resultMsg: Message): Boolean =
235
+ deciding(
236
+ "onCreateWindow", WEB_VIEW, BOOLEAN, BOOLEAN, Message::class.java,
237
+ lost = "navigationRules, their defaults and onNavigationRequest don't apply to new windows"
238
+ )?.onCreateWindow(view, isDialog, isUserGesture, resultMsg)
239
+ ?: navigation.createWindow(isUserGesture, resultMsg)
240
+
241
+ // A hook client, else the app's prop (onFileRequest), else the system chooser (its intent ignores `capture`).
242
+ override fun onShowFileChooser(view: WebView, callback: ValueCallback<Array<Uri>>, params: FileChooserParams): Boolean {
243
+ val once = owner.fileUpload.hold(callback) // before the hook branch: a hook's chooser is held too
244
+ val hook = deciding(
245
+ "onShowFileChooser", WEB_VIEW, ValueCallback::class.java, FileChooserParams::class.java,
246
+ lost = "onFileRequest doesn't apply"
247
+ )
248
+ if (hook != null) return hook.onShowFileChooser(view, once, params)
249
+ owner.fileUpload.onShowFileChooser(once, params)
250
+ return true
251
+ }
252
+
253
+ // Without a hook client or the app's prop: deny (never grant device access by default).
254
+ override fun onPermissionRequest(request: PermissionRequest) {
255
+ val hook = deciding("onPermissionRequest", PermissionRequest::class.java, lost = "onPermissionRequest and the default deny don't apply")
256
+ when {
257
+ hook != null -> hook.onPermissionRequest(request)
258
+ !owner.permissions.onPermissionRequest(request) -> request.deny()
259
+ }
260
+ }
261
+
262
+ override fun onGeolocationPermissionsShowPrompt(origin: String, callback: GeolocationPermissions.Callback) {
263
+ val hook = deciding(
264
+ "onGeolocationPermissionsShowPrompt", STRING, GeolocationPermissions.Callback::class.java,
265
+ lost = "onPermissionRequest and the default deny don't apply to location"
266
+ )
267
+ when {
268
+ hook != null -> hook.onGeolocationPermissionsShowPrompt(origin, callback)
269
+ !owner.permissions.onGeolocationPrompt(origin, callback) -> callback.invoke(origin, false, false)
270
+ }
271
+ }
272
+
273
+ override fun onShowCustomView(view: View, callback: CustomViewCallback) {
274
+ val hook = deciding(
275
+ "onShowCustomView", View::class.java, CustomViewCallback::class.java,
276
+ lost = "the core's fullscreen and onFullscreenChange don't apply"
277
+ )
278
+ when {
279
+ hook != null -> hook.onShowCustomView(view, callback)
280
+ !owner.fullscreen.onShowCustomView(view, callback) -> callback.onCustomViewHidden()
281
+ }
282
+ }
283
+
284
+ override fun onHideCustomView() {
285
+ val hook = deciding("onHideCustomView")
286
+ if (hook != null) hook.onHideCustomView() else owner.fullscreen.onHideCustomView()
287
+ }
288
+
289
+ override fun onReceivedTitle(view: WebView, title: String?) {
290
+ owner.title = title ?: ""
291
+ owner.stateChanged()
292
+ observing("onReceivedTitle", WEB_VIEW, STRING) { it.onReceivedTitle(view, title) }
293
+ }
294
+
295
+ override fun onProgressChanged(view: WebView, newProgress: Int) {
296
+ owner.progress = newProgress / 100.0
297
+ owner.stateChanged()
298
+ observing("onProgressChanged", WEB_VIEW, INT) { it.onProgressChanged(view, newProgress) }
299
+ }
300
+
301
+ override fun onReceivedIcon(view: WebView, icon: Bitmap?) =
302
+ observing("onReceivedIcon", WEB_VIEW, Bitmap::class.java) { it.onReceivedIcon(view, icon) }
303
+
304
+ override fun onReceivedTouchIconUrl(view: WebView, url: String?, precomposed: Boolean) =
305
+ observing("onReceivedTouchIconUrl", WEB_VIEW, STRING, BOOLEAN) { it.onReceivedTouchIconUrl(view, url, precomposed) }
306
+
307
+ override fun onRequestFocus(view: WebView) {
308
+ super.onRequestFocus(view)
309
+ observing("onRequestFocus", WEB_VIEW) { it.onRequestFocus(view) }
310
+ }
311
+
312
+ override fun onCloseWindow(window: WebView?) {
313
+ super.onCloseWindow(window)
314
+ observing("onCloseWindow", WEB_VIEW) { it.onCloseWindow(window) }
315
+ }
316
+
317
+ override fun onJsAlert(view: WebView, url: String?, message: String?, result: JsResult): Boolean =
318
+ deciding("onJsAlert", WEB_VIEW, STRING, STRING, JsResult::class.java)?.onJsAlert(view, url, message, result)
319
+ ?: super.onJsAlert(view, url, message, result)
320
+
321
+ override fun onJsConfirm(view: WebView, url: String?, message: String?, result: JsResult): Boolean =
322
+ deciding("onJsConfirm", WEB_VIEW, STRING, STRING, JsResult::class.java)?.onJsConfirm(view, url, message, result)
323
+ ?: super.onJsConfirm(view, url, message, result)
324
+
325
+ override fun onJsPrompt(view: WebView, url: String?, message: String?, defaultValue: String?, result: JsPromptResult): Boolean =
326
+ deciding("onJsPrompt", WEB_VIEW, STRING, STRING, STRING, JsPromptResult::class.java)?.onJsPrompt(view, url, message, defaultValue, result)
327
+ ?: super.onJsPrompt(view, url, message, defaultValue, result)
328
+
329
+ override fun onJsBeforeUnload(view: WebView, url: String?, message: String?, result: JsResult): Boolean =
330
+ deciding("onJsBeforeUnload", WEB_VIEW, STRING, STRING, JsResult::class.java)?.onJsBeforeUnload(view, url, message, result)
331
+ ?: super.onJsBeforeUnload(view, url, message, result)
332
+
333
+ override fun onGeolocationPermissionsHidePrompt() {
334
+ super.onGeolocationPermissionsHidePrompt()
335
+ owner.permissions.onGeolocationPromptHidden()
336
+ observing("onGeolocationPermissionsHidePrompt") { it.onGeolocationPermissionsHidePrompt() }
337
+ }
338
+
339
+ override fun onPermissionRequestCanceled(request: PermissionRequest) {
340
+ super.onPermissionRequestCanceled(request)
341
+ owner.permissions.onPermissionRequestCanceled(request)
342
+ observing("onPermissionRequestCanceled", PermissionRequest::class.java) { it.onPermissionRequestCanceled(request) }
343
+ }
344
+
345
+ override fun onConsoleMessage(consoleMessage: ConsoleMessage): Boolean =
346
+ deciding("onConsoleMessage", ConsoleMessage::class.java)?.onConsoleMessage(consoleMessage)
347
+ ?: super.onConsoleMessage(consoleMessage)
348
+
349
+ override fun getDefaultVideoPoster(): Bitmap? =
350
+ deciding("getDefaultVideoPoster")?.defaultVideoPoster ?: super.getDefaultVideoPoster()
351
+
352
+ override fun getVideoLoadingProgressView(): View? =
353
+ deciding("getVideoLoadingProgressView")?.videoLoadingProgressView ?: super.getVideoLoadingProgressView()
354
+
355
+ override fun getVisitedHistory(callback: ValueCallback<Array<String>>) {
356
+ val hook = deciding("getVisitedHistory", ValueCallback::class.java)
357
+ if (hook != null) hook.getVisitedHistory(callback) else super.getVisitedHistory(callback)
358
+ }
359
+ }
@@ -0,0 +1,245 @@
1
+ package expo.modules.minimalwebview
2
+
3
+ import android.content.Context
4
+ import android.content.Intent
5
+ import android.net.Uri
6
+ import android.util.Log
7
+ import android.webkit.CookieManager
8
+ import android.webkit.WebChromeClient.FileChooserParams
9
+ import android.webkit.WebSettings
10
+ import android.webkit.WebView
11
+ import androidx.webkit.Profile
12
+ import androidx.webkit.ProfileStore
13
+ import androidx.webkit.WebViewCompat
14
+ import androidx.webkit.WebViewFeature
15
+ import androidx.webkit.WebViewOutcomeReceiver
16
+ import androidx.webkit.WebViewStartUpConfig
17
+ import androidx.webkit.WebViewStartUpResult
18
+ import androidx.webkit.WebViewStartupException
19
+ import expo.modules.kotlin.Promise
20
+ import expo.modules.kotlin.activityresult.AppContextActivityResultContract
21
+ import expo.modules.kotlin.activityresult.AppContextActivityResultLauncher
22
+ import expo.modules.kotlin.exception.Exceptions
23
+ import expo.modules.kotlin.exception.toCodedException
24
+ import expo.modules.kotlin.functions.Queues
25
+ import expo.modules.kotlin.modules.Module
26
+ import expo.modules.kotlin.modules.ModuleDefinition
27
+ import expo.modules.kotlin.records.Field
28
+ import expo.modules.kotlin.records.Record
29
+ import org.json.JSONArray
30
+ import org.json.JSONObject
31
+ import org.json.JSONTokener
32
+ import java.io.Serializable
33
+
34
+ /**
35
+ * Public only for Expo's autolinking.
36
+ * @suppress
37
+ */
38
+ class MinimalWebViewModule : Module() {
39
+ private var fileChooser: AppContextActivityResultLauncher<ChooserIntent, Array<Uri>?>? = null
40
+ private var chooserOpen = false
41
+
42
+ /**
43
+ * The system file chooser (ChromeClient.onShowFileChooser), one at a time app-wide: the launcher keeps one callback,
44
+ * so a request while one is open gets null at once, as does one before the launcher is registered or without an
45
+ * activity. Otherwise [onResult] gets the picked URIs, or null on cancel.
46
+ */
47
+ internal fun openFileChooser(intent: Intent, onResult: (Array<Uri>?) -> Unit) {
48
+ val launcher = fileChooser
49
+ if (launcher == null || chooserOpen) return onResult(null)
50
+ chooserOpen = true
51
+ try {
52
+ launcher.launch(ChooserIntent(intent)) {
53
+ chooserOpen = false
54
+ onResult(it)
55
+ }
56
+ } catch (e: RuntimeException) { // no activity opens it, no current activity, or the launcher was unregistered
57
+ chooserOpen = false
58
+ Log.w(TAG, "the file chooser can't open", e)
59
+ onResult(null)
60
+ }
61
+ }
62
+
63
+ override fun definition() = ModuleDefinition {
64
+ Name("MinimalWebView")
65
+
66
+ // 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
+ RegisterActivityContracts {
69
+ fileChooser = registerForActivityResult(FileChooserContract) { _, _ -> chooserOpen = false }
70
+ }
71
+
72
+ // Cookies live in memory until flushed; persist them before the process can be killed. Only once a WebView was
73
+ // made: CookieManager.getInstance() would otherwise start WebView, on the UI thread, in an app that never shows one.
74
+ OnActivityEntersBackground {
75
+ if (webViewCreated) flushCookies()
76
+ }
77
+
78
+ // Best effort: an error only means the first WebView starts WebView as before.
79
+ Function("warmUp") { warmUp(appContext.reactContext ?: throw Exceptions.ReactContextLost()) }
80
+
81
+ // ProfileStore wants the UI thread, and starts WebView there.
82
+ AsyncFunction("preconnect") { url: String -> preconnect(url) }.runOnQueue(Queues.MAIN)
83
+
84
+ AsyncFunction("setWebContentsDebuggingEnabled") { enabled: Boolean -> setWebContentsDebugging(enabled) }.runOnQueue(Queues.MAIN)
85
+
86
+ Constant("defaultUserAgent") {
87
+ WebSettings.getDefaultUserAgent(appContext.reactContext ?: throw Exceptions.ReactContextLost())
88
+ }
89
+
90
+ View(MinimalWebView::class) {
91
+ Events("onNavigationState", "onBridge", "onHookEvent", "onError", "onProcessGone", "onNavigation")
92
+
93
+ Prop("source") { view: MinimalWebView, source: WebViewSource? -> view.source = source }
94
+ Prop("navigationRules") { view: MinimalWebView, rules: List<Map<String, Any?>>? -> view.navigationRules = rules }
95
+ Prop("bridgeScript") { view: MinimalWebView, script: String? -> view.bridgeScript = script }
96
+ Prop("bridgeOrigins") { view: MinimalWebView, origins: List<String>? -> view.bridgeOrigins = origins }
97
+ Prop("hookOptions") { view: MinimalWebView, options: Map<String, Any?>? -> view.hookOptions = options.orEmpty() }
98
+ // The JSON is always an object (JS builds it).
99
+ Prop("settings") { view: MinimalWebView, json: String? -> view.settings = json?.let { JSONObject(it).toMap() } }
100
+ Prop("pullToRefresh") { view: MinimalWebView, value: Boolean? -> view.pullToRefresh = value ?: false }
101
+ Prop("injectedScripts") { view: MinimalWebView, value: List<InjectedScript>? -> view.injectedScripts = value }
102
+ Prop("requestHandlers") { view: MinimalWebView, value: List<String>? -> view.requestHandlers = value.orEmpty().toSet() }
103
+
104
+ OnViewDidUpdateProps { view: MinimalWebView -> view.applyProps() }
105
+ OnViewDestroys { view: MinimalWebView -> view.destroy() }
106
+
107
+ AsyncFunction("goBack") { view: MinimalWebView -> live(view) { it.goBack() } }.runOnQueue(Queues.MAIN)
108
+ AsyncFunction("goForward") { view: MinimalWebView -> live(view) { it.goForward() } }.runOnQueue(Queues.MAIN)
109
+ AsyncFunction("reload") { view: MinimalWebView -> view.retry() }.runOnQueue(Queues.MAIN)
110
+ AsyncFunction("stopLoading") { view: MinimalWebView -> live(view) { it.stopLoading() } }.runOnQueue(Queues.MAIN)
111
+ AsyncFunction("get") { view: MinimalWebView, path: String, promise: Promise ->
112
+ native(view, promise) { promise.resolve(view.platformSettings.get(path)) }
113
+ }.runOnQueue(Queues.MAIN)
114
+ AsyncFunction("call") { view: MinimalWebView, path: String, argsJson: String, promise: Promise ->
115
+ native(view, promise) {
116
+ view.platformSettings.call(path, fromJson(JSONArray(argsJson)) as List<Any?>) { json -> native(view, promise) { promise.resolve(json()) } }
117
+ }
118
+ // A call can change what the state shows (clearHistory, canGoBack); an unchanged state isn't sent.
119
+ view.stateChanged()
120
+ }.runOnQueue(Queues.MAIN)
121
+ AsyncFunction("bridgePost") { view: MinimalWebView, message: String -> view.bridgePost(message) }.runOnQueue(Queues.MAIN)
122
+ AsyncFunction("answer") { view: MinimalWebView, askId: Int, json: String ->
123
+ view.asks.answer(askId, fromJson(JSONTokener(json).nextValue()))
124
+ }.runOnQueue(Queues.MAIN)
125
+ AsyncFunction("hook") { view: MinimalWebView, name: String, method: String, args: String, promise: Promise ->
126
+ hook(view, name, method, args, promise)
127
+ }.runOnQueue(Queues.MAIN)
128
+ AsyncFunction("evaluate") { view: MinimalWebView, script: String, promise: Promise ->
129
+ view.evaluate(script) { result ->
130
+ result.fold(promise::resolve) { promise.reject(it.toCodedException()) }
131
+ }
132
+ }.runOnQueue(Queues.MAIN)
133
+ }
134
+ }
135
+ }
136
+
137
+ private fun preconnect(url: String) {
138
+ if (!WebViewFeature.isFeatureSupported(WebViewFeature.MULTI_PROFILE)) return
139
+ val profile = ProfileStore.getInstance().getOrCreateProfile(Profile.DEFAULT_PROFILE_NAME)
140
+ when {
141
+ WebViewFeature.isFeatureSupported(WebViewFeature.ENQUEUE_PRECONNECT) -> profile.enqueuePreconnect(url)
142
+ WebViewFeature.isFeatureSupported(WebViewFeature.PRECONNECT) -> profile.preconnect(url)
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Writes the cookies of the default profile and every other one to disk: a WebView on another `android.webView.profile`
148
+ * keeps its own.
149
+ */
150
+ private fun flushCookies() {
151
+ CookieManager.getInstance().flush()
152
+ if (!WebViewFeature.isFeatureSupported(WebViewFeature.MULTI_PROFILE)) return
153
+ val store = ProfileStore.getInstance()
154
+ store.allProfileNames.forEach { store.getProfile(it)?.cookieManager?.flush() }
155
+ }
156
+
157
+ /** Before the first WebView only stored, for each new WebView to apply: setting it now would start WebView. */
158
+ private fun setWebContentsDebugging(enabled: Boolean) {
159
+ webContentsDebugging = enabled
160
+ if (webViewCreated) WebView.setWebContentsDebuggingEnabled(enabled)
161
+ }
162
+
163
+ private fun warmUp(context: Context) {
164
+ val config = WebViewStartUpConfig.Builder { Thread(it, "WebViewWarmUp").start() }.build()
165
+ WebViewCompat.startUpWebView(context, config, object : WebViewOutcomeReceiver<WebViewStartUpResult, WebViewStartupException> {
166
+ override fun onResult(result: WebViewStartUpResult) = Unit
167
+
168
+ override fun onError(error: WebViewStartupException) {
169
+ Log.w(TAG, "WebView warm-up failed", error)
170
+ }
171
+ })
172
+ }
173
+
174
+ /** Runs [action] on the WebView, unless it's recovering: `webView` is then the destroyed one, and only reload acts, by building the new one. */
175
+ private fun live(view: MinimalWebView, action: (WebView) -> Unit) {
176
+ if (!view.recovering) action(view.webView)
177
+ }
178
+
179
+ private fun hook(view: MinimalWebView, name: String, method: String, args: String, promise: Promise) = native(view, promise) {
180
+ val handler = view.hookHandler(name, method)
181
+ ?: throw PlatformException("not_found", "no attached hook `$name` handles `$method`")
182
+ val reply = HookReply(
183
+ resolve = { native(view, promise) { promise.resolve(PlatformSettings.toJson(it)) } },
184
+ reject = { promise.reject("handler_error", it, null) }
185
+ )
186
+ try {
187
+ handler(fromJson(JSONArray(args)) as List<Any?>, reply)
188
+ } catch (e: Exception) {
189
+ reply.fail(e.message ?: e.toString())
190
+ }
191
+ }
192
+
193
+ /**
194
+ * Runs [body], which resolves [promise]. A [PlatformException] it throws rejects with its code, anything else with
195
+ * `native_error`, and a dead WebView with `unavailable`.
196
+ */
197
+ private inline fun native(view: MinimalWebView, promise: Promise, body: () -> Unit) =
198
+ if (view.recovering) {
199
+ promise.reject("unavailable", RECOVERING, null)
200
+ } else {
201
+ try {
202
+ body()
203
+ } catch (e: Exception) {
204
+ promise.reject((e as? PlatformException)?.code ?: "native_error", e.message, e)
205
+ }
206
+ }
207
+
208
+ /** Nested maps and lists, with JSON null as null and every number a Double, as Expo converts a JS value. */
209
+ private fun JSONObject.toMap(): Map<String, Any?> = keys().asSequence().associateWith { fromJson(get(it)) }
210
+
211
+ private fun fromJson(value: Any?): Any? = when (value) {
212
+ JSONObject.NULL -> null
213
+ is JSONObject -> value.toMap()
214
+ is JSONArray -> List(value.length()) { fromJson(value.get(it)) }
215
+ is Number -> value.toDouble()
216
+ else -> value
217
+ }
218
+
219
+ /** The chooser's intent. Serializable because the registry persists launch inputs; it never relaunches a restored one. */
220
+ private class ChooserIntent(@Transient val intent: Intent? = null) : Serializable
221
+
222
+ private object FileChooserContract : AppContextActivityResultContract<ChooserIntent, Array<Uri>?> {
223
+ override fun createIntent(context: Context, input: ChooserIntent) = checkNotNull(input.intent)
224
+
225
+ override fun parseResult(input: ChooserIntent, resultCode: Int, intent: Intent?): Array<Uri>? =
226
+ FileChooserParams.parseResult(resultCode, intent)
227
+ }
228
+
229
+ // Data classes, so the skip checks in applyProps compare them with ==. Every field is optional, as on iOS.
230
+
231
+ internal data class WebViewSource(
232
+ @Field val uri: String? = null,
233
+ @Field val headers: Map<String, String>? = null,
234
+ @Field val body: String? = null,
235
+ // Unused on Android: here so that a change loads the source again, as on iOS.
236
+ @Field val readAccessRoot: String? = null,
237
+ @Field val html: String? = null,
238
+ @Field val baseUrl: String? = null
239
+ ) : Record
240
+
241
+ internal data class InjectedScript(
242
+ @Field val code: String? = null,
243
+ @Field val allFrames: Boolean? = null
244
+ ) : Record
245
+