react-native-minimal-webview 1.0.1 → 1.2.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 (78) hide show
  1. package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +19 -32
  2. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +55 -26
  3. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +3 -3
  4. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +2 -1
  5. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +8 -8
  6. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +5 -7
  7. package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +32 -44
  8. package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +2 -2
  9. package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +7 -8
  10. package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +2 -2
  11. package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +4 -5
  12. package/build/WebView.d.ts +1 -9
  13. package/build/WebView.d.ts.map +1 -1
  14. package/build/WebView.js +37 -107
  15. package/build/WebView.js.map +1 -1
  16. package/build/bridge/createBridge.d.ts +19 -13
  17. package/build/bridge/createBridge.d.ts.map +1 -1
  18. package/build/bridge/createBridge.js +33 -45
  19. package/build/bridge/createBridge.js.map +1 -1
  20. package/build/bridge/endpoint.d.ts +3 -8
  21. package/build/bridge/endpoint.d.ts.map +1 -1
  22. package/build/bridge/endpoint.js +2 -3
  23. package/build/bridge/endpoint.js.map +1 -1
  24. package/build/bridge/origins.d.ts +5 -2
  25. package/build/bridge/origins.d.ts.map +1 -1
  26. package/build/bridge/origins.js +15 -4
  27. package/build/bridge/origins.js.map +1 -1
  28. package/build/bridge/pageClient.generated.d.ts +1 -1
  29. package/build/bridge/pageClient.generated.d.ts.map +1 -1
  30. package/build/bridge/pageClient.generated.js +1 -1
  31. package/build/bridge/pageClient.generated.js.map +1 -1
  32. package/build/index.d.ts +1 -1
  33. package/build/index.d.ts.map +1 -1
  34. package/build/index.js +1 -1
  35. package/build/index.js.map +1 -1
  36. package/build/{defaultNavigationRules.d.ts → navigationRules.d.ts} +10 -1
  37. package/build/navigationRules.d.ts.map +1 -0
  38. package/build/navigationRules.js +93 -0
  39. package/build/navigationRules.js.map +1 -0
  40. package/build/refStore.d.ts.map +1 -1
  41. package/build/refStore.js +13 -19
  42. package/build/refStore.js.map +1 -1
  43. package/build/types.d.ts +55 -35
  44. package/build/types.d.ts.map +1 -1
  45. package/ios/DelegateProxy.swift +32 -30
  46. package/ios/DocumentEnd.swift +1 -2
  47. package/ios/Hooks.swift +28 -28
  48. package/ios/Loads.swift +5 -4
  49. package/ios/MRWInvoke.h +10 -9
  50. package/ios/MRWInvoke.m +39 -24
  51. package/ios/MinimalWebView+Navigation.swift +18 -16
  52. package/ios/MinimalWebView+Scripts.swift +0 -8
  53. package/ios/MinimalWebView.podspec +0 -1
  54. package/ios/MinimalWebView.swift +77 -35
  55. package/ios/MinimalWebViewModule.swift +1 -0
  56. package/ios/NavigationRules.swift +15 -15
  57. package/ios/OriginRules.swift +6 -0
  58. package/ios/PlatformSettings.swift +3 -22
  59. package/ios/Recovery.swift +6 -5
  60. package/ios/SharedCookies.swift +1 -2
  61. package/package.json +7 -3
  62. package/src/WebView.tsx +50 -123
  63. package/src/bridge/createBridge.ts +48 -56
  64. package/src/bridge/endpoint.ts +6 -9
  65. package/src/bridge/origins.ts +18 -6
  66. package/src/bridge/pageClient.generated.ts +1 -1
  67. package/src/bridge/pageClient.ts +3 -7
  68. package/src/bridge/protocol.ts +1 -1
  69. package/src/index.ts +1 -1
  70. package/src/navigationRules.ts +111 -0
  71. package/src/refStore.ts +15 -21
  72. package/src/types.ts +56 -35
  73. package/build/defaultNavigationRules.d.ts.map +0 -1
  74. package/build/defaultNavigationRules.js +0 -22
  75. package/build/defaultNavigationRules.js.map +0 -1
  76. package/ios/MRWExceptions.h +0 -9
  77. package/ios/MRWExceptions.m +0 -10
  78. package/src/defaultNavigationRules.ts +0 -24
package/ios/MRWInvoke.m CHANGED
@@ -1,22 +1,35 @@
1
1
  #import "MRWInvoke.h"
2
- #import "MRWExceptions.h"
3
2
  #import <UIKit/UIKit.h>
4
3
 
