@dynamic-labs/legacy-react-native-extension 0.0.0 → 5.1.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 (76) hide show
  1. package/README.md +7 -0
  2. package/android/AndroidManifest.xml +1 -0
  3. package/android/EmbeddedWebViewController.kt +559 -0
  4. package/android/EmbeddedWebViewModule.kt +62 -0
  5. package/android/KeyStoreKeyManager.kt +154 -0
  6. package/android/KeychainModule.kt +71 -0
  7. package/android/build.gradle +38 -0
  8. package/android/dynamic/embeddedwebview/EmbeddedWebViewController.kt +559 -0
  9. package/android/dynamic/embeddedwebview/EmbeddedWebViewModule.kt +62 -0
  10. package/android/dynamic/keychain/KeyStoreKeyManager.kt +154 -0
  11. package/android/dynamic/keychain/KeychainModule.kt +71 -0
  12. package/android/embeddedwebview/EmbeddedWebViewController.kt +559 -0
  13. package/android/embeddedwebview/EmbeddedWebViewModule.kt +62 -0
  14. package/android/java/xyz/dynamic/embeddedwebview/EmbeddedWebViewController.kt +559 -0
  15. package/android/java/xyz/dynamic/embeddedwebview/EmbeddedWebViewModule.kt +62 -0
  16. package/android/java/xyz/dynamic/keychain/KeyStoreKeyManager.kt +154 -0
  17. package/android/java/xyz/dynamic/keychain/KeychainModule.kt +71 -0
  18. package/android/keychain/KeyStoreKeyManager.kt +154 -0
  19. package/android/keychain/KeychainModule.kt +71 -0
  20. package/android/main/AndroidManifest.xml +1 -0
  21. package/android/main/java/xyz/dynamic/embeddedwebview/EmbeddedWebViewController.kt +559 -0
  22. package/android/main/java/xyz/dynamic/embeddedwebview/EmbeddedWebViewModule.kt +62 -0
  23. package/android/main/java/xyz/dynamic/keychain/KeyStoreKeyManager.kt +154 -0
  24. package/android/main/java/xyz/dynamic/keychain/KeychainModule.kt +71 -0
  25. package/android/src/main/AndroidManifest.xml +1 -0
  26. package/android/src/main/java/xyz/dynamic/embeddedwebview/EmbeddedWebViewController.kt +559 -0
  27. package/android/src/main/java/xyz/dynamic/embeddedwebview/EmbeddedWebViewModule.kt +62 -0
  28. package/android/src/main/java/xyz/dynamic/keychain/KeyStoreKeyManager.kt +154 -0
  29. package/android/src/main/java/xyz/dynamic/keychain/KeychainModule.kt +71 -0
  30. package/android/xyz/dynamic/embeddedwebview/EmbeddedWebViewController.kt +559 -0
  31. package/android/xyz/dynamic/embeddedwebview/EmbeddedWebViewModule.kt +62 -0
  32. package/android/xyz/dynamic/keychain/KeyStoreKeyManager.kt +154 -0
  33. package/android/xyz/dynamic/keychain/KeychainModule.kt +71 -0
  34. package/expo-module.config.json +12 -0
  35. package/index.cjs +998 -0
  36. package/index.js +973 -0
  37. package/ios/EmbeddedWebViewController.swift +500 -0
  38. package/ios/EmbeddedWebViewModule.swift +69 -0
  39. package/ios/Keychain.podspec +15 -0
  40. package/ios/KeychainModule.swift +39 -0
  41. package/ios/SecureEnclaveKeyManager.swift +187 -0
  42. package/package.json +44 -1
  43. package/src/ReactNativeExtension/ReactNativeExtension.d.ts +64 -0
  44. package/src/ReactNativeExtension/index.d.ts +1 -0
  45. package/src/ReactNativeExtension/logNativeModuleAvailability.d.ts +19 -0
  46. package/src/ReactNativeExtension/setupKeychainHandler/index.d.ts +1 -0
  47. package/src/ReactNativeExtension/setupKeychainHandler/setupKeychainHandler.d.ts +2 -0
  48. package/src/ReactNativeExtension/setupPasskeyHandler/index.d.ts +1 -0
  49. package/src/ReactNativeExtension/setupPasskeyHandler/setupPasskeyHandler.d.ts +2 -0
  50. package/src/ReactNativeExtension/setupPlatformHandler/index.d.ts +1 -0
  51. package/src/ReactNativeExtension/setupPlatformHandler/setupPlatformHandler.d.ts +2 -0
  52. package/src/ReactNativeExtension/setupStorageHandler/index.d.ts +1 -0
  53. package/src/ReactNativeExtension/setupStorageHandler/setupStorageHandler.d.ts +2 -0
  54. package/src/ReactNativeExtension/setupTurnkeyPasskeyHandler/index.d.ts +1 -0
  55. package/src/ReactNativeExtension/setupTurnkeyPasskeyHandler/setupTurnkeyPasskeyHandler.d.ts +2 -0
  56. package/src/components/WebView/EmbeddedWebView/EmbeddedWebView.d.ts +13 -0
  57. package/src/components/WebView/EmbeddedWebView/index.d.ts +1 -0
  58. package/src/components/WebView/WebView.d.ts +37 -0
  59. package/src/components/WebView/WebView.styles.d.ts +26 -0
  60. package/src/components/WebView/index.d.ts +1 -0
  61. package/src/components/WebView/useMessageTransportWebViewBridge/index.d.ts +1 -0
  62. package/src/components/WebView/useMessageTransportWebViewBridge/useMessageTransportWebViewBridge.d.ts +6 -0
  63. package/src/components/WebView/useWebViewVisibility/index.d.ts +1 -0
  64. package/src/components/WebView/useWebViewVisibility/useWebViewVisibility.d.ts +4 -0
  65. package/src/components/WebView/utils/shouldAllowNavigation/index.d.ts +1 -0
  66. package/src/components/WebView/utils/shouldAllowNavigation/shouldAllowNavigation.d.ts +5 -0
  67. package/src/errors/WebViewFailedToLoadError.d.ts +1 -0
  68. package/src/index.d.ts +2 -0
  69. package/src/nativeModules/EmbeddedWebView.d.ts +68 -0
  70. package/src/nativeModules/Keychain.d.ts +23 -0
  71. package/src/nativeModules/index.d.ts +1 -0
  72. package/src/utils/logger.d.ts +2 -0
  73. package/turboModules/NativeDynamicWebView.ts +47 -0
  74. package/turboModules/NativeKeychain.ts +22 -0
  75. package/turboModules/NativeReactNativeManifest.ts +24 -0
  76. package/turboModules/NativeScreenshotProtection.ts +29 -0
