FlutterWebviewPlugin.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. #import "FlutterWebviewPlugin.h"
  2. #import "WebviewJavaScriptChannelHandler.h"
  3. static NSString *const CHANNEL_NAME = @"flutter_webview_plugin";
  4. // UIWebViewDelegate
  5. @interface FlutterWebviewPlugin() <WKNavigationDelegate, UIScrollViewDelegate, WKUIDelegate> {
  6. BOOL _enableAppScheme;
  7. BOOL _enableZoom;
  8. NSString* _invalidUrlRegex;
  9. NSMutableSet* _javaScriptChannelNames;
  10. NSNumber* _ignoreSSLErrors;
  11. }
  12. @end
  13. @implementation FlutterWebviewPlugin
  14. + (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  15. channel = [FlutterMethodChannel
  16. methodChannelWithName:CHANNEL_NAME
  17. binaryMessenger:[registrar messenger]];
  18. UIViewController *viewController = [UIApplication sharedApplication].delegate.window.rootViewController;
  19. FlutterWebviewPlugin* instance = [[FlutterWebviewPlugin alloc] initWithViewController:viewController];
  20. [registrar addMethodCallDelegate:instance channel:channel];
  21. }
  22. - (instancetype)initWithViewController:(UIViewController *)viewController {
  23. self = [super init];
  24. if (self) {
  25. self.viewController = viewController;
  26. }
  27. return self;
  28. }
  29. - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  30. if ([@"launch" isEqualToString:call.method]) {
  31. if (!self.webview)
  32. [self initWebview:call withResult:result];
  33. else
  34. [self navigate:call];
  35. result(nil);
  36. } else if ([@"close" isEqualToString:call.method]) {
  37. [self closeWebView];
  38. result(nil);
  39. } else if ([@"eval" isEqualToString:call.method]) {
  40. [self evalJavascript:call completionHandler:^(NSString * response) {
  41. result(response);
  42. }];
  43. } else if ([@"resize" isEqualToString:call.method]) {
  44. [self resize:call];
  45. result(nil);
  46. } else if ([@"reloadUrl" isEqualToString:call.method]) {
  47. [self reloadUrl:call];
  48. result(nil);
  49. } else if ([@"show" isEqualToString:call.method]) {
  50. [self show];
  51. result(nil);
  52. } else if ([@"hide" isEqualToString:call.method]) {
  53. [self hide];
  54. result(nil);
  55. } else if ([@"stopLoading" isEqualToString:call.method]) {
  56. [self stopLoading];
  57. result(nil);
  58. } else if ([@"cleanCookies" isEqualToString:call.method]) {
  59. [self cleanCookies:result];
  60. } else if ([@"back" isEqualToString:call.method]) {
  61. [self back];
  62. result(nil);
  63. } else if ([@"forward" isEqualToString:call.method]) {
  64. [self forward];
  65. result(nil);
  66. } else if ([@"reload" isEqualToString:call.method]) {
  67. [self reload];
  68. result(nil);
  69. } else if ([@"canGoBack" isEqualToString:call.method]) {
  70. [self onCanGoBack:call result:result];
  71. } else if ([@"canGoForward" isEqualToString:call.method]) {
  72. [self onCanGoForward:call result:result];
  73. } else if ([@"cleanCache" isEqualToString:call.method]) {
  74. [self cleanCache:result];
  75. } else {
  76. result(FlutterMethodNotImplemented);
  77. }
  78. }
  79. - (void)initWebview:(FlutterMethodCall*)call withResult:(FlutterResult)result {
  80. NSNumber *clearCache = call.arguments[@"clearCache"];
  81. NSNumber *clearCookies = call.arguments[@"clearCookies"];
  82. NSNumber *hidden = call.arguments[@"hidden"];
  83. NSDictionary *rect = call.arguments[@"rect"];
  84. _enableAppScheme = call.arguments[@"enableAppScheme"];
  85. NSString *userAgent = call.arguments[@"userAgent"];
  86. NSNumber *withZoom = call.arguments[@"withZoom"];
  87. NSNumber *scrollBar = call.arguments[@"scrollBar"];
  88. NSNumber *withJavascript = call.arguments[@"withJavascript"];
  89. _invalidUrlRegex = call.arguments[@"invalidUrlRegex"];
  90. _ignoreSSLErrors = call.arguments[@"ignoreSSLErrors"];
  91. _javaScriptChannelNames = [[NSMutableSet alloc] init];
  92. WKUserContentController* userContentController = [[WKUserContentController alloc] init];
  93. if ([call.arguments[@"javascriptChannelNames"] isKindOfClass:[NSArray class]]) {
  94. NSArray* javaScriptChannelNames = call.arguments[@"javascriptChannelNames"];
  95. [_javaScriptChannelNames addObjectsFromArray:javaScriptChannelNames];
  96. [self registerJavaScriptChannels:_javaScriptChannelNames controller:userContentController];
  97. }
  98. if (clearCache != (id)[NSNull null] && [clearCache boolValue]) {
  99. [[NSURLCache sharedURLCache] removeAllCachedResponses];
  100. [self cleanCache:result];
  101. }
  102. if (clearCookies != (id)[NSNull null] && [clearCookies boolValue]) {
  103. NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  104. for (NSHTTPCookie *cookie in [storage cookies])
  105. {
  106. [storage deleteCookie:cookie];
  107. }
  108. [self cleanCookies:result];
  109. }
  110. if (userAgent != (id)[NSNull null]) {
  111. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": userAgent}];
  112. }
  113. CGRect rc;
  114. if (rect != nil) {
  115. rc = [self parseRect:rect];
  116. } else {
  117. rc = self.viewController.view.bounds;
  118. }
  119. WKWebViewConfiguration* configuration = [[WKWebViewConfiguration alloc] init];
  120. configuration.userContentController = userContentController;
  121. self.webview = [[WKWebView alloc] initWithFrame:rc configuration:configuration];
  122. self.webview.UIDelegate = self;
  123. self.webview.navigationDelegate = self;
  124. self.webview.scrollView.delegate = self;
  125. self.webview.hidden = [hidden boolValue];
  126. self.webview.scrollView.showsHorizontalScrollIndicator = [scrollBar boolValue];
  127. self.webview.scrollView.showsVerticalScrollIndicator = [scrollBar boolValue];
  128. [self.webview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
  129. WKPreferences* preferences = [[self.webview configuration] preferences];
  130. if ([withJavascript boolValue]) {
  131. [preferences setJavaScriptEnabled:YES];
  132. } else {
  133. [preferences setJavaScriptEnabled:NO];
  134. }
  135. _enableZoom = [withZoom boolValue];
  136. UIViewController* presentedViewController = self.viewController.presentedViewController;
  137. UIViewController* currentViewController = presentedViewController != nil ? presentedViewController : self.viewController;
  138. [currentViewController.view addSubview:self.webview];
  139. [self navigate:call];
  140. }
  141. - (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {
  142. if ([_ignoreSSLErrors boolValue]){
  143. SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
  144. CFDataRef exceptions = SecTrustCopyExceptions(serverTrust);
  145. SecTrustSetExceptions(serverTrust, exceptions);
  146. CFRelease(exceptions);
  147. completionHandler(NSURLSessionAuthChallengeUseCredential,
  148. [NSURLCredential credentialForTrust:serverTrust]);
  149. }
  150. else {
  151. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling,nil);
  152. }
  153. }
  154. - (CGRect)parseRect:(NSDictionary *)rect {
  155. return CGRectMake([[rect valueForKey:@"left"] doubleValue],
  156. [[rect valueForKey:@"top"] doubleValue],
  157. [[rect valueForKey:@"width"] doubleValue],
  158. [[rect valueForKey:@"height"] doubleValue]);
  159. }
  160. - (void) scrollViewDidScroll:(UIScrollView *)scrollView {
  161. id xDirection = @{@"xDirection": @(scrollView.contentOffset.x) };
  162. [channel invokeMethod:@"onScrollXChanged" arguments:xDirection];
  163. id yDirection = @{@"yDirection": @(scrollView.contentOffset.y) };
  164. [channel invokeMethod:@"onScrollYChanged" arguments:yDirection];
  165. }
  166. - (void)navigate:(FlutterMethodCall*)call {
  167. if (self.webview != nil) {
  168. NSString *url = call.arguments[@"url"];
  169. NSNumber *withLocalUrl = call.arguments[@"withLocalUrl"];
  170. if ( [withLocalUrl boolValue]) {
  171. NSURL *htmlUrl = [NSURL fileURLWithPath:url isDirectory:false];
  172. NSString *localUrlScope = call.arguments[@"localUrlScope"];
  173. if (@available(iOS 9.0, *)) {
  174. if(localUrlScope == nil) {
  175. [self.webview loadFileURL:htmlUrl allowingReadAccessToURL:htmlUrl];
  176. }
  177. else {
  178. NSURL *scopeUrl = [NSURL fileURLWithPath:localUrlScope];
  179. [self.webview loadFileURL:htmlUrl allowingReadAccessToURL:scopeUrl];
  180. }
  181. } else {
  182. @throw @"not available on version earlier than ios 9.0";
  183. }
  184. } else {
  185. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
  186. NSDictionary *headers = call.arguments[@"headers"];
  187. if (headers != nil) {
  188. [request setAllHTTPHeaderFields:headers];
  189. }
  190. [self.webview loadRequest:request];
  191. }
  192. }
  193. }
  194. - (void)evalJavascript:(FlutterMethodCall*)call
  195. completionHandler:(void (^_Nullable)(NSString * response))completionHandler {
  196. if (self.webview != nil) {
  197. NSString *code = call.arguments[@"code"];
  198. [self.webview evaluateJavaScript:code
  199. completionHandler:^(id _Nullable response, NSError * _Nullable error) {
  200. completionHandler([NSString stringWithFormat:@"%@", response]);
  201. }];
  202. } else {
  203. completionHandler(nil);
  204. }
  205. }
  206. - (void)resize:(FlutterMethodCall*)call {
  207. if (self.webview != nil) {
  208. NSDictionary *rect = call.arguments[@"rect"];
  209. CGRect rc = [self parseRect:rect];
  210. self.webview.frame = rc;
  211. }
  212. }
  213. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
  214. if ([keyPath isEqualToString:@"estimatedProgress"] && object == self.webview) {
  215. [channel invokeMethod:@"onProgressChanged" arguments:@{@"progress": @(self.webview.estimatedProgress)}];
  216. } else {
  217. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  218. }
  219. }
  220. - (void)closeWebView {
  221. if (self.webview != nil) {
  222. [self.webview stopLoading];
  223. [self.webview removeFromSuperview];
  224. self.webview.navigationDelegate = nil;
  225. [self.webview removeObserver:self forKeyPath:@"estimatedProgress"];
  226. self.webview = nil;
  227. // manually trigger onDestroy
  228. [channel invokeMethod:@"onDestroy" arguments:nil];
  229. }
  230. }
  231. - (void)reloadUrl:(FlutterMethodCall*)call {
  232. if (self.webview != nil) {
  233. NSString *url = call.arguments[@"url"];
  234. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
  235. NSDictionary *headers = call.arguments[@"headers"];
  236. if (headers != nil) {
  237. [request setAllHTTPHeaderFields:headers];
  238. }
  239. [self.webview loadRequest:request];
  240. }
  241. }
  242. - (void)cleanCookies:(FlutterResult)result {
  243. if(self.webview != nil) {
  244. [[NSURLSession sharedSession] resetWithCompletionHandler:^{
  245. }];
  246. if (@available(iOS 9.0, *)) {
  247. NSSet<NSString *> *websiteDataTypes = [NSSet setWithObject:WKWebsiteDataTypeCookies];
  248. WKWebsiteDataStore *dataStore = [WKWebsiteDataStore defaultDataStore];
  249. void (^deleteAndNotify)(NSArray<WKWebsiteDataRecord *> *) =
  250. ^(NSArray<WKWebsiteDataRecord *> *cookies) {
  251. [dataStore removeDataOfTypes:websiteDataTypes
  252. forDataRecords:cookies
  253. completionHandler:^{
  254. result(nil);
  255. }];
  256. };
  257. [dataStore fetchDataRecordsOfTypes:websiteDataTypes completionHandler:deleteAndNotify];
  258. } else {
  259. // support for iOS8 tracked in https://github.com/flutter/flutter/issues/27624.
  260. NSLog(@"Clearing cookies is not supported for Flutter WebViews prior to iOS 9.");
  261. }
  262. }
  263. }
  264. - (void)cleanCache:(FlutterResult)result {
  265. if (self.webview != nil) {
  266. if (@available(iOS 9.0, *)) {
  267. NSSet* cacheDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
  268. WKWebsiteDataStore* dataStore = [WKWebsiteDataStore defaultDataStore];
  269. NSDate* dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
  270. [dataStore removeDataOfTypes:cacheDataTypes
  271. modifiedSince:dateFrom
  272. completionHandler:^{
  273. result(nil);
  274. }];
  275. } else {
  276. // support for iOS8 tracked in https://github.com/flutter/flutter/issues/27624.
  277. NSLog(@"Clearing cache is not supported for Flutter WebViews prior to iOS 9.");
  278. }
  279. }
  280. }
  281. - (void)show {
  282. if (self.webview != nil) {
  283. self.webview.hidden = false;
  284. }
  285. }
  286. - (void)hide {
  287. if (self.webview != nil) {
  288. self.webview.hidden = true;
  289. }
  290. }
  291. - (void)stopLoading {
  292. if (self.webview != nil) {
  293. [self.webview stopLoading];
  294. }
  295. }
  296. - (void)back {
  297. if (self.webview != nil) {
  298. [self.webview goBack];
  299. }
  300. }
  301. - (void)onCanGoBack:(FlutterMethodCall*)call result:(FlutterResult)result {
  302. BOOL canGoBack = [self.webview canGoBack];
  303. result([NSNumber numberWithBool:canGoBack]);
  304. }
  305. - (void)onCanGoForward:(FlutterMethodCall*)call result:(FlutterResult)result {
  306. BOOL canGoForward = [self.webview canGoForward];
  307. result([NSNumber numberWithBool:canGoForward]);
  308. }
  309. - (void)forward {
  310. if (self.webview != nil) {
  311. [self.webview goForward];
  312. }
  313. }
  314. - (void)reload {
  315. if (self.webview != nil) {
  316. [self.webview reload];
  317. }
  318. }
  319. - (bool)checkInvalidUrl:(NSURL*)url {
  320. NSString* urlString = url != nil ? [url absoluteString] : nil;
  321. if (![_invalidUrlRegex isEqual:[NSNull null]] && urlString != nil) {
  322. NSError* error = NULL;
  323. NSRegularExpression* regex =
  324. [NSRegularExpression regularExpressionWithPattern:_invalidUrlRegex
  325. options:NSRegularExpressionCaseInsensitive
  326. error:&error];
  327. NSTextCheckingResult* match = [regex firstMatchInString:urlString
  328. options:0
  329. range:NSMakeRange(0, [urlString length])];
  330. return match != nil;
  331. } else {
  332. return false;
  333. }
  334. }
  335. #pragma mark -- WkWebView Delegate
  336. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
  337. decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
  338. BOOL isInvalid = [self checkInvalidUrl: navigationAction.request.URL];
  339. id data = @{@"url": navigationAction.request.URL.absoluteString,
  340. @"type": isInvalid ? @"abortLoad" : @"shouldStart",
  341. @"navigationType": [NSNumber numberWithInteger:navigationAction.navigationType]};
  342. [channel invokeMethod:@"onState" arguments:data];
  343. if (navigationAction.navigationType == WKNavigationTypeBackForward) {
  344. [channel invokeMethod:@"onBackPressed" arguments:nil];
  345. } else if (!isInvalid) {
  346. id data = @{@"url": navigationAction.request.URL.absoluteString};
  347. [channel invokeMethod:@"onUrlChanged" arguments:data];
  348. }
  349. if (_enableAppScheme ||
  350. ([webView.URL.scheme isEqualToString:@"http"] ||
  351. [webView.URL.scheme isEqualToString:@"https"] ||
  352. [webView.URL.scheme isEqualToString:@"about"] ||
  353. [webView.URL.scheme isEqualToString:@"file"])) {
  354. if (isInvalid) {
  355. decisionHandler(WKNavigationActionPolicyCancel);
  356. } else {
  357. decisionHandler(WKNavigationActionPolicyAllow);
  358. }
  359. } else {
  360. decisionHandler(WKNavigationActionPolicyCancel);
  361. }
  362. }
  363. - (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration
  364. forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
  365. if (!navigationAction.targetFrame.isMainFrame) {
  366. [webView loadRequest:navigationAction.request];
  367. }
  368. return nil;
  369. }
  370. - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
  371. [channel invokeMethod:@"onState" arguments:@{@"type": @"startLoad", @"url": webView.URL.absoluteString}];
  372. }
  373. - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
  374. NSString* url = webView.URL == nil ? @"?" : webView.URL.absoluteString;
  375. [channel invokeMethod:@"onHttpError" arguments:@{@"code": [NSString stringWithFormat:@"%ld", error.code], @"url": url}];
  376. }
  377. - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
  378. [channel invokeMethod:@"onState" arguments:@{@"type": @"finishLoad", @"url": webView.URL.absoluteString}];
  379. }
  380. - (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
  381. [channel invokeMethod:@"onHttpError" arguments:@{@"code": [NSString stringWithFormat:@"%ld", error.code], @"error": error.localizedDescription}];
  382. }
  383. - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
  384. if ([navigationResponse.response isKindOfClass:[NSHTTPURLResponse class]]) {
  385. NSHTTPURLResponse * response = (NSHTTPURLResponse *)navigationResponse.response;
  386. if (response.statusCode >= 400) {
  387. [channel invokeMethod:@"onHttpError" arguments:@{@"code": [NSString stringWithFormat:@"%ld", response.statusCode], @"url": webView.URL.absoluteString}];
  388. }
  389. }
  390. decisionHandler(WKNavigationResponsePolicyAllow);
  391. }
  392. - (void)registerJavaScriptChannels:(NSSet*)channelNames
  393. controller:(WKUserContentController*)userContentController {
  394. for (NSString* channelName in channelNames) {
  395. FLTCommunityJavaScriptChannel* _channel =
  396. [[FLTCommunityJavaScriptChannel alloc] initWithMethodChannel: channel
  397. javaScriptChannelName:channelName];
  398. [userContentController addScriptMessageHandler:_channel name:channelName];
  399. NSString* wrapperSource = [NSString
  400. stringWithFormat:@"window.%@ = webkit.messageHandlers.%@;", channelName, channelName];
  401. WKUserScript* wrapperScript =
  402. [[WKUserScript alloc] initWithSource:wrapperSource
  403. injectionTime:WKUserScriptInjectionTimeAtDocumentStart
  404. forMainFrameOnly:NO];
  405. [userContentController addUserScript:wrapperScript];
  406. }
  407. }
  408. #pragma mark -- UIScrollViewDelegate
  409. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
  410. if (scrollView.pinchGestureRecognizer.isEnabled != _enableZoom) {
  411. scrollView.pinchGestureRecognizer.enabled = _enableZoom;
  412. }
  413. }
  414. @end