react-native-minimal-webview 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/README.md +35 -31
  2. package/android/build.gradle +1 -1
  3. package/android/src/main/java/expo/modules/minimalwebview/Asks.kt +5 -11
  4. package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +17 -11
  5. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +83 -125
  6. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +16 -31
  7. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +18 -19
  8. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +24 -38
  9. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +24 -36
  10. package/android/src/main/java/expo/modules/minimalwebview/NavigationRules.kt +19 -20
  11. package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +41 -37
  12. package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +14 -18
  13. package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +12 -23
  14. package/android/src/main/java/expo/modules/minimalwebview/requests/FileUpload.kt +0 -1
  15. package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +1 -4
  16. package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +34 -24
  17. package/build/WebView.d.ts +11 -2
  18. package/build/WebView.d.ts.map +1 -1
  19. package/build/WebView.js +45 -71
  20. package/build/WebView.js.map +1 -1
  21. package/build/bridge/createBridge.d.ts +1 -5
  22. package/build/bridge/createBridge.d.ts.map +1 -1
  23. package/build/bridge/createBridge.js +3 -15
  24. package/build/bridge/createBridge.js.map +1 -1
  25. package/build/bridge/endpoint.d.ts +1 -2
  26. package/build/bridge/endpoint.d.ts.map +1 -1
  27. package/build/bridge/endpoint.js +5 -6
  28. package/build/bridge/endpoint.js.map +1 -1
  29. package/build/bridge/matchesOrigin.d.ts +11 -0
  30. package/build/bridge/matchesOrigin.d.ts.map +1 -0
  31. package/build/bridge/matchesOrigin.js +26 -0
  32. package/build/bridge/matchesOrigin.js.map +1 -0
  33. package/build/bridge/origins.d.ts +2 -13
  34. package/build/bridge/origins.d.ts.map +1 -1
  35. package/build/bridge/origins.js +1 -30
  36. package/build/bridge/origins.js.map +1 -1
  37. package/build/bridge/pageClient.generated.d.ts +1 -1
  38. package/build/bridge/pageClient.generated.d.ts.map +1 -1
  39. package/build/bridge/pageClient.generated.js +2 -2
  40. package/build/bridge/pageClient.generated.js.map +1 -1
  41. package/build/bridge/protocol.d.ts +3 -5
  42. package/build/bridge/protocol.d.ts.map +1 -1
  43. package/build/bridge/protocol.js +12 -14
  44. package/build/bridge/protocol.js.map +1 -1
  45. package/build/index.d.ts +1 -1
  46. package/build/index.js +1 -1
  47. package/build/navigationRules.d.ts +0 -5
  48. package/build/navigationRules.d.ts.map +1 -1
  49. package/build/navigationRules.js +3 -12
  50. package/build/navigationRules.js.map +1 -1
  51. package/build/reactNativeWebViewDefaults.d.ts +0 -4
  52. package/build/reactNativeWebViewDefaults.d.ts.map +1 -1
  53. package/build/reactNativeWebViewDefaults.js +0 -4
  54. package/build/reactNativeWebViewDefaults.js.map +1 -1
  55. package/build/reactNativeWebViewMessages.d.ts.map +1 -1
  56. package/build/reactNativeWebViewMessages.js +0 -1
  57. package/build/reactNativeWebViewMessages.js.map +1 -1
  58. package/build/refStore.d.ts +0 -2
  59. package/build/refStore.d.ts.map +1 -1
  60. package/build/refStore.js +0 -6
  61. package/build/refStore.js.map +1 -1
  62. package/build/types.d.ts +55 -39
  63. package/build/types.d.ts.map +1 -1
  64. package/ios/Asks.swift +6 -9
  65. package/ios/DelegateProxy.swift +4 -18
  66. package/ios/DownloadName.swift +0 -2
  67. package/ios/Downloads.swift +0 -2
  68. package/ios/Hooks.swift +4 -6
  69. package/ios/Loads.swift +37 -19
  70. package/ios/MinimalWebView+Dialogs.swift +5 -7
  71. package/ios/MinimalWebView+Navigation.swift +23 -49
  72. package/ios/MinimalWebView+Scripts.swift +10 -17
  73. package/ios/MinimalWebView.podspec +1 -2
  74. package/ios/MinimalWebView.swift +63 -128
  75. package/ios/MinimalWebViewModule.swift +1 -18
  76. package/ios/NavigationRules.swift +2 -9
  77. package/ios/OriginRules.swift +4 -13
  78. package/ios/PlatformSettings.swift +9 -30
  79. package/ios/ReadAccess.swift +0 -2
  80. package/ios/Records.swift +18 -0
  81. package/ios/Recovery.swift +2 -8
  82. package/ios/SharedCookies.swift +10 -25
  83. package/mocks/MinimalWebView.ts +5 -0
  84. package/package.json +11 -10
  85. package/src/WebView.tsx +58 -80
  86. package/src/bridge/createBridge.ts +5 -20
  87. package/src/bridge/endpoint.ts +6 -9
  88. package/src/bridge/matchesOrigin.ts +27 -0
  89. package/src/bridge/origins.ts +2 -30
  90. package/src/bridge/pageClient.generated.ts +2 -2
  91. package/src/bridge/pageClient.ts +1 -7
  92. package/src/bridge/protocol.ts +16 -18
  93. package/src/index.ts +1 -1
  94. package/src/navigationRules.ts +6 -12
  95. package/src/reactNativeWebViewDefaults.ts +0 -4
  96. package/src/reactNativeWebViewMessages.ts +0 -1
  97. package/src/refStore.ts +0 -7
  98. package/src/types.ts +55 -39
