-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathModalWebViewController.mm
312 lines (255 loc) · 10.3 KB
/
ModalWebViewController.mm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
#import "ModalWebViewController.h"
#import "OpacityIOSHelper.h"
#import "opacity.h"
@interface ModalWebViewController ()
@property(nonatomic, strong) WKWebView *webView;
@property(nonatomic, strong) NSMutableURLRequest *request;
@property(nonatomic, strong) WKWebsiteDataStore *websiteDataStore;
@property(nonatomic, strong) NSMutableDictionary *cookies;
@property(nonatomic, strong) NSMutableArray<NSString *> *visitedUrls;
@end
@implementation ModalWebViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.cookies = [NSMutableDictionary dictionary];
self.visitedUrls = [NSMutableArray array];
// Configure the view's background color
self.view.backgroundColor = [UIColor blackColor];
// Create a WKWebViewConfiguration
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
// Create a WKProcessPool
WKProcessPool *processPool = [[WKProcessPool alloc] init];
configuration.processPool = processPool;
// Create a WKWebsiteDataStore
self.websiteDataStore = [WKWebsiteDataStore nonPersistentDataStore];
configuration.websiteDataStore = self.websiteDataStore;
// Initialize and configure the WKWebView
self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds
configuration:configuration];
// Set the configuration to the WKWebView
self.webView.allowsLinkPreview = true;
self.webView.autoresizingMask =
UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.webView.navigationDelegate = self;
// Add the WKWebView to the view hierarchy
[self.view addSubview:self.webView];
// Load the provided URL
if (self.request) {
[self.webView loadRequest:self.request];
}
// Add a Close button
UIBarButtonItem *closeButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemStop
target:self
action:@selector(close)];
self.navigationItem.rightBarButtonItem = closeButton;
}
+ (BOOL)accessInstanceVariablesDirectly {
return NO;
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
// Check if the controller or its navigation controller is being dismissed
if (self.isBeingDismissed || self.navigationController.isBeingDismissed) {
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
NSString *event_id = [NSString
stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]];
[dict setObject:@"close" forKey:@"event"];
[dict setObject:event_id forKey:@"id"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:0
error:&error];
NSString *payload = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
opacity_core::emit_webview_event([payload UTF8String]);
}
}
- (void)getBrowserCookiesForCurrentUrlWithCompletion:(void (^)(NSDictionary *))completion {
NSMutableDictionary *cookieDict = [NSMutableDictionary dictionary];
NSURL *url = self.webView.URL;
if (url == nil) {
completion(cookieDict);
return;
}
WKHTTPCookieStore *cookieStore =
self.webView.configuration.websiteDataStore.httpCookieStore;
[cookieStore getAllCookies:^(NSArray<NSHTTPCookie *> *cookies) {
for (NSHTTPCookie *cookie in cookies) {
if ([url.host hasSuffix:cookie.domain]) {
[cookieDict setObject:cookie.value forKey:cookie.name];
}
}
completion(cookieDict);
}];
}
- (NSDictionary *)getBrowserCookiesForCurrentUrl {
__block NSDictionary *result = nil;
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[self getBrowserCookiesForCurrentUrlWithCompletion:^(NSDictionary *cookies) {
result = cookies;
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
return result;
}
- (void)updateCapturedCookiesWithCompletion:(void (^)(void))completion {
WKHTTPCookieStore *cookieStore =
self.webView.configuration.websiteDataStore.httpCookieStore;
[cookieStore getAllCookies:^(NSArray<NSHTTPCookie *> *cookies) {
for (NSHTTPCookie *cookie in cookies) {
[self.cookies setObject:cookie.value forKey:cookie.name];
}
completion();
}];
}
- (void)openRequest:(NSMutableURLRequest *)request {
_request = request;
[self.webView loadRequest:_request];
}
- (instancetype)initWithRequest:(NSMutableURLRequest *)request {
self = [super init];
if (self) {
_request = request;
}
return self;
}
- (void)close {
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)addToVisitedUrls:(NSString *)urlToAdd {
if (self.visitedUrls.count == 0 ||
![self.visitedUrls.lastObject isEqualToString:urlToAdd]) {
[self.visitedUrls addObject:urlToAdd];
}
}
- (void)resetVisitedUrls {
[self.visitedUrls removeAllObjects];
}
#pragma mark - WKNavigationDelegate Methods
- (void)webView:(WKWebView *)webView
didStartProvisionalNavigation:(WKNavigation *)navigation {
if (webView.URL) {
[self addToVisitedUrls:webView.URL.absoluteString];
}
}
- (void)getHtmlBodyWithCompletion:(void (^)(NSString *))completion {
[self.webView
evaluateJavaScript:@"document.documentElement.outerHTML.toString()"
completionHandler:^(NSString *html, NSError *error) {
completion(html);
}];
}
- (void)webView:(WKWebView *)webView
didFinishNavigation:(WKNavigation *)navigation {
NSURL *url = webView.URL;
if (url) {
[self addToVisitedUrls:webView.URL.absoluteString];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
NSString *event_id = [NSString
stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]];
[dict setObject:url.absoluteString forKey:@"url"];
[dict setObject:@"navigation" forKey:@"event"];
[dict setObject:event_id forKey:@"id"];
[self getHtmlBodyWithCompletion:^(NSString *body) {
if (body != nil) {
[dict setObject:body forKey:@"html_body"];
}
[self updateCapturedCookiesWithCompletion:^{
[dict setObject:self.cookies forKey:@"cookies"];
[dict setObject:self.visitedUrls forKey:@"visited_urls"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:0
error:&error];
NSString *payload = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
opacity_core::emit_webview_event([payload UTF8String]);
[self resetVisitedUrls];
}];
}];
}
}
- (void)webView:(WKWebView *)webView
didReceiveServerRedirectForProvisionalNavigation:
(WKNavigation *)navigation {
NSURL *url = webView.URL;
if (url) {
[self addToVisitedUrls:url.absoluteString];
}
}
- (void)webView:(WKWebView *)webView
didFailProvisionalNavigation:(WKNavigation *)navigation
withError:(NSError *)error {
NSString *url = error.userInfo[NSURLErrorFailingURLStringErrorKey];
if (url) {
[self addToVisitedUrls:url];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:url forKey:@"url"];
[dict setObject:@"navigation" forKey:@"event"];
[dict
setObject:[NSString stringWithFormat:@"%f", [[NSDate date]
timeIntervalSince1970]]
forKey:@"id"];
[dict setObject:self.cookies forKey:@"cookies"];
[dict setObject:self.visitedUrls forKey:@"visited_urls"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:0
error:&error];
NSString *payload = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
opacity_core::emit_webview_event([payload UTF8String]);
[self resetVisitedUrls];
}
NSLog(@"Failed to load: %@, Error: %@",
error.userInfo[NSURLErrorFailingURLStringErrorKey],
error.localizedDescription);
}
- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
willPerformHTTPRedirection:(NSHTTPURLResponse *)response
newRequest:(NSURLRequest *)request
completionHandler:
(void (^)(NSURLRequest *_Nullable))completionHandler {
NSDictionary *headers = [response allHeaderFields];
NSArray *cookies =
[NSHTTPCookie cookiesWithResponseHeaderFields:headers
forURL:[response URL]];
for (NSHTTPCookie *cookie in cookies) {
[self.cookies setObject:cookie.value forKey:cookie.name];
}
if (request.URL) {
[self addToVisitedUrls:request.URL.absoluteString];
}
if (response.URL) {
[self addToVisitedUrls:response.URL.absoluteString];
}
completionHandler(request);
}
- (void)webView:(WKWebView *)webView
decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
decisionHandler:
(void (^)(WKNavigationActionPolicy))decisionHandler {
/// We potentially want to intercept navigation requests with deeplinks
/// A deeplink might take you out of the current app and into the service app
/// The problem is by canceling the redirection none of the other handlers are
/// triggered. Which means the cookies at the moment of the redirection are
/// not sent to Rust. We could potentially move the code of
/// didFailProvisionalNavigation here and it might work... I don't know, this
/// needs testing. For now allowing all redirections causes the deeplinks we
/// need to fail which then triggeres didFailProvisionalNavigation and
/// extracts and sends the requests to Rust and then to Lua
// NSURLRequest *request = navigationAction.request;
// NSURL *url = request.URL;
// if (![url.scheme isEqualToString:@"http"] &&
// ![url.scheme isEqualToString:@"https"]) {
// decisionHandler(WKNavigationActionPolicyCancel);
// return;
// }
if (webView.URL) {
[self addToVisitedUrls:webView.URL.absoluteString];
}
decisionHandler(WKNavigationActionPolicyAllow);
}
@end