-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlutterWebView.m
More file actions
308 lines (272 loc) · 11.7 KB
/
FlutterWebView.m
File metadata and controls
308 lines (272 loc) · 11.7 KB
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
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "FlutterWebView.h"
#import "FLTWKNavigationDelegate.h"
#import "JavaScriptChannelHandler.h"
@implementation FLTWebViewFactory {
NSObject<FlutterPluginRegistrar>* _registrar;
NSObject<FlutterBinaryMessenger>* _messenger;
}
- (instancetype)initWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
self = [super init];
if (self) {
_registrar = registrar;
_messenger = registrar.messenger;
}
return self;
}
- (NSObject<FlutterMessageCodec>*)createArgsCodec {
return [FlutterStandardMessageCodec sharedInstance];
}
- (NSObject<FlutterPlatformView>*)createWithFrame:(CGRect)frame
viewIdentifier:(int64_t)viewId
arguments:(id _Nullable)args {
FLTWebViewController* webviewController = [[FLTWebViewController alloc] initWithFrame:frame
viewIdentifier:viewId
arguments:args
registar:_registrar];
return webviewController;
}
@end
@implementation FLTWebViewController {
WKWebView* _webView;
int64_t _viewId;
FlutterMethodChannel* _channel;
NSString* _currentUrl;
// The set of registered JavaScript channel names.
NSMutableSet* _javaScriptChannelNames;
FLTWKNavigationDelegate* _navigationDelegate;
NSObject<FlutterPluginRegistrar>* _registrar;
}
- (instancetype)initWithFrame:(CGRect)frame
viewIdentifier:(int64_t)viewId
arguments:(id _Nullable)args
registar:(NSObject<FlutterPluginRegistrar>*)registrar {
if ([super init]) {
_viewId = viewId;
_registrar = registrar;
NSString* channelName = [NSString stringWithFormat:@"plugins.flutter.io/webview_%lld", viewId];
_channel = [FlutterMethodChannel methodChannelWithName:channelName binaryMessenger:registrar.messenger];
_javaScriptChannelNames = [[NSMutableSet alloc] init];
WKUserContentController* userContentController = [[WKUserContentController alloc] init];
if ([args[@"javascriptChannelNames"] isKindOfClass:[NSArray class]]) {
NSArray* javaScriptChannelNames = args[@"javascriptChannelNames"];
[_javaScriptChannelNames addObjectsFromArray:javaScriptChannelNames];
[self registerJavaScriptChannels:_javaScriptChannelNames controller:userContentController];
}
WKWebViewConfiguration* configuration = [[WKWebViewConfiguration alloc] init];
configuration.userContentController = userContentController;
_webView = [[WKWebView alloc] initWithFrame:frame configuration:configuration];
_navigationDelegate = [[FLTWKNavigationDelegate alloc] initWithChannel:_channel];
_webView.navigationDelegate = _navigationDelegate;
__weak __typeof__(self) weakSelf = self;
[_channel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
[weakSelf onMethodCall:call result:result];
}];
NSDictionary<NSString*, id>* settings = args[@"settings"];
[self applySettings:settings];
NSString* initialUrl = args[@"initialUrl"];
if ([initialUrl isKindOfClass:[NSString class]]) {
[self loadUrl:initialUrl];
}
}
return self;
}
- (UIView*)view {
return _webView;
}
- (void)onMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
if ([[call method] isEqualToString:@"updateSettings"]) {
[self onUpdateSettings:call result:result];
} else if ([[call method] isEqualToString:@"loadUrl"]) {
[self onLoadUrl:call result:result];
} else if ([[call method] isEqualToString:@"canGoBack"]) {
[self onCanGoBack:call result:result];
} else if ([[call method] isEqualToString:@"canGoForward"]) {
[self onCanGoForward:call result:result];
} else if ([[call method] isEqualToString:@"goBack"]) {
[self onGoBack:call result:result];
} else if ([[call method] isEqualToString:@"goForward"]) {
[self onGoForward:call result:result];
} else if ([[call method] isEqualToString:@"reload"]) {
[self onReload:call result:result];
} else if ([[call method] isEqualToString:@"currentUrl"]) {
[self onCurrentUrl:call result:result];
} else if ([[call method] isEqualToString:@"evaluateJavascript"]) {
[self onEvaluateJavaScript:call result:result];
} else if ([[call method] isEqualToString:@"addJavascriptChannels"]) {
[self onAddJavaScriptChannels:call result:result];
} else if ([[call method] isEqualToString:@"removeJavascriptChannels"]) {
[self onRemoveJavaScriptChannels:call result:result];
} else if ([[call method] isEqualToString:@"clearCache"]) {
[self clearCache:result];
} else {
result(FlutterMethodNotImplemented);
}
}
- (void)onUpdateSettings:(FlutterMethodCall*)call result:(FlutterResult)result {
[self applySettings:[call arguments]];
result(nil);
}
- (void)onLoadUrl:(FlutterMethodCall*)call result:(FlutterResult)result {
NSString* url = [call arguments];
if (![self loadUrl:url]) {
result([FlutterError errorWithCode:@"loadUrl_failed"
message:@"Failed parsing the URL"
details:[NSString stringWithFormat:@"URL was: '%@'", url]]);
} else {
result(nil);
}
}
- (void)onCanGoBack:(FlutterMethodCall*)call result:(FlutterResult)result {
BOOL canGoBack = [_webView canGoBack];
result([NSNumber numberWithBool:canGoBack]);
}
- (void)onCanGoForward:(FlutterMethodCall*)call result:(FlutterResult)result {
BOOL canGoForward = [_webView canGoForward];
result([NSNumber numberWithBool:canGoForward]);
}
- (void)onGoBack:(FlutterMethodCall*)call result:(FlutterResult)result {
[_webView goBack];
result(nil);
}
- (void)onGoForward:(FlutterMethodCall*)call result:(FlutterResult)result {
[_webView goForward];
result(nil);
}
- (void)onReload:(FlutterMethodCall*)call result:(FlutterResult)result {
[_webView reload];
result(nil);
}
- (void)onCurrentUrl:(FlutterMethodCall*)call result:(FlutterResult)result {
_currentUrl = [[_webView URL] absoluteString];
result(_currentUrl);
}
- (void)onEvaluateJavaScript:(FlutterMethodCall*)call result:(FlutterResult)result {
NSString* jsString = [call arguments];
if (!jsString) {
result([FlutterError errorWithCode:@"evaluateJavaScript_failed"
message:@"JavaScript String cannot be null"
details:nil]);
return;
}
[_webView evaluateJavaScript:jsString
completionHandler:^(_Nullable id evaluateResult, NSError* _Nullable error) {
if (error) {
result([FlutterError
errorWithCode:@"evaluateJavaScript_failed"
message:@"Failed evaluating JavaScript"
details:[NSString stringWithFormat:@"JavaScript string was: '%@'\n%@",
jsString, error]]);
} else {
result([NSString stringWithFormat:@"%@", evaluateResult]);
}
}];
}
- (void)onAddJavaScriptChannels:(FlutterMethodCall*)call result:(FlutterResult)result {
NSArray* channelNames = [call arguments];
NSSet* channelNamesSet = [[NSSet alloc] initWithArray:channelNames];
[_javaScriptChannelNames addObjectsFromArray:channelNames];
[self registerJavaScriptChannels:channelNamesSet
controller:_webView.configuration.userContentController];
result(nil);
}
- (void)onRemoveJavaScriptChannels:(FlutterMethodCall*)call result:(FlutterResult)result {
// WkWebView does not support removing a single user script, so instead we remove all
// user scripts, all message handlers. And re-register channels that shouldn't be removed.
[_webView.configuration.userContentController removeAllUserScripts];
for (NSString* channelName in _javaScriptChannelNames) {
[_webView.configuration.userContentController removeScriptMessageHandlerForName:channelName];
}
NSArray* channelNamesToRemove = [call arguments];
for (NSString* channelName in channelNamesToRemove) {
[_javaScriptChannelNames removeObject:channelName];
}
[self registerJavaScriptChannels:_javaScriptChannelNames
controller:_webView.configuration.userContentController];
result(nil);
}
- (void)clearCache:(FlutterResult)result {
if (@available(iOS 9.0, *)) {
NSSet* cacheDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
WKWebsiteDataStore* dataStore = [WKWebsiteDataStore defaultDataStore];
NSDate* dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
[dataStore removeDataOfTypes:cacheDataTypes
modifiedSince:dateFrom
completionHandler:^{
result(nil);
}];
} else {
// support for iOS8 tracked in https://github.com/flutter/flutter/issues/27624.
NSLog(@"Clearing cache is not supported for Flutter WebViews prior to iOS 9.");
}
}
- (void)applySettings:(NSDictionary<NSString*, id>*)settings {
for (NSString* key in settings) {
if ([key isEqualToString:@"jsMode"]) {
NSNumber* mode = settings[key];
[self updateJsMode:mode];
} else if ([key isEqualToString:@"hasNavigationDelegate"]) {
NSNumber* hasDartNavigationDelegate = settings[key];
_navigationDelegate.hasDartNavigationDelegate = [hasDartNavigationDelegate boolValue];
} else {
NSLog(@"webview_flutter: unknown setting key: %@", key);
}
}
}
- (void)updateJsMode:(NSNumber*)mode {
WKPreferences* preferences = [[_webView configuration] preferences];
switch ([mode integerValue]) {
case 0: // disabled
[preferences setJavaScriptEnabled:NO];
break;
case 1: // unrestricted
[preferences setJavaScriptEnabled:YES];
break;
default:
NSLog(@"webview_flutter: unknown JavaScript mode: %@", mode);
}
}
- (bool)loadUrl:(NSString*)url {
NSLog(@"\nwebview_flutter: loadingurl: %@", url);
// NSArray* urlArray = [url componentsSeparatedByString:@"/#"];
//NSLog(@"\n urlArray: %@", urlArray);
//NSString* urlKey = [urlArray objectAtIndex:0];
//NSLog(@"\n urlKey: %@", urlKey);
//NSString* urlBookmark = [urlArray objectAtIndex:1];
//NSLog(@"\n urlBookmark: %@", urlBookmark);
NSString* key = [_registrar lookupKeyForAsset:url];
NSLog(@"\n key: %@", key);
// NSString* keyWithHash = [key stringByAppendingString:@"/#"];
// NSLog(@"\n keyWithHash: %@", keyWithHash);
// NSString* fullKey = [keyWithHash stringByAppendingString:urlBookmark];
// NSLog(@"\n FullKey: %@", fullKey);
NSURL* nsUrl = [[NSBundle mainBundle] URLForResource:key withExtension:nil];
if (!nsUrl) {
return false;
}
if (@available(iOS 9.0, *)) {
[_webView loadFileURL:nsUrl allowingReadAccessToURL:[NSURL URLWithString:@"file:///"]];
} else {
return false;
}
return true;
}
- (void)registerJavaScriptChannels:(NSSet*)channelNames
controller:(WKUserContentController*)userContentController {
for (NSString* channelName in channelNames) {
FLTJavaScriptChannel* channel =
[[FLTJavaScriptChannel alloc] initWithMethodChannel:_channel
javaScriptChannelName:channelName];
[userContentController addScriptMessageHandler:channel name:channelName];
NSString* wrapperSource = [NSString
stringWithFormat:@"window.%@ = webkit.messageHandlers.%@;", channelName, channelName];
WKUserScript* wrapperScript =
[[WKUserScript alloc] initWithSource:wrapperSource
injectionTime:WKUserScriptInjectionTimeAtDocumentStart
forMainFrameOnly:NO];
[userContentController addUserScript:wrapperScript];
}
}
@end