@@ -2,27 +2,21 @@ import UIKit
2
2
  import UIKit.UIGestureRecognizerSubclass
3
3
  import WebKit
4
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
5
  extension MinimalWebView {
8
6
  func decideNavigation(_ action: WKNavigationAction, decide: @escaping @MainActor (WKNavigationActionPolicy) -> Void) {
9
7
  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).
8
+ // A new window (no target frame) is decided in createWebViewWith.
12
9
  guard let targetFrame = action.targetFrame else { return decide(allowInPlace) }
13
10
  let mainFrame = targetFrame.isMainFrame
14
- if mainFrame { mainFrameChecks += 1 }
15
- let own = mainFrame ? ownLoads.firstIndex { Loads.sameURL($0.url, target) } : nil
16
- if own != nil || action.navigationType == .backForward || action.navigationType == .reload
11
+ let own = takeOwnLoad(action)
12
+ if own || action.navigationType == .backForward || action.navigationType == .reload
17
13
  || action.request.httpMethod == "POST" {
18
- if let own { ownLoads.remove(at: own) }
19
14
  return decide(allowInPlace)
20
15
  }
21
16
  let request = NavigationRules.Request(
22
17
  url: target.absoluteString, mainFrame: mainFrame, newWindow: false, userInitiated: userInitiated(action)
23
18
  )
24
- // A navigation WebKit marks as a download (`<a download>`, blob:). One no onDownload takes is cancelled, and an
25
- // http(s) one opens outside the WebView (openDownload): .allow would show it as a page.
19
+ // `.allow` would show a navigation WebKit marks as a download (`<a download>`, blob:) as a page.
26
20
  let download = action.shouldPerformDownload && requestHandlers.contains("onDownload")
27
21
  let dropped = action.shouldPerformDownload && !download
28
22
  run(request) { [weak self] allowed in
@@ -35,24 +29,24 @@ extension MinimalWebView {
35
29
  }
36
30
  }
37
31
 
38
- /// Whether a user gesture started `action`: a link activation right after a tap on this view (`Taps`). WebKit
39
- /// reports every navigation with a triggering event as `.linkActivated` (NavigationAction.cpp's navigationType),
40
- /// including a link a script clicks (`element.click()`), and no public WKNavigationAction property tells a real one
41
- /// apart.
32
+ func takeOwnLoad(_ action: WKNavigationAction) -> Bool {
33
+ guard action.targetFrame?.isMainFrame == true, let target = action.request.url else { return false }
34
+ return ownLoads.check(target)
35
+ }
36
+
37
+ /// WebKit reports a link a script clicks (`element.click()`) as `.linkActivated` too, and no public
38
+ /// WKNavigationAction property tells a real one apart.
42
39
  private func userInitiated(_ action: WKNavigationAction) -> Bool {
43
40
  action.navigationType == .linkActivated
44
41
  && (taps.recent || UIAccessibility.isVoiceOverRunning || UIAccessibility.isSwitchControlRunning)
45
42
  }
46
43
 
47
- /// A download no `onDownload` takes.
48
44
  func openDownload(_ url: URL) {
49
45
  guard ["http", "https"].contains(url.scheme?.lowercased()) else { return }
50
46
  let request = NavigationRules.Request(url: url.absoluteString, mainFrame: true, newWindow: false, userInitiated: false)
51
47
  finish(request, .external, nil) { _ in }
52
48
  }
53
49
 
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
50
  func webView(
57
51
  _ webView: WKWebView,
58
52
  createWebViewWith configuration: WKWebViewConfiguration,
@@ -69,7 +63,6 @@ extension MinimalWebView {
69
63
 
70
64
  private func openWindow(_ request: URLRequest, _ userInitiated: Bool) {
71
65
  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
66
  if request.httpMethod == "POST", ["http", "https"].contains(target.scheme?.lowercased()) {
74
67
  return loadProgrammatic(request)
75
68
  }
@@ -83,8 +76,7 @@ extension MinimalWebView {
83
76
 
84
77
  /// Applies the rules (and `ask`) to a request and reports the outcome; `completion` gets whether to load it here.
85
78
  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). WebKit has no
87
- // redirect flag, so a tap on that URL isn't asked again either; Android skips only redirects.
79
+ // WebKit has no redirect flag: a URL an `ask` allowed isn't asked again until the next main-frame commit.
88
80
  let decision = NavigationRules.decide(
89
81
  navigationRules, request, asked: askedAndAllowed[request.mainFrame] ?? [],
90
82
  canAsk: requestHandlers.contains("onNavigationRequest")
@@ -93,14 +85,13 @@ extension MinimalWebView {
93
85
  finish(request, decision.action, decision.rule, completion)
94
86
  return
95
87
  }
96
- let id = asks.ask("core", "onNavigationRequest", request.payload) { [weak self] answer in
97
- // The view can be gone: the decision handler must still be called.
88
+ let asked = asks.ask("core", "onNavigationRequest", request.payload) { [weak self] answer in
98
89
  guard let self else { return completion(false) }
99
90
  let action = NavigationRules.answer(answer)
100
91
  if action == .allow { self.askedAndAllowed[request.mainFrame, default: []].insert(request.url) }
101
92
  self.finish(request, action, decision.rule, completion)
102
93
  }
103
- // Unanswered after the timeout: block.
94
+ guard let id = asked else { return }
104
95
  DispatchQueue.main.asyncAfter(deadline: .now() + askTimeout) { [weak self] in
105
96
  self?.asks.cancel(id)
106
97
  }
@@ -112,13 +103,11 @@ extension MinimalWebView {
112
103
  completion(action == .allow)
113
104
  guard action == .external else { return report(request, action, rule) }
114
105
  guard requestHandlers.contains("onOpenExternal") else { return open(request, rule) }
115
- // A page that moved on first answers nil, which counts as opened. No timeout: nothing waits for the answer.
116
106
  asks.ask("core", "onOpenExternal", request.payload) { [weak self] answer in
117
107
  if answer as? Bool == false { self?.open(request, rule) } else { self?.report(request, .external, rule) }
118
108
  }
119
109
  }
120
110
 
121
- /// Opens an `external` URL outside the WebView. As on Android, one that nothing opens is reported as blocked.
122
111
  private func open(_ request: NavigationRules.Request, _ rule: Int?) {
123
112
  guard let url = URL(string: request.url) else { return report(request, .block, rule) }
124
113
  UIApplication.shared.open(url) { [weak self] opened in self?.report(request, opened ? .external : .block, rule) }
@@ -132,10 +121,7 @@ extension MinimalWebView {
132
121
 
133
122
  private let askTimeout: TimeInterval = 1
134
123
 
135
- /// The throwaway window for `window.open('')` or about:blank, which the page navigates later (`w.location = url`), as
136
- /// async popup payment buttons do. WebKit needs a WKWebView for it, made from the configuration it passes. It is
137
- /// never shown: it cancels its first navigation, hands the request on and goes. One that hasn't navigated within 5 s,
138
- /// or that the page closes, goes unused.
124
+ /// WebKit needs a WKWebView made from the configuration it passes for a `window.open('')` the page navigates later.
139
125
  private final class WindowCatcher: NSObject, WKNavigationDelegate, WKUIDelegate {
140
126
  private var child: WKWebView?
141
127
  private var caught: ((URLRequest) -> Void)?
@@ -146,7 +132,7 @@ private final class WindowCatcher: NSObject, WKNavigationDelegate, WKUIDelegate
146
132
  child.navigationDelegate = catcher
147
133
  child.uiDelegate = catcher
148
134
  (catcher.child, catcher.caught) = (child, caught)
149
- // The view's delegates are weak: the timer holds the catcher, and the catcher the view until it lets it go.
135
+ // WKWebView's delegates are weak: the timer holds the catcher.
150
136
  DispatchQueue.main.asyncAfter(deadline: .now() + newWindowTimeout) { catcher.drop() }
151
137
  return child
152
138
  }
@@ -177,17 +163,12 @@ private final class WindowCatcher: NSObject, WKNavigationDelegate, WKUIDelegate
177
163
 
178
164
  private let newWindowTimeout: TimeInterval = 5
179
165
 
180
- /// WebKit's private `_WKNavigationActionPolicyAllowWithoutTryingAppLink` (allow + 2), as Firefox for iOS uses it:
181
- /// `.allow` would hand a tapped link to another host to an installed app that claims it as a universal link, which
182
- /// Android's WebView never does. Hand-off is an explicit `external` rule. `init(rawValue:)` accepts any value, so
183
- /// `?? .allow` only satisfies the type: nothing falls back if WebKit drops the value.
166
+ /// WebKit's private `_WKNavigationActionPolicyAllowWithoutTryingAppLink` (allow + 2): `.allow` would hand a tapped
167
+ /// link to an installed app that claims it as a universal link.
168
+ /// `init(rawValue:)` accepts any value, so the fallback never applies.
184
169
  private let allowInPlace = WKNavigationActionPolicy(rawValue: WKNavigationActionPolicy.allow.rawValue + 2) ?? .allow
185
170
 
186
- /// When a tap on the WKWebView last ended, for `userInitiated`. It only watches the view's touches and 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). It fails at each touch's end, or as soon as the touch scrolls.
189
171
  final class Taps: UIGestureRecognizer, UIGestureRecognizerDelegate {
190
- /// System uptime, so a change of the device time doesn't affect it.
191
172
  private var lastTap: TimeInterval = -.infinity
192
173
 
193
174
  override init(target: Any?, action: Selector?) {
@@ -197,7 +178,6 @@ final class Taps: UIGestureRecognizer, UIGestureRecognizerDelegate {
197
178
  delegate = self
198
179
  }
199
180
 
200
- /// A tap ended within `tapWindow`.
201
181
  var recent: Bool { ProcessInfo.processInfo.systemUptime - lastTap <= tapWindow }
202
182
 
203
183
  override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
@@ -216,9 +196,7 @@ final class Taps: UIGestureRecognizer, UIGestureRecognizerDelegate {
216
196
  state = .failed
217
197
  }
218
198
 
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).
199
+ /// WebKit gives the page and each scrollable box in it its own UIScrollView.
222
200
  private func scrolls(_ touches: Set<UITouch>) -> Bool {
223
201
  touches.contains { touch in
224
202
  touch.gestureRecognizers?.contains { recognizer in
@@ -228,8 +206,7 @@ final class Taps: UIGestureRecognizer, UIGestureRecognizerDelegate {
228
206
  }
229
207
  }
230
208
 
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.
209
+ /// WebKit's touch events recognizer begins at touch down, which would otherwise fail this one.
233
210
  func gestureRecognizer(
234
211
  _ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer
235
212
  ) -> Bool {
@@ -237,9 +214,6 @@ final class Taps: UIGestureRecognizer, UIGestureRecognizerDelegate {
237
214
  }
238
215
  }
239
216
 
240
- /// How long after a tap ends a link activation still counts as user-initiated. WebKit sends the click once the finger
241
- /// lifts: at once on a page sized to the device (`width=device-width`), after its double-tap wait (about 350 ms) on
242
- /// one that can zoom. The link's decision then follows from the web content process. The window covers a busy page
243
- /// and a redirect of the tapped link. It stays short so a script has little time to ride on an unrelated tap;
244
- /// Chromium's user activation lasts 5 s.
217
+ /// WebKit sends the click after its double-tap wait (about 350 ms) on a page that can zoom, and the link's decision
218
+ /// follows from the web content process.
245
219
  private let tapWindow: TimeInterval = 1
@@ -1,12 +1,7 @@
1
1
  import ExpoModulesCore
2
2
  import WebKit
3
3
 
4
- /// The scripts the view runs in the page: the injected scripts, `evaluate`, and the bridge transport (page -> JS through a
5
- /// WKScriptMessageHandler, JS -> 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
4
  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
5
  func installScripts(_ controller: WKUserContentController) {
11
6
  // WebKit can only remove every script: take the hooks' out and add them back after the core's.
12
7
  let hooks = controller.userScripts.filter { script in !ownScripts.contains { $0 === script } }
@@ -22,8 +17,7 @@ extension MinimalWebView {
22
17
  (ownScripts + hooks).forEach { controller.addUserScript($0) }
23
18
  }
24
19
 
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.
20
+ /// WebKit settles a call whose page went away seconds later or never.
27
21
  func evaluate(_ script: String, _ promise: Promise) {
28
22
  guard let webView else { return promise.reject("unavailable", "No WebView") }
29
23
  let id = nextEvaluation
@@ -31,38 +25,37 @@ extension MinimalWebView {
31
25
  evaluations[id] = promise
32
26
  let body = "return ((v) => { try { return JSON.stringify(v) ?? 'null' } catch { return 'null' } })(await (\n\(script)\n))"
33
27
  webView.callAsyncJavaScript(body, arguments: [:], in: nil, in: .page) { [weak self] result in
34
- // Already rejected when its page went away.
35
28
  guard let promise = self?.evaluations.removeValue(forKey: id) else { return }
36
29
  switch result {
37
30
  case .success(let value): promise.resolve(value as? String ?? "null")
38
31
  case .failure(let error):
39
- // The thrown error's own text, as on Android; WebKit's localizedDescription is generic.
32
+ // WebKit's localizedDescription is generic.
40
33
  let message = (error as NSError).userInfo["WKJavaScriptExceptionMessage"] as? String ?? error.localizedDescription
34
+ // WebKit drops the call of a page being left, and (iOS 27) can say so before didCommit.
35
+ if message == Self.unreachable, self?.webView?.isLoading == true { return promise.reject("navigated", Self.navigated) }
41
36
  promise.reject("script_error", message)
42
37
  }
43
38
  }
44
39
  }
45
40
 
46
- /// The page the waiting `evaluate` calls run in is gone.
47
41
  func failEvaluations() {
48
42
  let waiting = evaluations.values
49
43
  evaluations = [:]
50
- waiting.forEach { $0.reject("navigated", "the page navigated before the script finished") }
44
+ waiting.forEach { $0.reject("navigated", Self.navigated) }
51
45
  }
52
46
 
47
+ private static let navigated = "the page navigated before the script finished"
48
+ private static let unreachable = "Completion handler for function call is no longer reachable"
49
+
53
50
  func bridgeReceive(_ message: WKScriptMessage) {
54
51
  let origin = OriginRules.origin(of: message.frameInfo.securityOrigin)
55
- // This view's main frame only: a window.open('') view (WindowCatcher) shares the content controller.
52
+ // A window.open('') view (WindowCatcher) shares the content controller.
56
53
  guard message.webView === webView, message.frameInfo.isMainFrame, OriginRules.allows(bridgeOrigins, origin),
57
54
  let text = message.body as? String else { return }
58
- // `*` allows every document, opaque ones too (whose location.origin is "null"): nothing to compare.
59
55
  bridgeOrigin = bridgeOrigins.contains("*") ? "*" : origin
60
56
  onBridge(["message": text, "origin": origin])
61
57
  }
62
58
 
63
- /// Delivers a message from JS 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
59
  func bridgePost(_ text: String) {
67
60
  guard let bridgeOrigin else { return }
68
61
  let deliver = "if (origin === '*' || location.origin === origin) window.nativeBridge?.__receive(message)"
@@ -70,7 +63,7 @@ extension MinimalWebView {
70
63
  }
71
64
  }
72
65
 
73
- /// Holds the view weakly: WKUserContentController retains its handlers.
66
+ /// WKUserContentController retains its handlers.
74
67
  final class WeakBridgeHandler: NSObject, WKScriptMessageHandler {
75
68
  weak var view: MinimalWebView?
76
69
 
@@ -12,8 +12,7 @@ Pod::Spec.new do |s|
12
12
  s.platforms = {
13
13
  :ios => '17.0'
14
14
  }
15
- repository = package['repository']
16
- s.source = { git: repository.is_a?(Hash) ? repository['url'] : repository } # npm pkg fix makes it a Hash
15
+ s.source = { git: package['repository'] }
17
16
  s.static_framework = true
18
17
 
19
18
  s.dependency 'ExpoModulesCore'