5
- static NSDictionary *MRWStruct(NSValue *value) {
6
- const char *type = value.objCType;
7
- if (strcmp(type, @encode(UIEdgeInsets)) == 0) {
8
- UIEdgeInsets i = value.UIEdgeInsetsValue;
9
- return @{@"top": @(i.top), @"left": @(i.left), @"bottom": @(i.bottom), @"right": @(i.right)};
10
- }
11
- if (strcmp(type, @encode(CGPoint)) == 0) return @{@"x": @(value.CGPointValue.x), @"y": @(value.CGPointValue.y)};
12
- if (strcmp(type, @encode(CGSize)) == 0) return @{@"width": @(value.CGSizeValue.width), @"height": @(value.CGSizeValue.height)};
13
- if (strcmp(type, @encode(CGRect)) == 0) {
14
- CGRect r = value.CGRectValue;
15
- return @{@"x": @(r.origin.x), @"y": @(r.origin.y), @"width": @(r.size.width), @"height": @(r.size.height)};
4
+ NSString *MRWCatchException(void (NS_NOESCAPE ^block)(void)) {
5
+ @try {
6
+ block();
7
+ return nil;
8
+ } @catch (NSException *exception) {
9
+ return [NSString stringWithFormat:@"%@: %@", exception.name, exception.reason ?: @""];
16
10
  }
11
+ }
12
+
13
+ /// The JSON keys of a struct `call` and the settings carry, in field order, by its type encoding; nil for any other.
14
+ /// Each one's fields are doubles (CGFloat), so its bytes are the values in that order.
15
+ static NSArray<NSString *> *MRWStructKeys(const char *type) {
16
+ if (strcmp(type, @encode(UIEdgeInsets)) == 0) return @[@"top", @"left", @"bottom", @"right"];
17
+ if (strcmp(type, @encode(CGPoint)) == 0) return @[@"x", @"y"];
18
+ if (strcmp(type, @encode(CGSize)) == 0) return @[@"width", @"height"];
19
+ if (strcmp(type, @encode(CGRect)) == 0) return @[@"x", @"y", @"width", @"height"];
17
20
  return nil;
18
21
  }
19
22
 
23
+ static NSDictionary *MRWStruct(NSValue *value) {
24
+ NSArray<NSString *> *keys = MRWStructKeys(value.objCType);
25
+ if (!keys) return nil;
26
+ double n[4];
27
+ [value getValue:n size:keys.count * sizeof(double)];
28
+ NSMutableDictionary *json = [NSMutableDictionary new];
29
+ for (NSUInteger i = 0; i < keys.count; i++) json[keys[i]] = @(n[i]);
30
+ return json;
31
+ }
32
+
20
33
  id MRWJsonable(id value) {
21
34
  if ([value isKindOfClass:NSNumber.class] || [value isKindOfClass:NSString.class]) return value;
22
35
  if ([value isKindOfClass:NSURL.class]) return [value absoluteString];
@@ -56,9 +69,9 @@ static id MRWObject(id json) {
56
69
  return json;
57
70
  }
58
71
 
59
- /// Reads `keys` of `object` as numbers into `out`; NO when one is missing or not a number.
72
+ /// Reads `keys` of `object` as numbers into `out`; NO when `keys` is nil or one is missing or not a number.
60
73
  static BOOL MRWNumbers(id object, NSArray<NSString *> *keys, double *out) {
61
- if (![object isKindOfClass:NSDictionary.class]) return NO;
74
+ if (!keys || ![object isKindOfClass:NSDictionary.class]) return NO;
62
75
  for (NSUInteger i = 0; i < keys.count; i++) {
63
76
  id number = object[keys[i]];
64
77
  if (![number isKindOfClass:NSNumber.class]) return NO;
@@ -67,6 +80,11 @@ static BOOL MRWNumbers(id object, NSArray<NSString *> *keys, double *out) {
67
80
  return YES;
68
81
  }
69
82
 
83
+ NSValue *MRWStructValue(const char *type, id json) {
84
+ double n[4];
85
+ return MRWNumbers(json, MRWStructKeys(type), n) ? [NSValue valueWithBytes:n objCType:type] : nil;
86
+ }
87
+
70
88
  #define MRW_SET(ctype, expr) { ctype v = (expr); [invocation setArgument:&v atIndex:index]; return YES; }
71
89
 
72
90
  /// Sets argument `index` from the JSON `value` as the type encoding `type` wants it, or returns NO when it doesn't fit.
@@ -96,10 +114,7 @@ static BOOL MRWSetArgument(NSInvocation *invocation, NSUInteger index, const cha
96
114
  MRW_SET(id, object)
97
115
  }
98
116
  case '{':
99
- if (strcmp(type, @encode(UIEdgeInsets)) == 0 && MRWNumbers(value, @[@"top", @"left", @"bottom", @"right"], n)) MRW_SET(UIEdgeInsets, UIEdgeInsetsMake(n[0], n[1], n[2], n[3]))
100
- if (strcmp(type, @encode(CGPoint)) == 0 && MRWNumbers(value, @[@"x", @"y"], n)) MRW_SET(CGPoint, CGPointMake(n[0], n[1]))
101
- if (strcmp(type, @encode(CGSize)) == 0 && MRWNumbers(value, @[@"width", @"height"], n)) MRW_SET(CGSize, CGSizeMake(n[0], n[1]))
102
- if (strcmp(type, @encode(CGRect)) == 0 && MRWNumbers(value, @[@"x", @"y", @"width", @"height"], n)) MRW_SET(CGRect, CGRectMake(n[0], n[1], n[2], n[3]))
117
+ if (MRWNumbers(value, MRWStructKeys(type), n)) { [invocation setArgument:n atIndex:index]; return YES; }
103
118
  break;
104
119
  default: break;
105
120
  }
@@ -125,12 +140,12 @@ static id MRWReturnValue(NSInvocation *invocation) {
125
140
  case 'f': MRW_GET(float, @(v))
126
141
  case 'd': MRW_GET(double, @(v))
127
142
  case '@': { __unsafe_unretained id v = nil; [invocation getReturnValue:&v]; return v; }
128
- case '{':
129
- if (strcmp(type, @encode(UIEdgeInsets)) == 0) MRW_GET(UIEdgeInsets, [NSValue valueWithUIEdgeInsets:v])
130
- if (strcmp(type, @encode(CGPoint)) == 0) MRW_GET(CGPoint, [NSValue valueWithCGPoint:v])
131
- if (strcmp(type, @encode(CGSize)) == 0) MRW_GET(CGSize, [NSValue valueWithCGSize:v])
132
- if (strcmp(type, @encode(CGRect)) == 0) MRW_GET(CGRect, [NSValue valueWithCGRect:v])
133
- return NSNull.null;
143
+ case '{': {
144
+ if (!MRWStructKeys(type)) return NSNull.null;
145
+ double n[4];
146
+ [invocation getReturnValue:n];
147
+ return [NSValue valueWithBytes:n objCType:type];
148
+ }
134
149
  default: return NSNull.null;
135
150
  }
136
151
  }
@@ -11,10 +11,11 @@ extension MinimalWebView {
11
11
  // rules, as on Android (shouldOverrideUrlLoading is not called for them).
12
12
  guard let targetFrame = action.targetFrame else { return decide(allowInPlace) }
13
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
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
16
17
  || action.request.httpMethod == "POST" {
17
- if own { programmaticUrl = nil }
18
+ if let own { ownLoads.remove(at: own) }
18
19
  return decide(allowInPlace)
19
20
  }
20
21
  let request = NavigationRules.Request(
@@ -37,8 +38,7 @@ extension MinimalWebView {
37
38
  /// Whether a user gesture started `action`: a link activation right after a tap on this view (`Taps`). WebKit
38
39
  /// reports every navigation with a triggering event as `.linkActivated` (NavigationAction.cpp's navigationType),
39
40
  /// including a link a script clicks (`element.click()`), and no public WKNavigationAction property tells a real one
40
- /// apart. VoiceOver and Switch Control activate a link with no touch, so while either runs, a link activation counts
41
- /// on its own. A hardware keyboard's activation doesn't.
41
+ /// apart.
42
42
  private func userInitiated(_ action: WKNavigationAction) -> Bool {
43
43
  action.navigationType == .linkActivated
44
44
  && (taps.recent || UIAccessibility.isVoiceOverRunning || UIAccessibility.isSwitchControlRunning)
@@ -48,7 +48,7 @@ extension MinimalWebView {
48
48
  func openDownload(_ url: URL) {
49
49
  guard ["http", "https"].contains(url.scheme?.lowercased()) else { return }
50
50
  let request = NavigationRules.Request(url: url.absoluteString, mainFrame: true, newWindow: false, userInitiated: false)
51
- finish(request, "external", nil) { _ in }
51
+ finish(request, .external, nil) { _ in }
52
52
  }
53
53
 
54
54
  /// window.open and target=_blank. Never a second WKWebView: a popup model (presenting and closing a child,
@@ -89,7 +89,7 @@ extension MinimalWebView {
89
89
  navigationRules, request, asked: askedAndAllowed[request.mainFrame] ?? [],
90
90
  canAsk: requestHandlers.contains("onNavigationRequest")
91
91
  )
92
- guard decision.action == "ask" else {
92
+ guard decision.action == .ask else {
93
93
  finish(request, decision.action, decision.rule, completion)
94
94
  return
95
95
  }
@@ -97,7 +97,7 @@ extension MinimalWebView {
97
97
  // The view can be gone: the decision handler must still be called.
98
98
  guard let self else { return completion(false) }
99
99
  let action = NavigationRules.answer(answer)
100
- if action == "allow" { self.askedAndAllowed[request.mainFrame, default: []].insert(request.url) }
100
+ if action == .allow { self.askedAndAllowed[request.mainFrame, default: []].insert(request.url) }
101
101
  self.finish(request, action, decision.rule, completion)
102
102
  }
103
103
  // Unanswered after the timeout: block.
@@ -106,25 +106,27 @@ extension MinimalWebView {
106
106
  }
107
107
  }
108
108
 
109
- private func finish(_ request: NavigationRules.Request, _ action: String, _ rule: Int?, _ completion: (Bool) -> Void) {
110
- completion(action == "allow")
111
- guard action == "external" else { return report(request, action, rule) }
109
+ private func finish(
110
+ _ request: NavigationRules.Request, _ action: NavigationRules.Action, _ rule: Int?, _ completion: (Bool) -> Void
111
+ ) {
112
+ completion(action == .allow)
113
+ guard action == .external else { return report(request, action, rule) }
112
114
  guard requestHandlers.contains("onOpenExternal") else { return open(request, rule) }
113
115
  // A page that moved on first answers nil, which counts as opened. No timeout: nothing waits for the answer.
114
116
  asks.ask("core", "onOpenExternal", request.payload) { [weak self] answer in
115
- if answer as? Bool == false { self?.open(request, rule) } else { self?.report(request, "external", rule) }
117
+ if answer as? Bool == false { self?.open(request, rule) } else { self?.report(request, .external, rule) }
116
118
  }
117
119
  }
118
120
 
119
121
  /// Opens an `external` URL outside the WebView. As on Android, one that nothing opens is reported as blocked.
120
122
  private func open(_ request: NavigationRules.Request, _ rule: Int?) {
121
- guard let url = URL(string: request.url) else { return report(request, "block", rule) }
122
- UIApplication.shared.open(url) { [weak self] opened in self?.report(request, opened ? "external" : "block", rule) }
123
+ guard let url = URL(string: request.url) else { return report(request, .block, rule) }
124
+ UIApplication.shared.open(url) { [weak self] opened in self?.report(request, opened ? .external : .block, rule) }
123
125
  }
124
126
 
125
- private func report(_ request: NavigationRules.Request, _ action: String, _ rule: Int?) {
127
+ private func report(_ request: NavigationRules.Request, _ action: NavigationRules.Action, _ rule: Int?) {
126
128
  guard requestHandlers.contains("onNavigation") else { return }
127
- onNavigation(request.payload.merging(["action": action, "rule": rule as Any? ?? NSNull()]) { $1 })
129
+ onNavigation(request.payload.merging(["action": action.rawValue, "rule": rule as Any? ?? NSNull()]) { $1 })
128
130
  }
129
131
  }
130
132
 
@@ -82,11 +82,3 @@ final class WeakBridgeHandler: NSObject, WKScriptMessageHandler {
82
82
  view?.bridgeReceive(message)
83
83
  }
84
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
- }
@@ -18,7 +18,6 @@ Pod::Spec.new do |s|
18
18
 
19
19
  s.dependency 'ExpoModulesCore'
20
20
 
21
- # Swift/Objective-C compatibility
22
21
  s.pod_target_xcconfig = {
23
22
  'DEFINES_MODULE' => 'YES',
24
23
  # the documentation catalog, which CocoaPods can't add as a source
@@ -45,12 +45,10 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
45
45
  // Created once, from the first props: WebKit reads some WKWebViewConfiguration settings only at creation.
46
46
  private(set) var webView: WKWebView?
47
47
  private var observations: [NSKeyValueObservation] = []
48
- private(set) lazy var downloads = Downloads(view: self)
48
+ private lazy var downloads = Downloads(view: self)
49
49
  private lazy var proxy = DelegateProxy(core: self)
50
50
  /// When the user last tapped the WKWebView: a link activation counts as user-initiated only right after a tap.
51
51
  let taps = Taps(target: nil, action: nil)
52
- /// The decision warnings sent, shared and taken (DelegateProxy): one each per view.
53
- private var warnedDecisions: Set<String> = []
54
52
 
55
53
  // Navigation state, derived from WebKit in refreshUrls(). Native owns the committed URL; JS is told.
56
54
  private(set) var url = ""
@@ -63,15 +61,21 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
63
61
  /// while the item that was current at its commit stays current, the html page is what is on screen.
64
62
  private var htmlNavigation: WKNavigation?
65
63
  private var htmlCommit: (url: String, item: WKBackForwardListItem?)?
66
- /// The URL this view loads itself (source, reload after an error, an allowed new window): it skips the rules.
67
- var programmaticUrl: URL?
64
+ /// The loads this view starts itself (source, `load`, reload after an error, an allowed new window), each until its
65
+ /// main-frame policy check, which skips the rules, with `mainFrameChecks` at its start. A list: a load can start
66
+ /// before the previous one's check, and the page being left can commit after it. A commit drops the loads a later
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
68
70
  private(set) lazy var asks = Asks { [weak self] in self?.onHookEvent($0) }
69
71
  /// The attached hooks' contexts in attach order, for the life of the WKWebView: a hook may keep its own.
70
72
  var hookContexts: [HookContext] = []
71
73
  /// URLs an `ask` allowed in this Document, keyed by mainFrame: a subframe's answer doesn't decide the main frame's.
72
74
  var askedAndAllowed: [Bool: Set<String>] = [:]
73
- /// A `source` load is being prepared (shared cookies): loads wait until it is done.
75
+ /// A `source` or `load` load is being prepared (shared cookies): loads wait until it is done.
74
76
  private var preparing = false
77
+ /// The ref's `load` while it is prepared: it loads instead of the `source` being prepared, if any.
78
+ private var queuedUrl: URL?
75
79
  /// After a failed main-frame load `url` is the failed URL (as on Android, which commits an error page);
76
80
  /// WKWebView itself keeps the previous page, so `url` and reload() use this.
77
81
  private(set) var failedUrl: String?
@@ -80,6 +84,8 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
80
84
  private var lastEmitted: NSDictionary?
81
85
  private var updateScheduled = false
82
86
  private var crashTimes: [TimeInterval] = []
87
+ /// A web-process death whose reload waits until the view can be seen; a `load`, reload or new `source` replaces it.
88
+ private var recoveryPending = false
83
89
  /// `evaluate` calls waiting for their result, by id, until a new document or a dead web process rejects them.
84
90
  var evaluations: [Int: Promise] = [:]
85
91
  var nextEvaluation = 0
@@ -87,7 +93,7 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
87
93
  // The origin of the document whose page client last posted, as `location.origin` writes it (`*` when every origin is
88
94
  // allowed). JS's messages are delivered only while the page still has it.
89
95
  var bridgeOrigin: String?
90
- // The JS dialog on screen, and how to complete it if it has to go away. WebKit requires exactly one completion.
96
+ // The JS dialog on screen, and how to complete it if it has to go away.
91
97
  // While one is up the page is blocked, and an accessibility query into it (XCTest's) hangs: hide it.
92
98
  var dialog: (controller: UIAlertController, cancel: () -> Void)? {
93
99
  didSet { webView?.accessibilityElementsHidden = dialog != nil }
@@ -98,19 +104,34 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
98
104
  clipsToBounds = true
99
105
  // Made here, not lazily in the deinit fallback's endDocument(.closing), where its closure can't form a weak self.
100
106
  _ = asks
107
+ NotificationCenter.default.addObserver(
108
+ self, selector: #selector(recoverIfVisible), name: UIApplication.didBecomeActiveNotification, object: nil)
109
+ }
110
+
111
+ override func didMoveToWindow() {
112
+ super.didMoveToWindow()
113
+ recoverIfVisible()
114
+ }
115
+
116
+ /// Crash recovery reloads only in a window of an app not in the background, as on Android: there the reload
117
+ /// could die the same way, unseen.
118
+ @objc private func recoverIfVisible() {
119
+ guard recoveryPending, window != nil, UIApplication.shared.applicationState != .background else { return }
120
+ recoveryPending = false
121
+ loadAgain()
101
122
  }
102
123
 
103
124
  private var documentOpen = false
104
125
 
105
126
  private func endDocument(_ reason: DocumentEnd) {
106
- // The first commit after mount or a crash opens a Document and ends none: the asks and hooks don't hear it.
107
127
  let opening = reason == .committed && !documentOpen
108
128
  documentOpen = reason == .committed
109
129
  if !opening { asks.documentEnded(reason) }
110
130
  failEvaluations()
111
131
  bridgeOrigin = nil
112
132
  // JS queues bridge messages until the next page is ready; at unmount it rejects what is in flight itself.
113
- if reason != .closing, bridgeScript != nil { onBridge(["navigated": true]) }
133
+ if reason == .committed, bridgeScript != nil { onBridge(["navigated": true]) }
134
+ if reason == .crashed, bridgeScript != nil { onBridge(["crashed": true]) }
114
135
  askedAndAllowed.removeAll()
115
136
  dismissDialog()
116
137
  // The spinner belongs to a load, and a crash ends the load without a delegate callback.
@@ -131,11 +152,33 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
131
152
  loadedSource = next.toDictionary() as NSDictionary
132
153
  // New content from the app: the crash-loop guard starts over (recovery reloads don't come through here).
133
154
  crashTimes = []
155
+ recoveryPending = false
156
+ prepare(next)
157
+ }
158
+
159
+ /// The ref's `load`. It is prepared as a `source` load is, and a later call replaces one still waiting.
160
+ func load(url: String) {
161
+ guard let target = URL(string: url) else { return warn("load: \(url) is not a URL") }
162
+ guard webView != nil else { return }
163
+ crashTimes = []
164
+ recoveryPending = false
165
+ queuedUrl = target
166
+ if !preparing { prepare(nil) }
167
+ }
168
+
169
+ private func prepare(_ source: WebViewSource?) {
134
170
  preparing = true
135
171
  cookies.prepare { [weak self, weak webView] in
136
172
  guard let self, let webView, webView === self.webView else { return }
137
173
  preparing = false
138
- load(next)
174
+ // A load asked for while the source was prepared replaces it: started first, the source's request (a POST
175
+ // included) would be sent only to be cut off.
176
+ if let queuedUrl {
177
+ self.queuedUrl = nil
178
+ loadProgrammatic(URLRequest(url: queuedUrl), inSourceRoot: false)
179
+ } else if let source {
180
+ load(source)
181
+ }
139
182
  // Props that changed while preparing (a newer source) apply now.
140
183
  applyProps()
141
184
  }
@@ -154,7 +197,10 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
154
197
  }
155
198
  loadProgrammatic(request)
156
199
  } else {
157
- htmlNavigation = webView?.loadHTMLString(source.html ?? "", baseURL: source.baseUrl.flatMap(URL.init))
200
+ let baseURL = source.baseUrl.flatMap(URL.init)
201
+ // WebKit puts the html load through decidePolicyFor at its base URL, about:blank without one.
202
+ if let own = baseURL ?? URL(string: "about:blank") { ownLoads.append((own, mainFrameChecks)) }
203
+ htmlNavigation = webView?.loadHTMLString(source.html ?? "", baseURL: baseURL)
158
204
  }
159
205
  }
160
206
 
@@ -176,12 +222,12 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
176
222
  }
177
223
  }
178
224
 
179
- /// Loads a request the app started (see `programmaticUrl`). A file URL goes through loadFileURL with the source's read
180
- /// root, so the page's own assets load (load(_:) can't read local files).
181
- func loadProgrammatic(_ request: URLRequest) {
182
- programmaticUrl = request.url
225
+ /// Loads a request the app started (see `ownLoads`). A file URL goes through loadFileURL, so the page's own assets
226
+ /// load (load(_:) can't read local files), with the source's read root or, outside it, the file's directory.
227
+ func loadProgrammatic(_ request: URLRequest, inSourceRoot: Bool = true) {
228
+ if let url = request.url { ownLoads.append((url, mainFrameChecks)) }
183
229
  if let url = request.url, url.isFileURL {
184
- let access = ReadAccess.root(for: url, source?.readAccessRoot)
230
+ let access = ReadAccess.root(for: url, inSourceRoot ? source?.readAccessRoot : nil)
185
231
  if let warning = access.warning { warn(warning) }
186
232
  webView?.loadFileURL(url, allowingReadAccessTo: access.root)
187
233
  } else {
@@ -197,8 +243,11 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
197
243
  }
198
244
 
199
245
  func reload() {
200
- // WebKit's reload redoes no failed load or POST, and loads nothing while `url` is nil (no commit, a dead process).
201
- if let webView, webView.url != nil, failedUrl == nil, !onPostSource { webView.reload() } else { loadAgain() }
246
+ recoveryPending = false
247
+ // WebKit's reload redoes no failed load, POST or html source (it fetches the base URL), and loads nothing while `url`
248
+ // is nil (no commit, a dead process).
249
+ let onHtmlSource = onSource && source?.uri == nil
250
+ if let webView, webView.url != nil, failedUrl == nil, !onPostSource, !onHtmlSource { webView.reload() } else { loadAgain() }
202
251
  }
203
252
 
204
253
  /// Loads the page on screen again, as crash recovery does. In order:
@@ -271,7 +320,8 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
271
320
  unsafeBitCast(inherited, to: Invalidate.self)(self, selector)
272
321
  }
273
322
 
274
- /// Once: from invalidate, or from deinit if that never ran.
323
+ /// Once: from invalidate, or from deinit if that never ran (there weak self is nil, so in-flight evaluates can't be
324
+ /// rejected).
275
325
  private func tearDown() {
276
326
  guard let webView else { return }
277
327
  endDocument(.closing)
@@ -379,7 +429,6 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
379
429
  ) {
380
430
  if Downloads.isDownload(navigationResponse) {
381
431
  if requestHandlers.contains("onDownload") { return decisionHandler(.download) }
382
- // A file no hook takes (no onDownload).
383
432
  if let url = navigationResponse.response.url {
384
433
  openDownload(url)
385
434
  return decisionHandler(.cancel)
@@ -406,7 +455,7 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
406
455
 
407
456
  func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
408
457
  endDocument(.committed)
409
- programmaticUrl = nil
458
+ ownLoads.removeAll { $0.checks < mainFrameChecks }
410
459
  failedUrl = nil
411
460
  htmlCommit = navigation === htmlNavigation
412
461
  ? (webView.url?.absoluteString ?? "about:blank", webView.backForwardList.currentItem) : nil
@@ -441,15 +490,16 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
441
490
  let recovered = Recovery.crashAllowsReload(&crashTimes, now: ProcessInfo.processInfo.systemUptime) && !onPostSource
442
491
  endDocument(.crashed)
443
492
  if lastEmitted?["loading"] as? Bool == true { outcome = "failed" } // the load the crash cut off
444
- if recovered { loadAgain() }
445
- // WebKit doesn't say whether it crashed or was killed for memory
493
+ if recovered {
494
+ recoveryPending = true
495
+ recoverIfVisible()
496
+ }
446
497
  onProcessGone(["cause": "unknown", "recovered": recovered])
447
498
  forward { $0.webViewWebContentProcessDidTerminate?(webView) }
448
499
  }
449
500
  }
450
501
 
451
- /// What the hooks see of this view, through a HookContext per attached hook. The proxy gets the delegates of the
452
- /// contexts that are on; WebKit reads what a delegate responds to when it is assigned, so each change re-assigns it.
502
+ /// What the hooks see of this view, through a HookContext per attached hook.
453
503
  extension MinimalWebView {
454
504
  /// Tells each attached hook whose value changed, and attaches a hook without `configure` or `webViewClass` whose key turns on.
455
505
  private func optionsChanged(from old: [String: Any]) {
@@ -487,20 +537,12 @@ extension MinimalWebView {
487
537
  let on = hookContexts.filter(\.isOn)
488
538
  proxy.navigationDelegates = on.flatMap(\.navigationDelegates)
489
539
  proxy.uiDelegates = on.flatMap(\.uiDelegates)
540
+ // WebKit reads responds(to:) only when the delegate is set: unset first so it reads it again.
490
541
  webView?.navigationDelegate = nil
491
542
  webView?.navigationDelegate = proxy
492
543
  webView?.uiDelegate = nil
493
544
  webView?.uiDelegate = proxy
494
- warnDecisions()
495
- }
496
-
497
- private func warnDecisions() {
498
- for name in proxy.sharedDecisions where warnedDecisions.insert(name).inserted {
499
- warn("\(name): more than one hook delegate implements it; only the first one gets it")
500
- }
501
- for (name, lost) in proxy.takenDecisions where warnedDecisions.insert("\(name) taken").inserted {
502
- warn("\(name): a hook delegate takes it, so \(lost)")
503
- }
545
+ proxy.newWarnings().forEach(warn)
504
546
  }
505
547
 
506
548
  func emit(_ key: String, _ name: String, _ payload: [String: Any]) {
@@ -29,6 +29,7 @@ public class MinimalWebViewModule: Module {
29
29
 
30
30
  AsyncFunction("goBack") { (view: MinimalWebView) in view.webView?.goBack() }
31
31
  AsyncFunction("goForward") { (view: MinimalWebView) in view.webView?.goForward() }
32
+ AsyncFunction("load") { (view: MinimalWebView, url: String) in view.load(url: url) }
32
33
  AsyncFunction("reload") { (view: MinimalWebView) in view.retry() }
33
34
  AsyncFunction("stopLoading") { (view: MinimalWebView) in view.webView?.stopLoading() }
34
35
  AsyncFunction("get") { (view: MinimalWebView, path: String, promise: Promise) in
@@ -14,9 +14,11 @@ enum NavigationRules {
14
14
  }
15
15
  }
16
16
 
17
- /// `action` is allow, block, external or ask; `rule` is the matching rule's index, nil when a default decided.
17
+ enum Action: String { case allow, block, external, ask }
18
+
19
+ /// `rule` is the matching rule's index, nil when a default decided.
18
20
  struct Decision: Equatable {
19
- let action: String
21
+ let action: Action
20
22
  let rule: Int?
21
23
  }
22
24
 
@@ -33,36 +35,34 @@ enum NavigationRules {
33
35
  /// Never open as a new window, whatever the rules say: the core loads an allowed new window in the main frame itself,
34
36
  /// past the engine's limits on what a page may navigate the top frame to.
35
37
  private static let noNewWindowSchemes = internalSchemes.union(["blob", "file"])
36
- private static let actions: Set<String> = ["allow", "block", "external", "ask"]
37
- private static let answers: Set<String> = ["allow", "block", "external"]
38
38
 
39
39
  /// The rules' decision, gated for `ask`: blocked when nothing can answer it (`canAsk` false), allowed when its URL is
40
40
  /// in `asked` (URLs an `ask` already allowed). An unknown rule action blocks.
41
41
  static func decide(_ rules: [[String: Any]]?, _ request: Request, asked: Set<String>, canAsk: Bool) -> Decision {
42
42
  let decision = match(rules, request)
43
- guard decision.action == "ask" else { return decision }
44
- if !canAsk { return Decision(action: "block", rule: decision.rule) }
45
- return asked.contains(request.url) ? Decision(action: "allow", rule: decision.rule) : decision
43
+ guard decision.action == .ask else { return decision }
44
+ if !canAsk { return Decision(action: .block, rule: decision.rule) }
45
+ return asked.contains(request.url) ? Decision(action: .allow, rule: decision.rule) : decision
46
46
  }
47
47
 
48
48
  /// An `ask` answer: allow, block or external; anything else (nil on a timeout) blocks.
49
- static func answer(_ value: Any?) -> String {
50
- (value as? String).flatMap { answers.contains($0) ? $0 : nil } ?? "block"
49
+ static func answer(_ value: Any?) -> Action {
50
+ guard let action = (value as? String).flatMap(Action.init), action != .ask else { return .block }
51
+ return action
51
52
  }
52
53
 
53
54
  private static func match(_ rules: [[String: Any]]?, _ request: Request) -> Decision {
54
55
  let scheme = request.url.firstIndex(of: ":").map { request.url[..<$0].lowercased() } ?? ""
55
- if request.newWindow, noNewWindowSchemes.contains(scheme) { return Decision(action: "block", rule: nil) }
56
- if internalSchemes.contains(scheme) { return Decision(action: "allow", rule: nil) }
56
+ if request.newWindow, noNewWindowSchemes.contains(scheme) { return Decision(action: .block, rule: nil) }
57
+ if internalSchemes.contains(scheme) { return Decision(action: .allow, rule: nil) }
57
58
  // JS sends defaultNavigationRules when the prop is unset; no rules, nil or empty, match nothing.
58
59
  guard let rules, !rules.isEmpty,
59
60
  let parts = scheme == "blob" ? blobOrigin(request.url) : urlParts(scheme, request.url)
60
- else { return Decision(action: "block", rule: nil) }
61
+ else { return Decision(action: .block, rule: nil) }
61
62
  guard let index = rules.firstIndex(where: { matches($0, parts, request) }) else {
62
- return Decision(action: "block", rule: nil)
63
+ return Decision(action: .block, rule: nil)
63
64
  }
64
- let action = rules[index]["action"] as? String
65
- return Decision(action: action.flatMap { actions.contains($0) ? $0 : nil } ?? "block", rule: index)
65
+ return Decision(action: (rules[index]["action"] as? String).flatMap(Action.init) ?? .block, rule: index)
66
66
  }
67
67
 
68
68
  private static func urlParts(_ scheme: String, _ url: String) -> Parts {
@@ -1,4 +1,5 @@
1
1
  import Foundation
2
+ import WebKit
2
3
 
3
4
  /// Origin rules in Android's format (the bridge's `allowedOrigins`):
4
5
  /// `*`, an exact http(s) origin such as `https://example.com:8443`, or `https://*.example.com` for subdomains.
@@ -15,6 +16,11 @@ enum OriginRules {
15
16
  return "\(scheme)://\(host)" + (port == 0 || port == defaultPort ? "" : ":\(port)")
16
17
  }
17
18
 
19
+ /// The origin as `location.origin` writes it, so the bridge can compare the two exactly.
20
+ static func origin(of security: WKSecurityOrigin) -> String {
21
+ origin(security.protocol, security.host, security.port)
22
+ }
23
+
18
24
  static func allows(_ rules: [String], _ origin: String) -> Bool {
19
25
  let value = parse(origin)
20
26
  return rules.contains { rule in
@@ -8,15 +8,7 @@ import WebKit
8
8
  /// is created; the other roots apply live, to `webView.configuration.preferences`,
9
9
  /// `webView.configuration.defaultWebpagePreferences`, the WKWebView and its scroll view.
10
10
  ///
11
- /// A value must fit the property's type:
12
- /// - BOOL, floats and NSString as themselves
13
- /// - integers, enums and option sets by raw value
14
- /// - NSURL from a string
15
- /// - UIColor from `#rrggbb` or `#rrggbbaa`
16
- /// - UIEdgeInsets, CGPoint, CGSize and CGRect from an object
17
- /// - `websiteDataStore` from `"default"` or `"nonPersistent"`
18
- ///
19
- /// Anything else is rejected before KVC runs: a wrong value in an object-typed property can take the process down
11
+ /// A value must fit the property's type (coerce); anything else is rejected before KVC runs: a wrong value in an object-typed property can take the process down
20
12
  /// (WebKit asserts), and an unknown key raises an Objective-C exception Swift can't catch. Underscore (private)
21
13
  /// properties are refused, and the only private keys accepted are the two react-native-webview sets by KVC
22
14
  /// (`privateBools`).
@@ -194,7 +186,6 @@ final class PlatformSettings {
194
186
  let isBool = CFGetTypeID(value as CFTypeRef) == CFBooleanGetTypeID()
195
187
  let number = isBool ? nil : value as? NSNumber
196
188
  let string = value as? String
197
- let object = value as? [String: Any]
198
189
  let isNull = value is NSNull
199
190
  switch type {
200
191
  case "B", "c":
@@ -215,18 +206,8 @@ final class PlatformSettings {
215
206
  case "nonPersistent": return WKWebsiteDataStore.nonPersistent()
216
207
  default: return nil
217
208
  }
218
- case "{UIEdgeInsets=dddd}":
219
- guard let o = object, let t = o["top"] as? Double, let l = o["left"] as? Double, let b = o["bottom"] as? Double, let r = o["right"] as? Double else { return nil }
220
- return NSValue(uiEdgeInsets: UIEdgeInsets(top: t, left: l, bottom: b, right: r))
221
- case "{CGPoint=dd}":
222
- guard let o = object, let x = o["x"] as? Double, let y = o["y"] as? Double else { return nil }
223
- return NSValue(cgPoint: CGPoint(x: x, y: y))
224
- case "{CGSize=dd}":
225
- guard let o = object, let w = o["width"] as? Double, let h = o["height"] as? Double else { return nil }
226
- return NSValue(cgSize: CGSize(width: w, height: h))
227
- case "{CGRect={CGPoint=dd}{CGSize=dd}}":
228
- guard let o = object, let x = o["x"] as? Double, let y = o["y"] as? Double, let w = o["width"] as? Double, let h = o["height"] as? Double else { return nil }
229
- return NSValue(cgRect: CGRect(x: x, y: y, width: w, height: h))
209
+ case _ where type.hasPrefix("{"):
210
+ return __MRWStructValue(type, value)
230
211
  default:
231
212
  return nil
232
213
  }
@@ -3,12 +3,13 @@ import Foundation
3
3
  /// Crash recovery's choices that need no WebView, as on Android (`showsSource` and `crashAllowsReload` in
4
4
  /// MinimalWebView.kt). Cases: src/__tests__/vectors/recovery.json.
5
5
  enum Recovery {
6
- /// Whether the committed `url` is the page of the `source` with this `uri`: equal up to trailing slashes (WebKit
7
- /// commits `https://example.com` as `https://example.com/`). Not `Loads.sameURL`'s rule: that one picks out our own
8
- /// loads, which skip the navigation rules.
6
+ /// Whether the committed `url` is the page of the `source` with this `uri`: the same `Loads.canonical` form up to
7
+ /// trailing slashes.
9
8
  static func showsSource(_ uri: String, _ url: String) -> Bool {
10
- func trimmed(_ url: String) -> String { url.replacingOccurrences(of: "/+$", with: "", options: .regularExpression) }
11
- return trimmed(uri) == trimmed(url)
9
+ func page(_ url: String) -> String {
10
+ (URL(string: url).map(Loads.canonical) ?? url).replacingOccurrences(of: "/+$", with: "", options: .regularExpression)
11
+ }
12
+ return page(uri) == page(url)
12
13
  }
13
14
 
14
15
  /// Records a web content process death at `now` in `times`, and says whether to reload after it: not after more than
@@ -9,10 +9,9 @@ final class SharedCookies: NSObject, WKHTTPCookieStoreObserver {
9
9
  /// The WebView's cookies at the last copy: one gone from it since is deleted from native too.
10
10
  private var copied: [HTTPCookie] = []
11
11
 
12
- /// Once: the view's one WKWebView, which a crash keeps.
12
+ /// Once, before the first `set`: the view's one WKWebView, which a crash keeps.
13
13
  func didCreate(_ webView: WKWebView) {
14
14
  store = webView.configuration.websiteDataStore.httpCookieStore
15
- if enabled { store?.add(self) }
16
15
  }
17
16
 
18
17
  func set(_ enabled: Bool) {