react-native-minimal-webview 1.2.1 → 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.
- package/android/build.gradle +1 -1
- package/android/src/main/java/expo/modules/minimalwebview/Asks.kt +5 -11
- package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +17 -11
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +64 -119
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +16 -31
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +4 -16
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +24 -38
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +24 -36
- package/android/src/main/java/expo/modules/minimalwebview/NavigationRules.kt +19 -20
- package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +25 -37
- package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +14 -18
- package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +12 -23
- package/android/src/main/java/expo/modules/minimalwebview/requests/FileUpload.kt +0 -1
- package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +1 -4
- package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +34 -24
- package/build/WebView.d.ts +8 -1
- package/build/WebView.d.ts.map +1 -1
- package/build/WebView.js +22 -68
- package/build/WebView.js.map +1 -1
- package/build/bridge/createBridge.d.ts +1 -5
- package/build/bridge/createBridge.d.ts.map +1 -1
- package/build/bridge/createBridge.js +3 -15
- package/build/bridge/createBridge.js.map +1 -1
- package/build/bridge/endpoint.d.ts +1 -2
- package/build/bridge/endpoint.d.ts.map +1 -1
- package/build/bridge/endpoint.js +5 -6
- package/build/bridge/endpoint.js.map +1 -1
- package/build/bridge/matchesOrigin.d.ts +11 -0
- package/build/bridge/matchesOrigin.d.ts.map +1 -0
- package/build/bridge/matchesOrigin.js +26 -0
- package/build/bridge/matchesOrigin.js.map +1 -0
- package/build/bridge/origins.d.ts +2 -13
- package/build/bridge/origins.d.ts.map +1 -1
- package/build/bridge/origins.js +1 -30
- package/build/bridge/origins.js.map +1 -1
- package/build/bridge/pageClient.generated.d.ts +1 -1
- package/build/bridge/pageClient.generated.d.ts.map +1 -1
- package/build/bridge/pageClient.generated.js +2 -2
- package/build/bridge/pageClient.generated.js.map +1 -1
- package/build/bridge/protocol.d.ts +3 -5
- package/build/bridge/protocol.d.ts.map +1 -1
- package/build/bridge/protocol.js +12 -14
- package/build/bridge/protocol.js.map +1 -1
- package/build/index.d.ts +1 -1
- package/build/index.js +1 -1
- package/build/navigationRules.d.ts +0 -5
- package/build/navigationRules.d.ts.map +1 -1
- package/build/navigationRules.js +3 -12
- package/build/navigationRules.js.map +1 -1
- package/build/reactNativeWebViewDefaults.d.ts +0 -4
- package/build/reactNativeWebViewDefaults.d.ts.map +1 -1
- package/build/reactNativeWebViewDefaults.js +0 -4
- package/build/reactNativeWebViewDefaults.js.map +1 -1
- package/build/reactNativeWebViewMessages.d.ts.map +1 -1
- package/build/reactNativeWebViewMessages.js +0 -1
- package/build/reactNativeWebViewMessages.js.map +1 -1
- package/build/refStore.d.ts +0 -2
- package/build/refStore.d.ts.map +1 -1
- package/build/refStore.js +0 -6
- package/build/refStore.js.map +1 -1
- package/build/types.d.ts +25 -12
- package/build/types.d.ts.map +1 -1
- package/ios/Asks.swift +6 -9
- package/ios/DelegateProxy.swift +2 -19
- package/ios/DownloadName.swift +0 -2
- package/ios/Downloads.swift +0 -2
- package/ios/Hooks.swift +4 -6
- package/ios/Loads.swift +37 -19
- package/ios/MinimalWebView+Dialogs.swift +2 -6
- package/ios/MinimalWebView+Navigation.swift +17 -50
- package/ios/MinimalWebView+Scripts.swift +4 -16
- package/ios/MinimalWebView.podspec +1 -2
- package/ios/MinimalWebView.swift +62 -132
- package/ios/MinimalWebViewModule.swift +1 -18
- package/ios/NavigationRules.swift +2 -9
- package/ios/OriginRules.swift +4 -13
- package/ios/PlatformSettings.swift +9 -30
- package/ios/ReadAccess.swift +0 -2
- package/ios/Records.swift +18 -0
- package/ios/Recovery.swift +2 -8
- package/ios/SharedCookies.swift +10 -25
- package/package.json +4 -4
- package/src/WebView.tsx +34 -77
- package/src/bridge/createBridge.ts +5 -20
- package/src/bridge/endpoint.ts +6 -9
- package/src/bridge/matchesOrigin.ts +27 -0
- package/src/bridge/origins.ts +2 -30
- package/src/bridge/pageClient.generated.ts +2 -2
- package/src/bridge/pageClient.ts +1 -7
- package/src/bridge/protocol.ts +16 -18
- package/src/index.ts +1 -1
- package/src/navigationRules.ts +6 -12
- package/src/reactNativeWebViewDefaults.ts +0 -4
- package/src/reactNativeWebViewMessages.ts +0 -1
- package/src/refStore.ts +0 -7
- package/src/types.ts +25 -12
package/ios/MinimalWebView.swift
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import ExpoModulesCore
|
|
2
2
|
import WebKit
|
|
3
3
|
|
|
4
|
-
// swiftlint:disable file_length - because the view is the aggregate root
|
|
5
|
-
// swiftlint:disable:next type_body_length - because the view is the aggregate root
|
|
4
|
+
// swiftlint:disable file_length - because the view is the aggregate root
|
|
5
|
+
// swiftlint:disable:next type_body_length - because the view is the aggregate root
|
|
6
6
|
class MinimalWebView: ExpoView, WKNavigationDelegate {
|
|
7
7
|
let onNavigationState = EventDispatcher()
|
|
8
8
|
let onBridge = EventDispatcher()
|
|
@@ -11,16 +11,12 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
|
|
|
11
11
|
let onProcessGone = EventDispatcher()
|
|
12
12
|
let onNavigation = EventDispatcher()
|
|
13
13
|
|
|
14
|
-
// Props, applied together in applyProps(). The bridge, the hooks with a configure step and the `configuration`
|
|
15
|
-
// settings are fixed at mount (see `webView`).
|
|
16
14
|
var source: WebViewSource?
|
|
17
15
|
var bridgeScript: String?
|
|
18
16
|
var bridgeOrigins: [String] = []
|
|
19
|
-
/// The `hookOptions` prop, made from the `extensions` prop's options: each hook's value by key. A change reaches the attached hooks (onOptions).
|
|
20
17
|
var hookOptions: [String: Any] = [:] {
|
|
21
18
|
didSet { if webView != nil { optionsChanged(from: oldValue) } }
|
|
22
19
|
}
|
|
23
|
-
/// The `ios` prop: WebKit properties by name, applied by PlatformSettings.
|
|
24
20
|
var settings: [String: Any] = [:]
|
|
25
21
|
let platformSettings = PlatformSettings()
|
|
26
22
|
var pullToRefresh = false
|
|
@@ -35,68 +31,43 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
|
|
|
35
31
|
var injectedScripts: [InjectedScript] = [] {
|
|
36
32
|
didSet { if let webView { installScripts(webView.configuration.userContentController) } }
|
|
37
33
|
}
|
|
38
|
-
/// The user scripts installScripts added: the others in the content controller are a hook's.
|
|
39
34
|
var ownScripts: [WKUserScript] = []
|
|
40
|
-
/// The page requests JS has a prop for, by prop name (`onDownload`, `onNavigationRequest`, ...), and `onNavigation`, read when a
|
|
41
|
-
/// request comes or a decision is reported.
|
|
42
35
|
var requestHandlers: Set<String> = []
|
|
43
36
|
private var loadedSource: NSDictionary?
|
|
44
37
|
|
|
45
|
-
// Created once, from the first props: WebKit reads some WKWebViewConfiguration settings only at creation.
|
|
46
38
|
private(set) var webView: WKWebView?
|
|
47
39
|
private var observations: [NSKeyValueObservation] = []
|
|
48
40
|
private lazy var downloads = Downloads(view: self)
|
|
49
41
|
private lazy var proxy = DelegateProxy(core: self)
|
|
50
|
-
/// When the user last tapped the WKWebView: a link activation counts as user-initiated only right after a tap.
|
|
51
42
|
let taps = Taps(target: nil, action: nil)
|
|
52
43
|
|
|
53
|
-
// Navigation state, derived from WebKit in refreshUrls(). Native owns the committed URL; JS is told.
|
|
54
44
|
private(set) var url = ""
|
|
55
|
-
/// `url
|
|
56
|
-
/// agrees, and takes the new page at each commit, after `onDocumentEnd`. WebKit moves the back-forward list to the
|
|
57
|
-
/// next page before didCommit, and `url` can follow it early.
|
|
45
|
+
/// `WebViewContext.url`: WebKit moves the back-forward list to the next page before didCommit, and `url` can follow it early.
|
|
58
46
|
private(set) var hookUrl = ""
|
|
59
47
|
private var pendingUrl: String?
|
|
60
|
-
///
|
|
61
|
-
/// while the item that was current at its commit stays current, the html page is what is on screen.
|
|
48
|
+
/// WebKit hides substitute-data loads (an html source) from the back-forward list.
|
|
62
49
|
private var htmlNavigation: WKNavigation?
|
|
63
50
|
private var htmlCommit: (url: String, item: WKBackForwardListItem?)?
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
/// check passed (cut off before their own), so a page can't later skip the rules by navigating to one.
|
|
68
|
-
var ownLoads: [(url: URL, checks: Int)] = []
|
|
69
|
-
var mainFrameChecks = 0
|
|
70
|
-
private(set) lazy var asks = Asks { [weak self] in self?.onHookEvent($0) }
|
|
71
|
-
/// The attached hooks' contexts in attach order, for the life of the WKWebView: a hook may keep its own.
|
|
51
|
+
var ownLoads = OwnLoads()
|
|
52
|
+
// No weak self: forming a weak reference to an object in deinit aborts, and deinit's tearDown can be the first use.
|
|
53
|
+
private(set) lazy var asks = Asks { [onHookEvent] in onHookEvent($0) }
|
|
72
54
|
var hookContexts: [HookContext] = []
|
|
73
|
-
/// URLs an `ask` allowed in this Document, keyed by mainFrame: a subframe's answer doesn't decide the main frame's.
|
|
74
55
|
var askedAndAllowed: [Bool: Set<String>] = [:]
|
|
75
|
-
/// A `source` or `load` load is being prepared (shared cookies): loads wait until it is done.
|
|
76
56
|
private var preparing = false
|
|
77
|
-
/// The ref's `load` while it is prepared: it loads instead of the `source` being prepared, if any.
|
|
78
57
|
private var queuedUrl: URL?
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
private(set) var failedUrl: String?
|
|
84
|
-
/// How the last load ended, "finished", "failed" or "cancelled"; JS sees it only while nothing loads.
|
|
85
|
-
private var outcome: String?
|
|
58
|
+
private var directoryOnlyNavigation: WKNavigation?
|
|
59
|
+
/// WKWebView keeps the previous page after a failed main-frame load.
|
|
60
|
+
private var failedLoad: (url: String, inSourceRoot: Bool)?
|
|
61
|
+
private var outcome: Loads.Outcome?
|
|
86
62
|
private var lastEmitted: NSDictionary?
|
|
87
63
|
private var updateScheduled = false
|
|
88
64
|
private var crashTimes: [TimeInterval] = []
|
|
89
|
-
/// A web-process death whose reload waits until the view can be seen; a `load`, reload or new `source` replaces it.
|
|
90
65
|
private var recoveryPending = false
|
|
91
|
-
/// `evaluate` calls waiting for their result, by id, until a new document or a dead web process rejects them.
|
|
92
66
|
var evaluations: [Int: Promise] = [:]
|
|
93
67
|
var nextEvaluation = 0
|
|
94
68
|
|
|
95
|
-
// The origin of the document whose page client last posted, as `location.origin` writes it (`*` when every origin is
|
|
96
|
-
// allowed). JS's messages are delivered only while the page still has it.
|
|
97
69
|
var bridgeOrigin: String?
|
|
98
|
-
//
|
|
99
|
-
// While one is up the page is blocked, and an accessibility query into it (XCTest's) hangs: hide it.
|
|
70
|
+
// While a JS dialog is up the page is blocked, and an accessibility query into it (XCTest's) hangs.
|
|
100
71
|
var dialog: (controller: UIAlertController, cancel: () -> Void)? {
|
|
101
72
|
didSet { webView?.accessibilityElementsHidden = dialog != nil }
|
|
102
73
|
}
|
|
@@ -104,8 +75,6 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
|
|
|
104
75
|
required init(appContext: AppContext? = nil) {
|
|
105
76
|
super.init(appContext: appContext)
|
|
106
77
|
clipsToBounds = true
|
|
107
|
-
// Made here, not lazily in the deinit fallback's endDocument(.closing), where its closure can't form a weak self.
|
|
108
|
-
_ = asks
|
|
109
78
|
NotificationCenter.default.addObserver(
|
|
110
79
|
self, selector: #selector(recoverIfVisible), name: UIApplication.didBecomeActiveNotification, object: nil)
|
|
111
80
|
}
|
|
@@ -115,8 +84,6 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
|
|
|
115
84
|
recoverIfVisible()
|
|
116
85
|
}
|
|
117
86
|
|
|
118
|
-
/// Crash recovery reloads only in a window of an app not in the background, as on Android: there the reload
|
|
119
|
-
/// could die the same way, unseen.
|
|
120
87
|
@objc private func recoverIfVisible() {
|
|
121
88
|
guard recoveryPending, window != nil, UIApplication.shared.applicationState != .background else { return }
|
|
122
89
|
recoveryPending = false
|
|
@@ -131,34 +98,30 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
|
|
|
131
98
|
if !opening { asks.documentEnded(reason) }
|
|
132
99
|
failEvaluations()
|
|
133
100
|
bridgeOrigin = nil
|
|
134
|
-
// JS queues bridge messages until the next page is ready; at unmount it rejects what is in flight itself.
|
|
135
101
|
if reason == .committed, bridgeScript != nil { onBridge(["navigated": true]) }
|
|
136
102
|
if reason == .crashed, bridgeScript != nil { onBridge(["crashed": true]) }
|
|
137
103
|
askedAndAllowed.removeAll()
|
|
138
104
|
dismissDialog()
|
|
139
|
-
//
|
|
105
|
+
// A crash ends the load without a delegate callback.
|
|
140
106
|
if reason == .crashed { refreshControl.endRefreshing() }
|
|
141
107
|
if !opening { hookContexts.forEach { $0.documentEnded(reason) } }
|
|
142
108
|
}
|
|
143
109
|
|
|
144
|
-
/// Called once per prop batch. `source` loads last so everything else is ready first.
|
|
145
110
|
func applyProps() {
|
|
146
111
|
if webView == nil { createWebView() }
|
|
147
112
|
guard let webView, !preparing else { return }
|
|
148
113
|
report(platformSettings.apply(settings, webView: webView))
|
|
149
114
|
let refresh = pullToRefresh ? refreshControl : nil
|
|
150
115
|
if webView.scrollView.refreshControl !== refresh { webView.scrollView.refreshControl = refresh }
|
|
151
|
-
cookies.set(sharedCookies)
|
|
116
|
+
cookies.set(sharedCookies, for: webView.configuration.websiteDataStore.httpCookieStore)
|
|
152
117
|
// Records aren't Equatable: compare their dictionaries.
|
|
153
118
|
guard let next = source, loadedSource != next.toDictionary() as NSDictionary else { return }
|
|
154
119
|
loadedSource = next.toDictionary() as NSDictionary
|
|
155
|
-
// New content from the app: the crash-loop guard starts over (recovery reloads don't come through here).
|
|
156
120
|
crashTimes = []
|
|
157
121
|
recoveryPending = false
|
|
158
122
|
prepare(next)
|
|
159
123
|
}
|
|
160
124
|
|
|
161
|
-
/// The ref's `load`. It is prepared as a `source` load is, and a later call replaces one still waiting.
|
|
162
125
|
func load(url: String) {
|
|
163
126
|
guard let target = URL(string: url) else { return warn("load: \(url) is not a URL") }
|
|
164
127
|
guard webView != nil else { return }
|
|
@@ -173,17 +136,12 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
|
|
|
173
136
|
cookies.prepare { [weak self, weak webView] in
|
|
174
137
|
guard let self, let webView, webView === self.webView else { return }
|
|
175
138
|
preparing = false
|
|
176
|
-
// A load asked for while the source was prepared replaces it: started first, the source's request (a POST
|
|
177
|
-
// included) would be sent only to be cut off.
|
|
178
139
|
if let queuedUrl {
|
|
179
140
|
self.queuedUrl = nil
|
|
180
|
-
refLoad = queuedUrl
|
|
181
141
|
loadProgrammatic(URLRequest(url: queuedUrl), inSourceRoot: false)
|
|
182
142
|
} else if let source {
|
|
183
|
-
refLoad = nil
|
|
184
143
|
load(source)
|
|
185
144
|
}
|
|
186
|
-
// Props that changed while preparing (a newer source) apply now.
|
|
187
145
|
applyProps()
|
|
188
146
|
}
|
|
189
147
|
}
|
|
@@ -203,44 +161,37 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
|
|
|
203
161
|
} else {
|
|
204
162
|
let baseURL = source.baseUrl.flatMap(URL.init)
|
|
205
163
|
// WebKit puts the html load through decidePolicyFor at its base URL, about:blank without one.
|
|
206
|
-
if let own = baseURL ?? URL(string: "about:blank") { ownLoads.
|
|
164
|
+
if let own = baseURL ?? URL(string: "about:blank") { ownLoads.started(own) }
|
|
207
165
|
htmlNavigation = webView?.loadHTMLString(source.html ?? "", baseURL: baseURL)
|
|
208
166
|
}
|
|
209
167
|
}
|
|
210
168
|
|
|
211
|
-
/// The page on screen (`url`) is the `source`: its URL, or an html source whose commit no other commit or failed load
|
|
212
|
-
/// has followed.
|
|
213
169
|
private var onSource: Bool {
|
|
214
170
|
guard let source else { return false }
|
|
215
|
-
guard let uri = source.uri.flatMap(URL.init) else { return htmlCommit != nil &&
|
|
171
|
+
guard let uri = source.uri.flatMap(URL.init) else { return htmlCommit != nil && failedLoad == nil }
|
|
216
172
|
return Recovery.showsSource(uri.absoluteString, url)
|
|
217
173
|
}
|
|
218
174
|
|
|
219
|
-
/// The page on screen is the POST `source`: it can't be fetched again by URL, so reload loads the source instead.
|
|
220
175
|
private var onPostSource: Bool { source?.body != nil && onSource }
|
|
221
176
|
|
|
222
|
-
/// Settings keys that could not be applied, as warnings: JS logs them with console.warn.
|
|
223
177
|
private func report(_ rejected: [[String: String]]) {
|
|
224
178
|
for entry in rejected {
|
|
225
179
|
warn("ios.\(entry["key"] ?? ""): \(entry["reason"] ?? "")")
|
|
226
180
|
}
|
|
227
181
|
}
|
|
228
182
|
|
|
229
|
-
/// Loads a request the app started (see `ownLoads`). A file URL goes through loadFileURL, so the page's own assets
|
|
230
|
-
/// load (load(_:) can't read local files), with the source's read root or, outside it, the file's directory.
|
|
231
183
|
func loadProgrammatic(_ request: URLRequest, inSourceRoot: Bool = true) {
|
|
232
|
-
if let url = request.url { ownLoads.
|
|
184
|
+
if let url = request.url { ownLoads.started(url) }
|
|
233
185
|
if let url = request.url, url.isFileURL {
|
|
234
186
|
let access = ReadAccess.root(for: url, inSourceRoot ? source?.readAccessRoot : nil)
|
|
235
187
|
if let warning = access.warning { warn(warning) }
|
|
236
|
-
webView?.loadFileURL(url, allowingReadAccessTo: access.root)
|
|
188
|
+
let navigation = webView?.loadFileURL(url, allowingReadAccessTo: access.root)
|
|
189
|
+
if !inSourceRoot { directoryOnlyNavigation = navigation }
|
|
237
190
|
} else {
|
|
238
191
|
webView?.load(request)
|
|
239
192
|
}
|
|
240
193
|
}
|
|
241
194
|
|
|
242
|
-
/// The ref's reload: an explicit retry starts the crash-loop guard over, like a new source. Pull-to-refresh uses
|
|
243
|
-
/// reload().
|
|
244
195
|
func retry() {
|
|
245
196
|
crashTimes = []
|
|
246
197
|
reload()
|
|
@@ -248,37 +199,27 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
|
|
|
248
199
|
|
|
249
200
|
func reload() {
|
|
250
201
|
recoveryPending = false
|
|
251
|
-
// WebKit's reload redoes no failed load, POST or html source
|
|
252
|
-
// is nil (no commit, a dead process).
|
|
202
|
+
// WebKit's reload redoes no failed load, POST or html source, and loads nothing while `url` is nil.
|
|
253
203
|
let onHtmlSource = onSource && source?.uri == nil
|
|
254
|
-
if let webView, webView.url != nil,
|
|
204
|
+
if let webView, webView.url != nil, failedLoad == nil, !onPostSource, !onHtmlSource { webView.reload() } else { loadAgain() }
|
|
255
205
|
}
|
|
256
206
|
|
|
257
|
-
/// Loads the page on screen again, as crash recovery does. In order:
|
|
258
|
-
/// - the `source`, when it is the page or nothing has committed (so its headers, POST body or html are used);
|
|
259
|
-
/// - else the failed URL;
|
|
260
|
-
/// - else the back-forward list's item (a dead web process relaunches with it, so history stays).
|
|
261
|
-
/// A `source` being prepared loads once it is ready instead.
|
|
262
207
|
private func loadAgain() {
|
|
263
208
|
guard let webView, !preparing else { return }
|
|
264
|
-
if let source, onSource ||
|
|
209
|
+
if let source, onSource || failedLoad == nil && webView.backForwardList.currentItem == nil {
|
|
265
210
|
load(source)
|
|
266
|
-
} else if let
|
|
267
|
-
loadProgrammatic(URLRequest(url: target), inSourceRoot:
|
|
211
|
+
} else if let failedLoad, let target = URL(string: failedLoad.url) {
|
|
212
|
+
loadProgrammatic(URLRequest(url: target), inSourceRoot: failedLoad.inSourceRoot)
|
|
268
213
|
} else {
|
|
269
214
|
webView.reload()
|
|
270
215
|
}
|
|
271
216
|
}
|
|
272
217
|
|
|
273
|
-
/// `source` loads from applyProps once the load is prepared.
|
|
274
218
|
private func createWebView() {
|
|
275
219
|
let configuration = WKWebViewConfiguration()
|
|
276
|
-
// The creation-time settings (`ios.configuration`) and the configure hooks go first and the bridge after them,
|
|
277
|
-
// so nothing they set displaces the content controller the bridge is installed in.
|
|
278
220
|
report(platformSettings.apply(settings, webView: nil, configuration: configuration))
|
|
279
221
|
hookContexts = MinimalWebViewHooks.hooks.filter { hookOptions[$0.key] != nil }.map { HookContext($0, self) }
|
|
280
222
|
for context in hookContexts { context.hook.configure?(configuration, context) }
|
|
281
|
-
// A typo, or a hook's module not linked or not rebuilt.
|
|
282
223
|
for key in hookOptions.keys where !hookContexts.contains(where: { $0.key == key }) {
|
|
283
224
|
warn("extension \(key): no hook is registered under this key")
|
|
284
225
|
}
|
|
@@ -306,18 +247,14 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
|
|
|
306
247
|
webView.observe(\.estimatedProgress) { _, _ in update() }
|
|
307
248
|
] + [\WKWebView.canGoBack, \.canGoForward].map { webView.observe($0) { _, _ in update() } }
|
|
308
249
|
self.webView = webView
|
|
309
|
-
cookies.didCreate(webView)
|
|
310
|
-
// The live settings before the hooks, as on Android: what a hook sets wins over the package's defaults.
|
|
311
250
|
report(platformSettings.apply(settings, webView: webView))
|
|
312
251
|
hookContexts.forEach { $0.hook.attach(webView, $0) }
|
|
313
252
|
}
|
|
314
253
|
|
|
315
|
-
/// React Native calls `invalidate`
|
|
316
|
-
///
|
|
317
|
-
/// runtime, and it calls the inherited one as `super` would.
|
|
254
|
+
/// React Native calls `invalidate` at every unmount (Expo's views are never recycled), and Expo's (React Native 0.82+) resets its size-update guard.
|
|
255
|
+
/// Expo's Swift-visible header doesn't declare it, so Swift can't `override` it: this one wins at runtime.
|
|
318
256
|
@objc func invalidate() {
|
|
319
257
|
tearDown()
|
|
320
|
-
// Expo's (React Native 0.82+) resets its size-update guard; React Native's UIView default does nothing.
|
|
321
258
|
let selector = #selector(invalidate)
|
|
322
259
|
typealias Invalidate = @convention(c) (AnyObject, Selector) -> Void
|
|
323
260
|
guard class_respondsToSelector(ExpoView.self, selector),
|
|
@@ -325,12 +262,10 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
|
|
|
325
262
|
unsafeBitCast(inherited, to: Invalidate.self)(self, selector)
|
|
326
263
|
}
|
|
327
264
|
|
|
328
|
-
/// Once: from invalidate, or from deinit if that never ran (there weak self is nil, so in-flight evaluates can't be
|
|
329
|
-
/// rejected).
|
|
330
265
|
private func tearDown() {
|
|
331
266
|
guard let webView else { return }
|
|
332
267
|
endDocument(.closing)
|
|
333
|
-
cookies.
|
|
268
|
+
cookies.set(false, for: webView.configuration.websiteDataStore.httpCookieStore)
|
|
334
269
|
let closed = hookContexts
|
|
335
270
|
closed.forEach { $0.detach() }
|
|
336
271
|
hookContexts = []
|
|
@@ -352,26 +287,21 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
|
|
|
352
287
|
MainActor.assumeIsolated { tearDown() }
|
|
353
288
|
}
|
|
354
289
|
|
|
355
|
-
/// The page on screen: the back-forward list's current item, which a commit creates or moves to a moment before
|
|
356
|
-
/// didCommit (a history step may move it earlier), and pushState/replaceState/hash update.
|
|
357
290
|
private func refreshUrls() {
|
|
358
291
|
guard let webView else { return }
|
|
359
292
|
let item = webView.backForwardList.currentItem
|
|
360
|
-
// Empty before the first commit: the URL being loaded is pendingUrl.
|
|
361
293
|
let committed = htmlCommit.flatMap { $0.item === item ? $0.url : nil } ?? item?.url.absoluteString ?? ""
|
|
362
|
-
url =
|
|
294
|
+
url = failedLoad?.url ?? committed
|
|
363
295
|
// WebKit's `url` is the active URL: a pending or provisional load shows here first.
|
|
364
296
|
let active = webView.url?.absoluteString
|
|
365
297
|
pendingUrl = webView.isLoading && active != committed ? active : nil
|
|
366
|
-
if !webView.isLoading,
|
|
298
|
+
if !webView.isLoading, failedLoad != nil || active == committed { hookUrl = url }
|
|
367
299
|
}
|
|
368
300
|
|
|
369
|
-
/// WebKit's KVO fires before the delegate callbacks
|
|
370
|
-
///
|
|
371
|
-
/// load that starts and fails within one pass must still reach JS as loading true -> false. The end of a load waits
|
|
372
|
-
/// for the pass, because WebKit clears isLoading before it reports the failure (the error and outcome go first).
|
|
301
|
+
/// WebKit's KVO fires before the delegate callbacks, and clears isLoading before it reports a failure: the state is
|
|
302
|
+
/// read a main-queue turn later.
|
|
373
303
|
private func scheduleUpdate() {
|
|
374
|
-
if
|
|
304
|
+
if loadStartUnsent { emitState() }
|
|
375
305
|
guard !updateScheduled else { return }
|
|
376
306
|
updateScheduled = true
|
|
377
307
|
DispatchQueue.main.async { [weak self] in
|
|
@@ -382,6 +312,8 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
|
|
|
382
312
|
}
|
|
383
313
|
}
|
|
384
314
|
|
|
315
|
+
private var loadStartUnsent: Bool { webView?.isLoading == true && lastEmitted?["loading"] as? Bool != true }
|
|
316
|
+
|
|
385
317
|
private func emitState() {
|
|
386
318
|
guard let webView else { return }
|
|
387
319
|
let state: NSDictionary = [
|
|
@@ -392,33 +324,17 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
|
|
|
392
324
|
"progress": webView.estimatedProgress,
|
|
393
325
|
"canGoBack": webView.canGoBack,
|
|
394
326
|
"canGoForward": webView.canGoForward,
|
|
395
|
-
"outcome": webView.isLoading ? NSNull() : outcome as Any? ?? NSNull()
|
|
327
|
+
"outcome": webView.isLoading ? NSNull() : outcome?.rawValue as Any? ?? NSNull()
|
|
396
328
|
]
|
|
397
329
|
guard state != lastEmitted else { return }
|
|
398
330
|
lastEmitted = state
|
|
399
331
|
onNavigationState(state as? [String: Any] ?? [:])
|
|
400
332
|
}
|
|
401
333
|
|
|
402
|
-
/// An observation callback the core implements: every hook delegate that implements it gets it after the core.
|
|
403
334
|
private func forward(_ callback: (WKNavigationDelegate) -> Void) {
|
|
404
335
|
proxy.navigationDelegates.forEach(callback)
|
|
405
336
|
}
|
|
406
337
|
|
|
407
|
-
/// A main-frame load WebKit ended with `error`: reports it to onError when it failed (`Loads.ended`), and returns its
|
|
408
|
-
/// outcome.
|
|
409
|
-
private func ended(with error: Error) -> String {
|
|
410
|
-
let nsError = error as NSError
|
|
411
|
-
let end = Loads.ended(by: nsError)
|
|
412
|
-
guard let kind = end.kind else { return end.outcome }
|
|
413
|
-
let failing = (nsError.userInfo[NSURLErrorFailingURLErrorKey] as? URL)?.absoluteString
|
|
414
|
-
?? nsError.userInfo[NSURLErrorFailingURLStringErrorKey] as? String ?? pendingUrl ?? url
|
|
415
|
-
failedUrl = failing
|
|
416
|
-
onError(["kind": kind, "url": failing, "code": nsError.code, "description": nsError.localizedDescription])
|
|
417
|
-
return end.outcome
|
|
418
|
-
}
|
|
419
|
-
|
|
420
|
-
// MARK: WKNavigationDelegate
|
|
421
|
-
|
|
422
338
|
func webView(
|
|
423
339
|
_ webView: WKWebView,
|
|
424
340
|
decidePolicyFor navigationAction: WKNavigationAction,
|
|
@@ -460,8 +376,8 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
|
|
|
460
376
|
|
|
461
377
|
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
|
|
462
378
|
endDocument(.committed)
|
|
463
|
-
ownLoads.
|
|
464
|
-
|
|
379
|
+
ownLoads.committed()
|
|
380
|
+
failedLoad = nil
|
|
465
381
|
htmlCommit = navigation === htmlNavigation
|
|
466
382
|
? (webView.url?.absoluteString ?? "about:blank", webView.backForwardList.currentItem) : nil
|
|
467
383
|
refreshUrls()
|
|
@@ -471,30 +387,48 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
|
|
|
471
387
|
}
|
|
472
388
|
|
|
473
389
|
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
|
|
474
|
-
loadEnded { $0.webView?(webView, didFinish: navigation) }
|
|
390
|
+
loadEnded(.finished) { $0.webView?(webView, didFinish: navigation) }
|
|
475
391
|
}
|
|
476
392
|
|
|
477
393
|
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
|
|
478
|
-
|
|
394
|
+
loadFailed(webView, navigation, error, provisional: false)
|
|
479
395
|
}
|
|
480
396
|
|
|
481
397
|
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
|
|
482
|
-
|
|
398
|
+
loadFailed(webView, navigation, error, provisional: true)
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
private func loadFailed(_ webView: WKWebView, _ navigation: WKNavigation?, _ error: Error, provisional: Bool) {
|
|
402
|
+
let nsError = error as NSError
|
|
403
|
+
let end = Loads.ended(by: nsError)
|
|
404
|
+
if let kind = end.kind {
|
|
405
|
+
let failing = (nsError.userInfo[NSURLErrorFailingURLErrorKey] as? URL)?.absoluteString
|
|
406
|
+
?? nsError.userInfo[NSURLErrorFailingURLStringErrorKey] as? String ?? pendingUrl ?? url
|
|
407
|
+
failedLoad = (failing, inSourceRoot: navigation == nil || navigation !== directoryOnlyNavigation)
|
|
408
|
+
onError(["kind": kind, "url": failing, "code": nsError.code, "description": nsError.localizedDescription])
|
|
409
|
+
}
|
|
410
|
+
loadEnded(end.outcome) {
|
|
411
|
+
if provisional {
|
|
412
|
+
$0.webView?(webView, didFailProvisionalNavigation: navigation, withError: error)
|
|
413
|
+
} else {
|
|
414
|
+
$0.webView?(webView, didFail: navigation, withError: error)
|
|
415
|
+
}
|
|
416
|
+
}
|
|
483
417
|
}
|
|
484
418
|
|
|
485
|
-
private func loadEnded(_
|
|
486
|
-
outcome =
|
|
419
|
+
private func loadEnded(_ outcome: Loads.Outcome, _ callback: (WKNavigationDelegate) -> Void) {
|
|
420
|
+
self.outcome = outcome
|
|
487
421
|
// The spinner stops, or it would ignore the next pull.
|
|
488
422
|
refreshControl.endRefreshing()
|
|
489
423
|
scheduleUpdate()
|
|
490
424
|
forward(callback)
|
|
491
425
|
}
|
|
492
426
|
|
|
493
|
-
/// The
|
|
427
|
+
/// The WKWebView survives its web content process's death.
|
|
494
428
|
func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
|
|
495
429
|
let recovered = Recovery.crashAllowsReload(&crashTimes, now: ProcessInfo.processInfo.systemUptime) && !onPostSource
|
|
496
430
|
endDocument(.crashed)
|
|
497
|
-
if lastEmitted?["loading"] as? Bool == true { outcome =
|
|
431
|
+
if lastEmitted?["loading"] as? Bool == true { outcome = .failed }
|
|
498
432
|
if recovered {
|
|
499
433
|
recoveryPending = true
|
|
500
434
|
recoverIfVisible()
|
|
@@ -504,9 +438,7 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
|
|
|
504
438
|
}
|
|
505
439
|
}
|
|
506
440
|
|
|
507
|
-
/// What the hooks see of this view, through a HookContext per attached hook.
|
|
508
441
|
extension MinimalWebView {
|
|
509
|
-
/// Tells each attached hook whose value changed, and attaches a hook without `configure` or `webViewClass` whose key turns on.
|
|
510
442
|
private func optionsChanged(from old: [String: Any]) {
|
|
511
443
|
for key in inRegistrationOrder(Set(old.keys).union(hookOptions.keys), MinimalWebViewHooks.hooks.map(\.key)) {
|
|
512
444
|
let (was, value) = (old[key], hookOptions[key])
|
|
@@ -523,7 +455,6 @@ extension MinimalWebView {
|
|
|
523
455
|
guard let webView, let hook = MinimalWebViewHooks.hooks.first(where: { $0.key == key }) else {
|
|
524
456
|
return warn("extension \(key): no hook is registered under this key")
|
|
525
457
|
}
|
|
526
|
-
// configure edits the configuration the WKWebView was created from, and webViewClass makes it: too late for this one.
|
|
527
458
|
guard hook.configure == nil, hook.webViewClass == nil else {
|
|
528
459
|
let why = hook.configure != nil ? "configure" : "a webViewClass"
|
|
529
460
|
return warn("extension \(key): its hook has \(why), so it attaches only when the WebView is created")
|
|
@@ -537,7 +468,6 @@ extension MinimalWebView {
|
|
|
537
468
|
hookContexts.first { $0.key == key && $0.isOn }?.handlers[method]
|
|
538
469
|
}
|
|
539
470
|
|
|
540
|
-
/// Gives the proxy the delegates of the hooks that are on, in attach order, then each hook's own order.
|
|
541
471
|
func routeDelegates() {
|
|
542
472
|
let on = hookContexts.filter(\.isOn)
|
|
543
473
|
proxy.navigationDelegates = on.flatMap(\.navigationDelegates)
|
|
@@ -41,7 +41,7 @@ public class MinimalWebViewModule: Module {
|
|
|
41
41
|
AsyncFunction("bridgePost") { (view: MinimalWebView, message: String) in view.bridgePost(message) }
|
|
42
42
|
AsyncFunction("answer") { (view: MinimalWebView, askId: Int, json: String) in
|
|
43
43
|
let value = try? JSONSerialization.jsonObject(with: Data(json.utf8), options: .fragmentsAllowed)
|
|
44
|
-
view.asks.answer(askId, value is NSNull ? nil : value)
|
|
44
|
+
MainActor.assumeIsolated { view.asks.answer(askId, value is NSNull ? nil : value) }
|
|
45
45
|
}
|
|
46
46
|
AsyncFunction("hook") { (view: MinimalWebView, name: String, method: String, args: String, promise: Promise) in
|
|
47
47
|
hook(view, name, method, args, promise)
|
|
@@ -92,20 +92,3 @@ private func reject(_ promise: Promise, _ error: Error) {
|
|
|
92
92
|
let platform = error as? PlatformError
|
|
93
93
|
promise.reject(platform?.code ?? "native_error", platform?.message ?? error.localizedDescription)
|
|
94
94
|
}
|
|
95
|
-
|
|
96
|
-
// A prop that fails to convert is dropped whole (ExpoFabricView's try?), so every field is optional.
|
|
97
|
-
|
|
98
|
-
struct WebViewSource: Record {
|
|
99
|
-
@Field var uri: String? = nil
|
|
100
|
-
@Field var headers: [String: String]? = nil
|
|
101
|
-
@Field var body: String? = nil
|
|
102
|
-
@Field var readAccessRoot: String? = nil
|
|
103
|
-
@Field var html: String? = nil
|
|
104
|
-
@Field var baseUrl: String? = nil
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
struct InjectedScript: Record {
|
|
108
|
-
@Field var code: String? = nil
|
|
109
|
-
@Field var allFrames: Bool? = nil
|
|
110
|
-
}
|
|
111
|
-
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import Foundation
|
|
2
2
|
|
|
3
|
-
/// The structured navigation rules. Semantics and cases: src/__tests__/vectors/navigation-rules.json (shared with Kotlin).
|
|
4
3
|
enum NavigationRules {
|
|
5
4
|
struct Request {
|
|
6
5
|
let url: String
|
|
@@ -8,7 +7,6 @@ enum NavigationRules {
|
|
|
8
7
|
let newWindow: Bool
|
|
9
8
|
let userInitiated: Bool
|
|
10
9
|
|
|
11
|
-
/// The fields JS events carry.
|
|
12
10
|
var payload: [String: Any] {
|
|
13
11
|
["url": url, "mainFrame": mainFrame, "newWindow": newWindow, "userInitiated": userInitiated]
|
|
14
12
|
}
|
|
@@ -22,7 +20,6 @@ enum NavigationRules {
|
|
|
22
20
|
let rule: Int?
|
|
23
21
|
}
|
|
24
22
|
|
|
25
|
-
/// What rules match; `params` are the query's `&`-separated parameters.
|
|
26
23
|
private struct Parts {
|
|
27
24
|
let scheme: String
|
|
28
25
|
let host: String?
|
|
@@ -30,10 +27,8 @@ enum NavigationRules {
|
|
|
30
27
|
let params: [String]
|
|
31
28
|
}
|
|
32
29
|
|
|
33
|
-
/// Load in place without the rules.
|
|
34
30
|
private static let internalSchemes: Set<String> = ["about", "data", "javascript"]
|
|
35
|
-
///
|
|
36
|
-
/// past the engine's limits on what a page may navigate the top frame to.
|
|
31
|
+
/// The core loads an allowed new window itself, past WebKit's limits on what a page may navigate the top frame to.
|
|
37
32
|
private static let noNewWindowSchemes = internalSchemes.union(["blob", "file"])
|
|
38
33
|
|
|
39
34
|
/// The rules' decision, gated for `ask`: blocked when nothing can answer it (`canAsk` false), allowed when its URL is
|
|
@@ -55,7 +50,6 @@ enum NavigationRules {
|
|
|
55
50
|
let scheme = request.url.firstIndex(of: ":").map { request.url[..<$0].lowercased() } ?? ""
|
|
56
51
|
if request.newWindow, noNewWindowSchemes.contains(scheme) { return Decision(action: .block, rule: nil) }
|
|
57
52
|
if internalSchemes.contains(scheme) { return Decision(action: .allow, rule: nil) }
|
|
58
|
-
// JS sends defaultNavigationRules when the prop is unset; no rules, nil or empty, match nothing.
|
|
59
53
|
guard let rules, !rules.isEmpty,
|
|
60
54
|
let parts = scheme == "blob" ? blobOrigin(request.url) : urlParts(scheme, request.url)
|
|
61
55
|
else { return Decision(action: .block, rule: nil) }
|
|
@@ -66,10 +60,9 @@ enum NavigationRules {
|
|
|
66
60
|
}
|
|
67
61
|
|
|
68
62
|
private static func urlParts(_ scheme: String, _ url: String) -> Parts {
|
|
69
|
-
// shortcut: an unparseable URL has no host and path "/", so only host-less rules match; parse it by hand when a rule must match such URLs
|
|
70
63
|
let components = URLComponents(string: url)
|
|
71
64
|
let rawPath = components?.percentEncodedPath ?? ""
|
|
72
|
-
//
|
|
65
|
+
// URLComponents gives `file:///x` an empty host, not none.
|
|
73
66
|
let path = rawPath.isEmpty || components?.host == nil ? "/" : rawPath
|
|
74
67
|
let params = components?.percentEncodedQuery?.split(separator: "&").map(String.init) ?? []
|
|
75
68
|
return Parts(scheme: scheme, host: host(components), path: path, params: params)
|
package/ios/OriginRules.swift
CHANGED
|
@@ -1,14 +1,8 @@
|
|
|
1
1
|
import Foundation
|
|
2
2
|
import WebKit
|
|
3
3
|
|
|
4
|
-
/// Origin rules in Android's format (the bridge's `allowedOrigins`):
|
|
5
|
-
/// `*`, an exact http(s) origin such as `https://example.com:8443`, or `https://*.example.com` for subdomains.
|
|
6
|
-
/// Compared case-insensitively, a missing port is the scheme's default, and a malformed rule matches nothing.
|
|
7
|
-
/// createBridge validates the rules on the JS side. Cases: src/__tests__/vectors/origin-rules.json.
|
|
8
4
|
enum OriginRules {
|
|
9
|
-
/// The origin
|
|
10
|
-
/// without `baseUrl`, a sandboxed page). The default port is left out (WebKit reports it as 0) and an IPv6 host is
|
|
11
|
-
/// bracketed.
|
|
5
|
+
/// The origin as `location.origin` writes it: `null` for an opaque one (no scheme). WebKit reports a default port as 0.
|
|
12
6
|
static func origin(_ scheme: String, _ host: String, _ port: Int) -> String {
|
|
13
7
|
guard !scheme.isEmpty else { return "null" }
|
|
14
8
|
let defaultPort = scheme == "https" ? 443 : scheme == "http" ? 80 : nil
|
|
@@ -16,12 +10,11 @@ enum OriginRules {
|
|
|
16
10
|
return "\(scheme)://\(host)" + (port == 0 || port == defaultPort ? "" : ":\(port)")
|
|
17
11
|
}
|
|
18
12
|
|
|
19
|
-
/// The origin as `location.origin` writes it, so the bridge can compare the two exactly.
|
|
20
13
|
static func origin(of security: WKSecurityOrigin) -> String {
|
|
21
14
|
origin(security.protocol, security.host, security.port)
|
|
22
15
|
}
|
|
23
16
|
|
|
24
|
-
static func allows(_ rules: [String], _ origin: String) -> Bool {
|
|
17
|
+
@MainActor static func allows(_ rules: [String], _ origin: String) -> Bool {
|
|
25
18
|
let value = parse(origin)
|
|
26
19
|
return rules.contains { rule in
|
|
27
20
|
guard let r = parse(rule), let o = value, !o.wildcard else { return rule == "*" }
|
|
@@ -29,13 +22,11 @@ enum OriginRules {
|
|
|
29
22
|
}
|
|
30
23
|
}
|
|
31
24
|
|
|
32
|
-
|
|
33
|
-
// caller is a WebKit delegate callback on the main thread.
|
|
34
|
-
nonisolated(unsafe) private static let pattern = #/(https?):\/\/(\*\.(?!\[))?([a-z0-9_-]+(?:\.[a-z0-9_-]+)*|\[[0-9a-f:.]+\])(?::(\d{1,5}))?/#
|
|
25
|
+
@MainActor private static let pattern = #/(https?):\/\/(\*\.(?!\[))?([a-z0-9_-]+(?:\.[a-z0-9_-]+)*|\[[0-9a-f:.]+\])(?::(\d{1,5}))?/#
|
|
35
26
|
|
|
36
27
|
private struct Parsed { let scheme: Substring, wildcard: Bool, host: Substring, port: Int }
|
|
37
28
|
|
|
38
|
-
private static func parse(_ text: String) -> Parsed? {
|
|
29
|
+
@MainActor private static func parse(_ text: String) -> Parsed? {
|
|
39
30
|
guard let m = try? pattern.wholeMatch(in: text.lowercased()) else { return nil }
|
|
40
31
|
return Parsed(scheme: m.1, wildcard: m.2 != nil, host: m.3, port: m.4.flatMap { Int($0) } ?? (m.1 == "https" ? 443 : 80))
|
|
41
32
|
}
|