package/README.md ADDED
@@ -0,0 +1,7 @@
1
+ # react-native-extension
2
+
3
+ This library was generated with [Nx](https://nx.dev).
4
+
5
+ ## Running unit tests
6
+
7
+ Run `nx test react-native-extension` to execute the unit tests via [Jest](https://jestjs.io).
@@ -0,0 +1 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android" />
@@ -0,0 +1,559 @@
1
+ package xyz.dynamic.embeddedwebview
2
+
3
+ import android.annotation.SuppressLint
4
+ import android.content.pm.ApplicationInfo
5
+ import android.graphics.Bitmap
6
+ import android.graphics.Color
7
+ import android.net.http.SslError
8
+ import android.os.Handler
9
+ import android.os.Looper
10
+ import android.view.View
11
+ import android.view.ViewGroup
12
+ import android.webkit.JavascriptInterface
13
+ import android.webkit.RenderProcessGoneDetail
14
+ import android.webkit.SslErrorHandler
15
+ import android.webkit.WebChromeClient
16
+ import android.webkit.WebResourceError
17
+ import android.webkit.WebResourceRequest
18
+ import android.webkit.WebResourceResponse
19
+ import android.webkit.WebView
20
+ import android.webkit.WebViewClient
21
+ import android.widget.FrameLayout
22
+ import expo.modules.kotlin.AppContext
23
+ import org.json.JSONObject
24
+ import java.util.UUID
25
+
26
+ private const val SCRIPT_HANDLER_NAME = "DynamicEmbeddedWebView"
27
+ private const val NAVIGATION_DECISION_TIMEOUT_MS = 5000L
28
+
29
+ // Singleton owning the in-app overlay view that hosts the WebView.
30
+ // Mirrors EmbeddedWebViewController on iOS.
31
+ //
32
+ // Lifecycle: lazy creation on the first setUrl call, retained until destroy()
33
+ // is invoked explicitly. The overlay is attached to the activity's decorView
34
+ // so it sits above the React Native root view (which lives at
35
+ // android.R.id.content). RN's reconciler does not traverse decorView, so the
36
+ // overlay is effectively outside the React Native ecosystem.
37
+ object EmbeddedWebViewController {
38
+ private val mainHandler = Handler(Looper.getMainLooper())
39
+
40
+ private var appContext: AppContext? = null
41
+ private var eventEmitter: ((String, Map<String, Any?>) -> Unit)? = null
42
+
43
+ private var overlayContainer: FrameLayout? = null
44
+ private var webView: WebView? = null
45
+ private var debuggingEnabled = false
46
+
47
+ private val pendingNavigationUrls = mutableMapOf<String, String>()
48
+ private val pendingTimeouts = mutableMapOf<String, Runnable>()
49
+
50
+ // Cleartext http is only permitted when the consuming app is debuggable.
51
+ // Release builds reject http top-frame and sub-frame navigations regardless
52
+ // of the JS allowlist, so a JS compromise cannot trick production into
53
+ // loading http content. Reads the application's FLAG_DEBUGGABLE — set
54
+ // automatically by the build system based on the manifest's debuggable
55
+ // attribute, which is true for debug builds and false for release.
56
+ private val allowsHttpScheme: Boolean
57
+ get() {
58
+ val flags = appContext?.reactContext?.applicationInfo?.flags ?: 0
59
+ return (flags and ApplicationInfo.FLAG_DEBUGGABLE) != 0
60
+ }
61
+
62
+ // Single-element bypass for re-entry into shouldOverrideUrlLoading.
63
+ // When JS approves a navigation, we call webView.loadUrl(url) which may
64
+ // re-trigger shouldOverrideUrlLoading on the same URL. We stash the URL
65
+ // here so the re-entry returns false (let WebView handle it) instead of
66
+ // prompting JS again — avoiding a potential approval loop.
67
+ private var bypassUrl: String? = null
68
+
69
+ // Origin pre-approved by `setUrl`. When `shouldOverrideUrlLoading` sees a
70
+ // top-frame navigation whose origin matches, it allows it immediately — no
71
+ // JS round-trip required. Cleared after first use so subsequent navigations
72
+ // still go through the JS allowlist.
73
+ private var preApprovedOrigin: String? = null
74
+
75
+ private var emitterToken: java.util.UUID? = null
76
+
77
+ // Module-side hook: assign the emitter under a token. The token lets
78
+ // detach() avoid clobbering an emitter that a newer attach() already
79
+ // installed — relevant during dev hot reloads where module instances
80
+ // briefly overlap.
81
+ fun attach(
82
+ context: AppContext,
83
+ emitter: (String, Map<String, Any?>) -> Unit,
84
+ ): java.util.UUID {
85
+ val token = java.util.UUID.randomUUID()
86
+ this.appContext = context
87
+ this.eventEmitter = emitter
88
+ this.emitterToken = token
89
+ return token
90
+ }
91
+
92
+ fun detach(token: java.util.UUID) {
93
+ if (this.emitterToken == token) {
94
+ this.eventEmitter = null
95
+ this.emitterToken = null
96
+ }
97
+ }
98
+
99
+ // ---- Public control surface (called from the Expo module) -----------------
100
+
101
+ fun setUrl(url: String) {
102
+ runOnMain {
103
+ // Match react-native-webview parity: a malformed URL must surface as a
104
+ // load error instead of silently no-op'ing, so the JS side throws
105
+ // WebViewFailedToLoadError.
106
+ if (!isValidUrl(url)) {
107
+ emitLoadError(
108
+ url = url,
109
+ code = -1,
110
+ domain = "EmbeddedWebViewInvalidUrl",
111
+ description = "Invalid URL: $url",
112
+ isProvisional = true,
113
+ )
114
+ return@runOnMain
115
+ }
116
+ val webView = ensureWebView()
117
+ if (webView == null) {
118
+ // ensureWebView() needs appContext.currentActivity to host the
119
+ // overlay; during early startup or backgrounding there may be none
120
+ // yet. Surface the failure instead of silently dropping the load —
121
+ // the JS retry engine treats this domain as transient and retries,
122
+ // by which point an activity usually exists.
123
+ emitLoadError(
124
+ url = url,
125
+ code = 0,
126
+ // The event-domain constant trips FireHog's generic high-entropy
127
+ // string detector; it is a public event name, not a secret.
128
+ domain = "EmbeddedWebViewNoActivity", // firehog:ignore
129
+ description = "No current activity available to host the embedded webview",
130
+ isProvisional = true,
131
+ )
132
+ return@runOnMain
133
+ }
134
+ // Pre-approve the origin so the first `shouldOverrideUrlLoading` call
135
+ // can skip the JS round-trip. On cold boot the JS thread may be too
136
+ // congested to respond within the navigation-decision timeout, silently
137
+ // cancelling the load.
138
+ preApprovedOrigin = originString(android.net.Uri.parse(url))
139
+ webView.loadUrl(url)
140
+ }
141
+ }
142
+
143
+ private fun isValidUrl(url: String): Boolean {
144
+ if (url.isBlank()) return false
145
+ val parsed = runCatching { android.net.Uri.parse(url) }.getOrNull() ?: return false
146
+ return !parsed.scheme.isNullOrBlank()
147
+ }
148
+
149
+ fun setVisible(visible: Boolean) {
150
+ runOnMain {
151
+ ensureWebView() ?: return@runOnMain
152
+ updateVisibility(visible)
153
+ }
154
+ }
155
+
156
+ fun setDebuggingEnabled(enabled: Boolean) {
157
+ runOnMain {
158
+ debuggingEnabled = enabled
159
+ WebView.setWebContentsDebuggingEnabled(enabled)
160
+ }
161
+ }
162
+
163
+ fun destroy() {
164
+ runOnMain { teardown() }
165
+ }
166
+
167
+ fun postMessage(message: String) {
168
+ runOnMain {
169
+ val webView = webView ?: return@runOnMain
170
+ val escaped = JSONObject.quote(message)
171
+ webView.evaluateJavascript(
172
+ "window.dispatchEvent(new MessageEvent('message', { data: $escaped }));",
173
+ null,
174
+ )
175
+ }
176
+ }
177
+
178
+ fun respondToShouldStartLoad(id: String, allow: Boolean) {
179
+ runOnMain {
180
+ val url = pendingNavigationUrls.remove(id) ?: return@runOnMain
181
+ pendingTimeouts.remove(id)?.let { mainHandler.removeCallbacks(it) }
182
+ if (allow) {
183
+ // Set the bypass before calling loadUrl so the re-entry into
184
+ // shouldOverrideUrlLoading returns false (let the WebView handle it
185
+ // natively) instead of prompting JS again for the same URL.
186
+ bypassUrl = url
187
+ webView?.loadUrl(url)
188
+ }
189
+ }
190
+ }
191
+
192
+ private fun emitLoadError(
193
+ url: String,
194
+ code: Int,
195
+ domain: String,
196
+ description: String,
197
+ isProvisional: Boolean,
198
+ ) {
199
+ eventEmitter?.invoke(
200
+ "onLoadError",
201
+ mapOf(
202
+ "url" to url,
203
+ "code" to code,
204
+ "domain" to domain,
205
+ "description" to description,
206
+ "isProvisional" to isProvisional,
207
+ ),
208
+ )
209
+ }
210
+
211
+ // ---- Lazy creation --------------------------------------------------------
212
+
213
+ @SuppressLint("SetJavaScriptEnabled", "JavascriptInterface")
214
+ private fun ensureWebView(): WebView? {
215
+ webView?.let { return it }
216
+
217
+ val activity = appContext?.currentActivity ?: return null
218
+
219
+ WebView.setWebContentsDebuggingEnabled(debuggingEnabled)
220
+
221
+ val webView = WebView(activity).apply {
222
+ setBackgroundColor(Color.TRANSPARENT)
223
+ settings.javaScriptEnabled = true
224
+ settings.domStorageEnabled = true
225
+ settings.databaseEnabled = true
226
+ settings.mediaPlaybackRequiresUserGesture = false
227
+ settings.allowFileAccess = false
228
+ settings.allowContentAccess = false
229
+ // Match react-native-webview's `setSupportMultipleWindows={false}`:
230
+ // refuse `target=_blank` / window.open popups so they don't escape
231
+ // the embedded webview into an unmanaged context.
232
+ settings.setSupportMultipleWindows(false)
233
+ addJavascriptInterface(JsBridge(), SCRIPT_HANDLER_NAME)
234
+ webViewClient = NavigationClient()
235
+ webChromeClient = NoPopupWebChromeClient()
236
+ }
237
+
238
+ val container = FrameLayout(activity).apply {
239
+ setBackgroundColor(Color.TRANSPARENT)
240
+ addView(
241
+ webView,
242
+ FrameLayout.LayoutParams(
243
+ ViewGroup.LayoutParams.MATCH_PARENT,
244
+ ViewGroup.LayoutParams.MATCH_PARENT,
245
+ ),
246
+ )
247
+ // INVISIBLE (not GONE) so the WebView stays attached to its window
248
+ // and its JS runtime keeps running. View.dispatchTouchEvent
249
+ // short-circuits for non-VISIBLE views, so touches pass through to
250
+ // the RN content underneath.
251
+ visibility = View.INVISIBLE
252
+ }
253
+
254
+ // Attach the overlay above the activity's content view. The decorView is
255
+ // the root of the activity's window — its children include the system bar
256
+ // backgrounds and android.R.id.content (where RN's root view lives).
257
+ // Adding our overlay last places it on top in draw order.
258
+ val decor = activity.window.decorView as ViewGroup
259
+ decor.addView(
260
+ container,
261
+ ViewGroup.LayoutParams(
262
+ ViewGroup.LayoutParams.MATCH_PARENT,
263
+ ViewGroup.LayoutParams.MATCH_PARENT,
264
+ ),
265
+ )
266
+
267
+ this.overlayContainer = container
268
+ this.webView = webView
269
+ return webView
270
+ }
271
+
272
+ private fun updateVisibility(visible: Boolean) {
273
+ val container = overlayContainer ?: return
274
+
275
+ // INVISIBLE (not GONE) when hidden: the WebView stays attached to its
276
+ // window so its JS runtime keeps processing fetch/XHR/postMessage,
277
+ // and View.dispatchTouchEvent short-circuits for non-VISIBLE views so
278
+ // touches pass through to the RN content beneath.
279
+ container.visibility = if (visible) View.VISIBLE else View.INVISIBLE
280
+
281
+ if (visible) {
282
+ // Defensively re-raise to the top of the decorView's draw order in case
283
+ // some other library inserted siblings above us after our initial attach.
284
+ container.bringToFront()
285
+ (container.parent as? View)?.invalidate()
286
+ container.requestFocus()
287
+ }
288
+ }
289
+
290
+ private fun teardown() {
291
+ overlayContainer?.let { container ->
292
+ (container.parent as? ViewGroup)?.removeView(container)
293
+ container.removeAllViews()
294
+ }
295
+ webView?.let {
296
+ it.stopLoading()
297
+ try {
298
+ it.removeJavascriptInterface(SCRIPT_HANDLER_NAME)
299
+ } catch (_: Exception) {
300
+ // No-op
301
+ }
302
+ it.webChromeClient = null
303
+ it.destroy()
304
+ }
305
+ overlayContainer = null
306
+ webView = null
307
+ pendingNavigationUrls.clear()
308
+ pendingTimeouts.values.forEach { mainHandler.removeCallbacks(it) }
309
+ pendingTimeouts.clear()
310
+ bypassUrl = null
311
+ preApprovedOrigin = null
312
+ }
313
+
314
+ private fun runOnMain(action: () -> Unit) {
315
+ if (Looper.myLooper() == Looper.getMainLooper()) {
316
+ action()
317
+ } else {
318
+ mainHandler.post(action)
319
+ }
320
+ }
321
+
322
+ // ---- Bridges --------------------------------------------------------------
323
+
324
+ private class JsBridge {
325
+ @JavascriptInterface
326
+ fun postMessage(message: String) {
327
+ mainHandler.post {
328
+ eventEmitter?.invoke("onMessage", mapOf("message" to message))
329
+ }
330
+ }
331
+ }
332
+
333
+ private class NavigationClient : WebViewClient() {
334
+ override fun shouldOverrideUrlLoading(
335
+ view: WebView,
336
+ request: WebResourceRequest,
337
+ ): Boolean {
338
+ val url = request.url.toString()
339
+ val scheme = request.url.scheme?.lowercase()
340
+ val httpAllowed = allowsHttpScheme
341
+
342
+ // Sub-frame requests are auto-allowed (matches iOS + JS allowlist).
343
+ // The trusted top-frame controls iframe content; iframes routinely
344
+ // start as `about:blank` and use `blob:` / `data:` / `about:srcdoc`
345
+ // URLs for legitimate functionality (WaaS MPC iframes, web workers,
346
+ // sandboxed inline content), so we defer iframe trust to the top-frame.
347
+ // shouldOverrideUrlLoading: false = let WebView load.
348
+ if (!request.isForMainFrame) return false
349
+
350
+ // Re-entry from our own loadUrl after JS approval: let the WebView
351
+ // handle it without a second JS round-trip.
352
+ if (url == bypassUrl) {
353
+ bypassUrl = null
354
+ return false
355
+ }
356
+
357
+ // Defense-in-depth: reject non-https top-frame schemes before prompting
358
+ // JS. The JS allowlist would also reject these, but a JS bug must not be
359
+ // enough to load `javascript:` / `file:` / `data:` / custom schemes.
360
+ // http is permitted only in debug builds.
361
+ val isAllowedTopFrameScheme =
362
+ scheme == "https" || (httpAllowed && scheme == "http")
363
+ if (!isAllowedTopFrameScheme) {
364
+ preApprovedOrigin = null
365
+ emitLoadError(
366
+ url = url,
367
+ code = -1,
368
+ domain = "EmbeddedWebViewBlockedScheme",
369
+ description = "Blocked navigation to disallowed scheme: $url",
370
+ isProvisional = true,
371
+ )
372
+ return true
373
+ }
374
+
375
+ // Fast-path: if the URL's origin matches the pre-approved origin (set
376
+ // by `setUrl`), allow immediately. This eliminates the cold-boot race
377
+ // where the JS thread is too congested to respond to
378
+ // `onShouldStartLoad` within the navigation-decision timeout.
379
+ val approved = preApprovedOrigin
380
+ if (approved != null && approved == originString(request.url)) {
381
+ preApprovedOrigin = null
382
+ bypassUrl = url
383
+ return false
384
+ }
385
+
386
+ val id = UUID.randomUUID().toString()
387
+ pendingNavigationUrls[id] = url
388
+
389
+ val timeout = Runnable {
390
+ // Default-cancel on timeout: drop the stashed URL and surface as a load
391
+ // error so JS sees the timeout (matches iOS's cancellation semantics
392
+ // but adds an explicit signal — iOS gets WebKitErrorDomain 102, which
393
+ // is filtered out, so neither side emits a network error).
394
+ if (pendingNavigationUrls.remove(id) != null) {
395
+ pendingTimeouts.remove(id)
396
+ emitLoadError(
397
+ url = url,
398
+ code = -1,
399
+ domain = "EmbeddedWebViewNavigationTimeout",
400
+ description = "Navigation decision timed out after ${NAVIGATION_DECISION_TIMEOUT_MS}ms",
401
+ isProvisional = true,
402
+ )
403
+ }
404
+ }
405
+ pendingTimeouts[id] = timeout
406
+ mainHandler.postDelayed(timeout, NAVIGATION_DECISION_TIMEOUT_MS)
407
+
408
+ eventEmitter?.invoke(
409
+ "onShouldStartLoad",
410
+ mapOf(
411
+ "id" to id,
412
+ "url" to url,
413
+ "isTopFrame" to true,
414
+ ),
415
+ )
416
+
417
+ // Cancel; if JS allows, respondToShouldStartLoad re-invokes loadUrl.
418
+ return true
419
+ }
420
+
421
+ override fun onPageStarted(view: WebView, url: String?, favicon: Bitmap?) {
422
+ super.onPageStarted(view, url, favicon)
423
+ // Inject the ReactNativeWebView polyfill so the webview-controller's
424
+ // existing outbound code (window.ReactNativeWebView.postMessage) routes
425
+ // through our JavaScriptInterface — same surface as iOS.
426
+ val polyfill =
427
+ "(function() {" +
428
+ "if (window.ReactNativeWebView) return;" +
429
+ "window.ReactNativeWebView = {" +
430
+ "postMessage: function(message) {" +
431
+ "window." + SCRIPT_HANDLER_NAME + ".postMessage(message);" +
432
+ "}" +
433
+ "};" +
434
+ "})();"
435
+ view.evaluateJavascript(polyfill, null)
436
+
437
+ eventEmitter?.invoke(
438
+ "onLoadStart",
439
+ mapOf("url" to (url ?: "")),
440
+ )
441
+ }
442
+
443
+ override fun onPageCommitVisible(view: WebView, url: String?) {
444
+ super.onPageCommitVisible(view, url)
445
+ // Analogue of iOS WKNavigationDelegate.didCommit: fired when the first
446
+ // pixels of the new document hit the screen — i.e. the response has
447
+ // committed and rendering has started. Lets the JS phase timer
448
+ // distinguish "request still in flight" from "request landed but page
449
+ // not yet finished".
450
+ eventEmitter?.invoke(
451
+ "onLoad",
452
+ mapOf("url" to (url ?: "")),
453
+ )
454
+ }
455
+
456
+ override fun onPageFinished(view: WebView, url: String?) {
457
+ super.onPageFinished(view, url)
458
+ eventEmitter?.invoke(
459
+ "onLoadEnd",
460
+ mapOf("url" to (url ?: "")),
461
+ )
462
+ }
463
+
464
+ override fun onReceivedError(
465
+ view: WebView,
466
+ request: WebResourceRequest,
467
+ error: WebResourceError,
468
+ ) {
469
+ if (!request.isForMainFrame) return
470
+ emitLoadError(
471
+ url = request.url.toString(),
472
+ code = error.errorCode,
473
+ domain = "EmbeddedWebViewLoadError",
474
+ description = error.description?.toString().orEmpty(),
475
+ isProvisional = true,
476
+ )
477
+ }
478
+
479
+ override fun onReceivedHttpError(
480
+ view: WebView,
481
+ request: WebResourceRequest,
482
+ errorResponse: WebResourceResponse,
483
+ ) {
484
+ if (!request.isForMainFrame) return
485
+ emitLoadError(
486
+ url = request.url.toString(),
487
+ code = errorResponse.statusCode,
488
+ domain = "EmbeddedWebViewHttpError",
489
+ description = errorResponse.reasonPhrase ?: "HTTP ${errorResponse.statusCode}",
490
+ isProvisional = false,
491
+ )
492
+ }
493
+
494
+ override fun onReceivedSslError(
495
+ view: WebView,
496
+ handler: SslErrorHandler,
497
+ error: SslError,
498
+ ) {
499
+ // Always reject — never proceed past an SSL error. Default
500
+ // WebViewClient already cancels but emits no event; surface it so the
501
+ // SDK's load-error path runs.
502
+ handler.cancel()
503
+ emitLoadError(
504
+ url = error.url ?: view.url ?: "",
505
+ code = error.primaryError,
506
+ domain = "EmbeddedWebViewSslError",
507
+ description = "SSL error: ${error.primaryError}",
508
+ isProvisional = true,
509
+ )
510
+ }
511
+
512
+ override fun onRenderProcessGone(
513
+ view: WebView,
514
+ detail: RenderProcessGoneDetail,
515
+ ): Boolean {
516
+ emitLoadError(
517
+ url = view.url ?: "",
518
+ code = -1,
519
+ domain = "EmbeddedWebViewProcessTerminated",
520
+ description = "WebContent process terminated",
521
+ isProvisional = false,
522
+ )
523
+ // Returning true tells the system we've handled it so the host process
524
+ // is not killed. The webView is in an unusable state; we tear it down.
525
+ runOnMain { teardown() }
526
+ return true
527
+ }
528
+ }
529
+
530
+ // Extract the scheme + host + port origin from a URI (e.g.
531
+ // "https://webview.dynamicauth.com"). Returns null for URIs without a host.
532
+ // Default ports (443 for HTTPS, 80 for HTTP) are omitted so that
533
+ // "https://example.com" and "https://example.com:443" produce the same
534
+ // origin string.
535
+ private fun originString(uri: android.net.Uri?): String? {
536
+ val scheme = uri?.scheme ?: return null
537
+ val host = uri.host ?: return null
538
+ val port = uri.port
539
+
540
+ val shouldIncludePort = port != -1 &&
541
+ !((scheme == "https" && port == 443) || (scheme == "http" && port == 80))
542
+
543
+ return if (shouldIncludePort) "$scheme://$host:$port" else "$scheme://$host"
544
+ }
545
+
546
+ // Refuse target=_blank / window.open popups (matches react-native-webview's
547
+ // `setSupportMultipleWindows={false}` semantics: there's nowhere reasonable
548
+ // to open the new window inside the overlay).
549
+ private class NoPopupWebChromeClient : WebChromeClient() {
550
+ override fun onCreateWindow(
551
+ view: WebView,
552
+ isDialog: Boolean,
553
+ isUserGesture: Boolean,
554
+ resultMsg: android.os.Message?,
555
+ ): Boolean {
556
+ return false
557
+ }
558
+ }
559
+ }
@@ -0,0 +1,62 @@
1
+ package xyz.dynamic.embeddedwebview
2
+
3
+ import expo.modules.kotlin.modules.Module
4
+ import expo.modules.kotlin.modules.ModuleDefinition
5
+ import java.util.UUID
6
+
7
+ class EmbeddedWebViewModule : Module() {
8
+ private var emitterToken: UUID? = null
9
+
10
+ override fun definition() = ModuleDefinition {
11
+ Name("EmbeddedWebView")
12
+
13
+ Events(
14
+ "onMessage",
15
+ "onShouldStartLoad",
16
+ "onLoadError",
17
+ "onLoadStart",
18
+ "onLoad",
19
+ "onLoadEnd",
20
+ )
21
+
22
+ OnCreate {
23
+ emitterToken = EmbeddedWebViewController.attach(appContext) { name, payload ->
24
+ sendEvent(name, payload)
25
+ }
26
+ }
27
+
28
+ OnDestroy {
29
+ // Only clear if our emitter is still the live one. Prevents a stale
30
+ // OnDestroy (e.g. during dev hot reload after a newer OnCreate already
31
+ // ran) from nulling the active emitter.
32
+ emitterToken?.let { token ->
33
+ EmbeddedWebViewController.detach(token)
34
+ emitterToken = null
35
+ }
36
+ }
37
+
38
+ AsyncFunction("setUrl") { url: String ->
39
+ EmbeddedWebViewController.setUrl(url)
40
+ }
41
+
42
+ AsyncFunction("setVisible") { visible: Boolean ->
43
+ EmbeddedWebViewController.setVisible(visible)
44
+ }
45
+
46
+ AsyncFunction("setDebuggingEnabled") { enabled: Boolean ->
47
+ EmbeddedWebViewController.setDebuggingEnabled(enabled)
48
+ }
49
+
50
+ AsyncFunction("destroy") {
51
+ EmbeddedWebViewController.destroy()
52
+ }
53
+
54
+ AsyncFunction("postMessage") { message: String ->
55
+ EmbeddedWebViewController.postMessage(message)
56
+ }
57
+
58
+ AsyncFunction("respondToShouldStartLoad") { id: String, allow: Boolean ->
59
+ EmbeddedWebViewController.respondToShouldStartLoad(id, allow)
60
+ }
61
+ }
62
+ }