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,99 @@
1
+ import UIKit
2
+ import WebKit
3
+
4
+ /// JS alert, confirm and prompt as UIAlertControllers. Android's WebChromeClient shows them by default.
5
+ /// WebKit requires each completion handler to be called exactly once, including when no dialog can be shown.
6
+ extension MinimalWebView: WKUIDelegate {
7
+ func webView(
8
+ _ webView: WKWebView,
9
+ runJavaScriptAlertPanelWithMessage message: String,
10
+ initiatedByFrame frame: WKFrameInfo,
11
+ completionHandler: @escaping @MainActor () -> Void
12
+ ) {
13
+ let alert = UIAlertController(title: dialogTitle(frame), message: message, preferredStyle: .alert)
14
+ alert.addAction(action("OK", .default) { completionHandler() })
15
+ showDialog(alert, cancel: completionHandler)
16
+ }
17
+
18
+ func webView(
19
+ _ webView: WKWebView,
20
+ runJavaScriptConfirmPanelWithMessage message: String,
21
+ initiatedByFrame frame: WKFrameInfo,
22
+ completionHandler: @escaping @MainActor (Bool) -> Void
23
+ ) {
24
+ let alert = UIAlertController(title: dialogTitle(frame), message: message, preferredStyle: .alert)
25
+ alert.addAction(action("Cancel", .cancel) { completionHandler(false) })
26
+ alert.addAction(action("OK", .default) { completionHandler(true) })
27
+ showDialog(alert) { completionHandler(false) }
28
+ }
29
+
30
+ func webView(
31
+ _ webView: WKWebView,
32
+ runJavaScriptTextInputPanelWithPrompt prompt: String,
33
+ defaultText: String?,
34
+ initiatedByFrame frame: WKFrameInfo,
35
+ completionHandler: @escaping @MainActor (String?) -> Void
36
+ ) {
37
+ let alert = UIAlertController(title: dialogTitle(frame), message: prompt, preferredStyle: .alert)
38
+ alert.addTextField { $0.text = defaultText }
39
+ alert.addAction(action("Cancel", .cancel) { completionHandler(nil) })
40
+ alert.addAction(action("OK", .default) { [weak alert] in completionHandler(alert?.textFields?.first?.text ?? "") })
41
+ showDialog(alert) { completionHandler(nil) }
42
+ }
43
+
44
+ /// Camera and microphone, for the main frame of a page with an origin: a subframe or an opaque page is denied. WebKit
45
+ /// asks the OS itself, with the app's Info.plist strings; a grant from `onPermissionRequest` skips only WebKit's own
46
+ /// prompt.
47
+ func webView(
48
+ _ webView: WKWebView,
49
+ requestMediaCapturePermissionFor origin: WKSecurityOrigin,
50
+ initiatedByFrame frame: WKFrameInfo,
51
+ type: WKMediaCaptureType,
52
+ decisionHandler: @escaping @MainActor (WKPermissionDecision) -> Void
53
+ ) {
54
+ let requester = OriginRules.origin(of: origin)
55
+ guard frame.isMainFrame, requester != "null" else { return decisionHandler(.deny) }
56
+ guard requestHandlers.contains("onPermissionRequest") else { return decisionHandler(.prompt) }
57
+ let resources: [String] = switch type {
58
+ case .camera: ["camera"]
59
+ case .microphone: ["microphone"]
60
+ default: ["camera", "microphone"]
61
+ }
62
+ asks.ask("core", "onPermissionRequest", ["origin": requester, "resources": resources]) { answer in
63
+ decisionHandler(answer as? Bool == true ? .grant : .deny)
64
+ }
65
+ }
66
+
67
+ /// The frame's host; one without a host (an opaque origin, such as a `data:` or sandboxed frame's, or `file:`) gets
68
+ /// "JavaScript", as Android titles a `data:` page's dialogs, so it doesn't look like the app's own alert.
69
+ private func dialogTitle(_ frame: WKFrameInfo) -> String {
70
+ let host = frame.securityOrigin.host
71
+ return host.isEmpty ? "JavaScript" : host
72
+ }
73
+
74
+ func dismissDialog() {
75
+ guard let current = dialog else { return }
76
+ dialog = nil
77
+ current.controller.dismiss(animated: false)
78
+ current.cancel()
79
+ }
80
+
81
+ private func action(_ title: String, _ style: UIAlertAction.Style, _ complete: @escaping () -> Void) -> UIAlertAction {
82
+ UIAlertAction(title: title, style: style) { [weak self] _ in
83
+ self?.dialog = nil
84
+ complete()
85
+ }
86
+ }
87
+
88
+ /// From the top of this view's window. A controller still presenting (one being dismissed) or itself being presented
89
+ /// can't present: UIKit only logs it and the page would stay blocked, so the dialog is cancelled instead.
90
+ private func showDialog(_ alert: UIAlertController, cancel: @escaping () -> Void) {
91
+ var top = window?.rootViewController
92
+ while let next = top?.presentedViewController, !next.isBeingDismissed { top = next }
93
+ guard dialog == nil, let presenter = top, presenter.presentedViewController == nil, !presenter.isBeingPresented else {
94
+ return cancel()
95
+ }
96
+ dialog = (alert, cancel)
97
+ presenter.present(alert, animated: true)
98
+ }
99
+ }
@@ -0,0 +1,244 @@
1
+ import UIKit
2
+ import UIKit.UIGestureRecognizerSubclass
3
+ import WebKit
4
+
5
+ /// Navigation rules, `ask`, new windows and external opening. The decision handler is held while JS answers an
6
+ /// `ask`, called exactly once, and blocked after 1 s or when the WebView goes away.
7
+ extension MinimalWebView {
8
+ func decideNavigation(_ action: WKNavigationAction, decide: @escaping @MainActor (WKNavigationActionPolicy) -> Void) {
9
+ guard let target = action.request.url else { return decide(allowInPlace) }
10
+ // New windows are decided in createWebViewWith; history steps, reloads, form POSTs and our own loads skip the
11
+ // rules, as on Android (shouldOverrideUrlLoading is not called for them).
12
+ guard let targetFrame = action.targetFrame else { return decide(allowInPlace) }
13
+ let mainFrame = targetFrame.isMainFrame
14
+ let own = mainFrame && programmaticUrl.map { Loads.sameURL($0, target) } == true
15
+ if own || action.navigationType == .backForward || action.navigationType == .reload
16
+ || action.request.httpMethod == "POST" {
17
+ if own { programmaticUrl = nil }
18
+ return decide(allowInPlace)
19
+ }
20
+ let request = NavigationRules.Request(
21
+ url: target.absoluteString, mainFrame: mainFrame, newWindow: false, userInitiated: userInitiated(action)
22
+ )
23
+ // A navigation WebKit marks as a download (`<a download>`, blob:). One no hook takes (no onDownload) is dropped:
24
+ // .allow would show it as a page.
25
+ let download = action.shouldPerformDownload && requestHandlers.contains("onDownload")
26
+ let dropped = action.shouldPerformDownload && !download
27
+ run(request) { [weak self] allowed in
28
+ guard allowed else { return decide(.cancel) }
29
+ if dropped {
30
+ self?.openDownload(target)
31
+ return decide(.cancel)
32
+ }
33
+ decide(download ? .download : allowInPlace)
34
+ }
35
+ }
36
+
37
+ /// Whether a user gesture started `action`: a link activation right after a tap on this view (`Taps`). WebKit reports
38
+ /// every navigation with a triggering event as `.linkActivated` (NavigationAction.cpp's navigationType), a link a
39
+ /// script clicks (`element.click()`) too, and no public WKNavigationAction property tells a real one apart. VoiceOver
40
+ /// and Switch Control activate a link with no touch: while either runs, a link activation counts on its own. A
41
+ /// hardware keyboard's doesn't count.
42
+ private func userInitiated(_ action: WKNavigationAction) -> Bool {
43
+ action.navigationType == .linkActivated
44
+ && (taps.recent || UIAccessibility.isVoiceOverRunning || UIAccessibility.isSwitchControlRunning)
45
+ }
46
+
47
+ /// A download no `onDownload` takes.
48
+ func openDownload(_ url: URL) {
49
+ guard ["http", "https"].contains(url.scheme?.lowercased()) else { return }
50
+ let request = NavigationRules.Request(url: url.absoluteString, mainFrame: true, newWindow: false, userInitiated: false)
51
+ finish(request, "external", nil) { _ in }
52
+ }
53
+
54
+ /// window.open and target=_blank. Never a second WKWebView: a popup model (presenting and closing a child,
55
+ /// `window.opener`, its own rules and bridge) is more than almost any app wants.
56
+ func webView(
57
+ _ webView: WKWebView,
58
+ createWebViewWith configuration: WKWebViewConfiguration,
59
+ for action: WKNavigationAction,
60
+ windowFeatures: WKWindowFeatures
61
+ ) -> WKWebView? {
62
+ let tapped = userInitiated(action)
63
+ guard let target = action.request.url?.absoluteString, !target.isEmpty, target != "about:blank" else {
64
+ return WindowCatcher.window(configuration) { [weak self] request in self?.openWindow(request, tapped) }
65
+ }
66
+ openWindow(action.request, tapped)
67
+ return nil
68
+ }
69
+
70
+ private func openWindow(_ request: URLRequest, _ userInitiated: Bool) {
71
+ guard let target = request.url else { return }
72
+ // This load is the app's, past WebKit's limits on what a page may load, so only an http(s) POST skips the rules.
73
+ if request.httpMethod == "POST", ["http", "https"].contains(target.scheme?.lowercased()) {
74
+ return loadProgrammatic(request)
75
+ }
76
+ let window = NavigationRules.Request(
77
+ url: target.absoluteString, mainFrame: true, newWindow: true, userInitiated: userInitiated
78
+ )
79
+ run(window) { [weak self] allowed in
80
+ if allowed { self?.loadProgrammatic(request) }
81
+ }
82
+ }
83
+
84
+ /// Applies the rules (and `ask`) to a request and reports the outcome; `completion` gets whether to load it here.
85
+ private func run(_ request: NavigationRules.Request, completion: @escaping (Bool) -> Void) {
86
+ // A URL an `ask` allowed is not asked again until the next main-frame commit (redirect loops). Without an
87
+ // onNavigationRequest prop nobody could allow it.
88
+ // WebKit has no redirect flag, so a tap on that URL isn't asked again either; Android skips only redirects.
89
+ let decision = NavigationRules.decide(
90
+ navigationRules, request, asked: askedAndAllowed[request.mainFrame] ?? [],
91
+ canAsk: requestHandlers.contains("onNavigationRequest")
92
+ )
93
+ guard decision.action == "ask" else {
94
+ finish(request, decision.action, decision.rule, completion)
95
+ return
96
+ }
97
+ let id = asks.ask("core", "onNavigationRequest", request.payload) { [weak self] answer in
98
+ // The view can be gone: the decision handler must still be called.
99
+ guard let self else { return completion(false) }
100
+ let action = NavigationRules.answer(answer)
101
+ if action == "allow" { self.askedAndAllowed[request.mainFrame, default: []].insert(request.url) }
102
+ self.finish(request, action, decision.rule, completion)
103
+ }
104
+ // Unanswered after the timeout: block.
105
+ DispatchQueue.main.asyncAfter(deadline: .now() + askTimeout) { [weak self] in
106
+ self?.asks.cancel(id)
107
+ }
108
+ }
109
+
110
+ private func finish(_ request: NavigationRules.Request, _ action: String, _ rule: Int?, _ completion: (Bool) -> Void) {
111
+ completion(action == "allow")
112
+ guard action == "external" else { return report(request, action, rule) }
113
+ guard requestHandlers.contains("onOpenExternal") else { return open(request, rule) }
114
+ // A page that moved on first answers nil, which counts as opened. No timeout: nothing waits for the answer.
115
+ asks.ask("core", "onOpenExternal", request.payload) { [weak self] answer in
116
+ if answer as? Bool == false { self?.open(request, rule) } else { self?.report(request, "external", rule) }
117
+ }
118
+ }
119
+
120
+ /// Opens an `external` URL outside the WebView. As on Android, one that nothing opens is reported as blocked.
121
+ private func open(_ request: NavigationRules.Request, _ rule: Int?) {
122
+ guard let url = URL(string: request.url) else { return report(request, "block", rule) }
123
+ UIApplication.shared.open(url) { [weak self] opened in self?.report(request, opened ? "external" : "block", rule) }
124
+ }
125
+
126
+ private func report(_ request: NavigationRules.Request, _ action: String, _ rule: Int?) {
127
+ guard requestHandlers.contains("onNavigation") else { return }
128
+ onNavigation(request.payload.merging(["action": action, "rule": rule as Any? ?? NSNull()]) { $1 })
129
+ }
130
+ }
131
+
132
+ private let askTimeout: TimeInterval = 1
133
+
134
+ /// The window `window.open('')` (or about:blank) opens, which a page navigates later (`w.location = url`), as async
135
+ /// popup payment buttons do. WebKit needs a WKWebView for it, made from the configuration it passes (it requires that
136
+ /// object). This one is never shown: it cancels its first navigation and hands the request on, then goes; one that
137
+ /// hasn't navigated within 5 s, or that the page closes, goes unused.
138
+ private final class WindowCatcher: NSObject, WKNavigationDelegate, WKUIDelegate {
139
+ private var child: WKWebView?
140
+ private var caught: ((URLRequest) -> Void)?
141
+
142
+ static func window(_ configuration: WKWebViewConfiguration, caught: @escaping (URLRequest) -> Void) -> WKWebView {
143
+ let catcher = WindowCatcher()
144
+ let child = WKWebView(frame: .zero, configuration: configuration)
145
+ child.navigationDelegate = catcher
146
+ child.uiDelegate = catcher
147
+ (catcher.child, catcher.caught) = (child, caught)
148
+ // The view's delegates are weak: the timer holds the catcher, and the catcher the view until it lets it go.
149
+ DispatchQueue.main.asyncAfter(deadline: .now() + newWindowTimeout) { catcher.drop() }
150
+ return child
151
+ }
152
+
153
+ func webView(
154
+ _ webView: WKWebView,
155
+ decidePolicyFor action: WKNavigationAction,
156
+ decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void
157
+ ) {
158
+ guard action.request.url?.absoluteString != "about:blank" else { return decisionHandler(.allow) }
159
+ decisionHandler(.cancel)
160
+ let caught = self.caught
161
+ drop()
162
+ caught?(action.request)
163
+ }
164
+
165
+ func webViewDidClose(_ webView: WKWebView) {
166
+ drop()
167
+ }
168
+
169
+ /// The view goes a turn later: this can run inside its own callback.
170
+ private func drop() {
171
+ caught = nil
172
+ DispatchQueue.main.async { [child] in withExtendedLifetime(child) {} }
173
+ child = nil
174
+ }
175
+ }
176
+
177
+ private let newWindowTimeout: TimeInterval = 5
178
+
179
+ /// WebKit's private `_WKNavigationActionPolicyAllowWithoutTryingAppLink` (iOS 9+), as Firefox for iOS uses it: `.allow`
180
+ /// would hand a tapped link to another host to an installed app that claims it as a universal link, which Android's
181
+ /// WebView never does, so the same rules would split the platforms. Hand-off is an explicit `external` rule. The value
182
+ /// goes to WebKit unchecked on every OS: an NS_ENUM's `init(rawValue:)` accepts any value, so `?? .allow` only
183
+ /// satisfies the type, and nothing falls back if WebKit drops the value; only an app that claims a domain could tell.
184
+ private let allowInPlace = WKNavigationActionPolicy(rawValue: WKNavigationActionPolicy.allow.rawValue + 2) ?? .allow
185
+
186
+ /// When a tap on the WKWebView last ended, for `userInitiated`. It only watches the view's touches: it never
187
+ /// recognizes, so it cancels, delays and prevents nothing (scrolling, links, text selection and the pull-to-refresh
188
+ /// control work as without it), and it fails at each touch's end, or as soon as the touch scrolls.
189
+ final class Taps: UIGestureRecognizer, UIGestureRecognizerDelegate {
190
+ /// In system uptime, a clock the device time doesn't move.
191
+ private var lastTap: TimeInterval = -.infinity
192
+
193
+ override init(target: Any?, action: Selector?) {
194
+ super.init(target: target, action: action)
195
+ cancelsTouchesInView = false
196
+ delaysTouchesEnded = false
197
+ delegate = self
198
+ }
199
+
200
+ /// A tap ended within `tapWindow`.
201
+ var recent: Bool { ProcessInfo.processInfo.systemUptime - lastTap <= tapWindow }
202
+
203
+ override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
204
+ super.touchesMoved(touches, with: event)
205
+ if scrolls(touches) { state = .failed }
206
+ }
207
+
208
+ override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
209
+ super.touchesEnded(touches, with: event)
210
+ if !scrolls(touches) { lastTap = ProcessInfo.processInfo.systemUptime }
211
+ state = .failed
212
+ }
213
+
214
+ override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) {
215
+ super.touchesCancelled(touches, with: event)
216
+ state = .failed
217
+ }
218
+
219
+ /// A touch that scrolls or zooms the page, or a scrollable box in it (WebKit gives each its own UIScrollView), is no
220
+ /// tap, as in Chromium, where lifting a finger after a scroll gives the page no user activation
221
+ /// (pointer_event_manager.cc).
222
+ private func scrolls(_ touches: Set<UITouch>) -> Bool {
223
+ touches.contains { touch in
224
+ touch.gestureRecognizers?.contains { recognizer in
225
+ guard let scrollView = recognizer.view as? UIScrollView else { return false }
226
+ return scrollView.isDragging || scrollView.isZooming
227
+ } == true
228
+ }
229
+ }
230
+
231
+ /// Another recognizer that recognizes before the touch ends (WebKit's touch events one begins at touch down) leaves
232
+ /// this one watching instead of failing it.
233
+ func gestureRecognizer(
234
+ _ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer
235
+ ) -> Bool {
236
+ true
237
+ }
238
+ }
239
+
240
+ /// WebKit sends a tap's click once the finger lifts, at once on a page sized to the device (`width=device-width`) or
241
+ /// after its double-tap wait (about 350 ms) on one that can zoom, and the link's decision follows from the web content
242
+ /// process. A second covers that on a busy page, and a redirect of the tapped link that answers within it; it leaves a
243
+ /// script little time to ride on an unrelated tap, where Chromium's user activation lasts 5 s.
244
+ private let tapWindow: TimeInterval = 1
@@ -0,0 +1,92 @@
1
+ import ExpoModulesCore
2
+ import WebKit
3
+
4
+ /// The scripts the view runs in the page: the injected scripts, `evaluate`, and the bridge transport (page -> RN through a
5
+ /// WKScriptMessageHandler, RN -> page through callAsyncJavaScript). The bridge moves only the text, with the sender's
6
+ /// verified origin; the protocol (calls, results, events) is the page client's and createBridge's.
7
+ extension MinimalWebView {
8
+ /// The bridge's page client first, then the app's scripts in order, then the hooks' own. Changes take effect from the
9
+ /// next navigation.
10
+ func installScripts(_ controller: WKUserContentController) {
11
+ // WebKit can only remove every script: take the hooks' out and add them back after the core's.
12
+ let hooks = controller.userScripts.filter { script in !ownScripts.contains { $0 === script } }
13
+ controller.removeAllUserScripts()
14
+ ownScripts = []
15
+ if let bridgeScript {
16
+ ownScripts.append(WKUserScript(source: bridgeScript, injectionTime: .atDocumentStart, forMainFrameOnly: true, in: .page))
17
+ }
18
+ for script in injectedScripts {
19
+ guard let code = script.code else { continue }
20
+ ownScripts.append(WKUserScript(source: code, injectionTime: .atDocumentStart, forMainFrameOnly: script.allFrames != true, in: .page))
21
+ }
22
+ (ownScripts + hooks).forEach { controller.addUserScript($0) }
23
+ }
24
+
25
+ /// The `evaluate` ref method. A new document rejects what is still waiting: WebKit settles a call whose page went
26
+ /// away seconds later or never.
27
+ func evaluate(_ script: String, _ promise: Promise) {
28
+ guard let webView else { return promise.reject("unavailable", "No WebView") }
29
+ let id = nextEvaluation
30
+ nextEvaluation += 1
31
+ evaluations[id] = promise
32
+ let body = "return ((v) => { try { return JSON.stringify(v) ?? 'null' } catch { return 'null' } })(await (\n\(script)\n))"
33
+ webView.callAsyncJavaScript(body, arguments: [:], in: nil, in: .page) { [weak self] result in
34
+ // Already rejected when its page went away.
35
+ guard let promise = self?.evaluations.removeValue(forKey: id) else { return }
36
+ switch result {
37
+ case .success(let value): promise.resolve(value as? String ?? "null")
38
+ case .failure(let error):
39
+ // The thrown error's own text, as on Android; WebKit's localizedDescription is generic.
40
+ let message = (error as NSError).userInfo["WKJavaScriptExceptionMessage"] as? String ?? error.localizedDescription
41
+ promise.reject("script_error", message)
42
+ }
43
+ }
44
+ }
45
+
46
+ /// The page the waiting `evaluate` calls run in is gone.
47
+ func failEvaluations() {
48
+ let waiting = evaluations.values
49
+ evaluations = [:]
50
+ waiting.forEach { $0.reject("navigated", "the page navigated before the script finished") }
51
+ }
52
+
53
+ func bridgeReceive(_ message: WKScriptMessage) {
54
+ let origin = OriginRules.origin(of: message.frameInfo.securityOrigin)
55
+ // This view's main frame only: a window.open('') view (WindowCatcher) shares the content controller.
56
+ guard message.webView === webView, message.frameInfo.isMainFrame, OriginRules.allows(bridgeOrigins, origin),
57
+ let text = message.body as? String else { return }
58
+ // `*` allows every document, opaque ones too (whose location.origin is "null"): nothing to compare.
59
+ bridgeOrigin = bridgeOrigins.contains("*") ? "*" : origin
60
+ onBridge(["message": text, "origin": origin])
61
+ }
62
+
63
+ /// Delivers a message from RN to the page. Only to the allowed document that last posted (its page client says
64
+ /// `ready` first). The page checks its origin again at delivery time: the document may have changed since the post
65
+ /// was queued. A message for a page that is gone is dropped.
66
+ func bridgePost(_ text: String) {
67
+ guard let bridgeOrigin else { return }
68
+ let deliver = "if (origin === '*' || location.origin === origin) window.nativeBridge?.__receive(message)"
69
+ webView?.callAsyncJavaScript(deliver, arguments: ["message": text, "origin": bridgeOrigin], in: nil, in: .page)
70
+ }
71
+ }
72
+
73
+ /// Holds the view weakly: WKUserContentController retains its handlers.
74
+ final class WeakBridgeHandler: NSObject, WKScriptMessageHandler {
75
+ weak var view: MinimalWebView?
76
+
77
+ init(_ view: MinimalWebView) {
78
+ self.view = view
79
+ }
80
+
81
+ func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) {
82
+ view?.bridgeReceive(message)
83
+ }
84
+ }
85
+
86
+ extension OriginRules {
87
+ /// The origin as `location.origin` writes it, so the bridge can compare the two exactly. Kept out of OriginRules.swift
88
+ /// so that file builds without WebKit (the rule tests run on Linux).
89
+ static func origin(of security: WKSecurityOrigin) -> String {
90
+ origin(security.protocol, security.host, security.port)
91
+ }
92
+ }
@@ -0,0 +1,13 @@
1
+ # ``MinimalWebView``
2
+
3
+ For native-hook authors: the Swift API a hook gets. An app that only renders `<WebView>` doesn't need it. Start
4
+ with the [native hooks guide](https://rasmuskard.github.io/react-native-minimal-webview/guides/native-hooks/).
5
+
6
+ ## Topics
7
+
8
+ ### Hooks
9
+
10
+ - ``MinimalWebViewHooks``
11
+ - ``WebViewContext``
12
+ - ``HookReply``
13
+ - ``DocumentEnd``
@@ -0,0 +1,32 @@
1
+ require 'json'
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, '..', 'package.json')))
4
+
5
+ Pod::Spec.new do |s|
6
+ s.name = 'MinimalWebView'
7
+ s.version = package['version']
8
+ s.summary = package['description']
9
+ s.license = package['license']
10
+ s.author = package['author']
11
+ s.homepage = package['homepage']
12
+ s.platforms = {
13
+ :ios => '17.0'
14
+ }
15
+ repository = package['repository']
16
+ s.source = { git: repository.is_a?(Hash) ? repository['url'] : repository } # npm pkg fix makes it a Hash
17
+ s.static_framework = true
18
+
19
+ s.dependency 'ExpoModulesCore'
20
+
21
+ # Swift/Objective-C compatibility
22
+ s.pod_target_xcconfig = {
23
+ 'DEFINES_MODULE' => 'YES',
24
+ # the documentation catalog, which CocoaPods can't add as a source
25
+ 'OTHER_DOCC_FLAGS' => '$(inherited) "$(PODS_TARGET_SRCROOT)/MinimalWebView.docc"',
26
+ }
27
+
28
+ # Every header here is public, so the Objective-C helpers are NS_REFINED_FOR_SWIFT: Swift sees them as __MRW…,
29
+ # which keeps them out of the Swift API reference.
30
+ s.source_files = "**/*.{h,m,mm,swift,hpp,cpp}"
31
+ s.exclude_files = "Tests/**/*"
32
+ end