FlutterWebviewPlugin.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. #import "FlutterWebviewPlugin.h"
  2. static NSString *const CHANNEL_NAME = @"flutter_webview_plugin";
  3. // UIWebViewDelegate
  4. @interface FlutterWebviewPlugin() <WKNavigationDelegate, UIScrollViewDelegate, WKUIDelegate> {
  5. BOOL _enableAppScheme;
  6. BOOL _enableZoom;
  7. NSString* _invalidUrlRegex;
  8. }
  9. @end
  10. @implementation FlutterWebviewPlugin
  11. + (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  12. channel = [FlutterMethodChannel
  13. methodChannelWithName:CHANNEL_NAME
  14. binaryMessenger:[registrar messenger]];
  15. UIViewController *viewController = [UIApplication sharedApplication].delegate.window.rootViewController;
  16. FlutterWebviewPlugin* instance = [[FlutterWebviewPlugin alloc] initWithViewController:viewController];
  17. [registrar addMethodCallDelegate:instance channel:channel];
  18. }
  19. - (instancetype)initWithViewController:(UIViewController *)viewController {
  20. self = [super init];
  21. if (self) {
  22. self.viewController = viewController;
  23. }
  24. return self;
  25. }
  26. - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  27. if ([@"launch" isEqualToString:call.method]) {
  28. if (!self.webview)
  29. [self initWebview:call];
  30. else
  31. [self navigate:call];
  32. result(nil);
  33. } else if ([@"close" isEqualToString:call.method]) {
  34. [self closeWebView];
  35. result(nil);
  36. } else if ([@"eval" isEqualToString:call.method]) {
  37. [self evalJavascript:call completionHandler:^(NSString * response) {
  38. result(response);
  39. }];
  40. } else if ([@"resize" isEqualToString:call.method]) {
  41. [self resize:call];
  42. result(nil);
  43. } else if ([@"reloadUrl" isEqualToString:call.method]) {
  44. [self reloadUrl:call];
  45. result(nil);
  46. } else if ([@"show" isEqualToString:call.method]) {
  47. [self show];
  48. result(nil);
  49. } else if ([@"hide" isEqualToString:call.method]) {
  50. [self hide];
  51. result(nil);
  52. } else if ([@"stopLoading" isEqualToString:call.method]) {
  53. [self stopLoading];
  54. result(nil);
  55. } else if ([@"cleanCookies" isEqualToString:call.method]) {
  56. [self cleanCookies];
  57. } else if ([@"back" isEqualToString:call.method]) {
  58. [self back];
  59. result(nil);
  60. } else if ([@"forward" isEqualToString:call.method]) {
  61. [self forward];
  62. result(nil);
  63. } else if ([@"reload" isEqualToString:call.method]) {
  64. [self reload];
  65. result(nil);
  66. } else {
  67. result(FlutterMethodNotImplemented);
  68. }
  69. }
  70. - (void)initWebview:(FlutterMethodCall*)call {
  71. NSNumber *clearCache = call.arguments[@"clearCache"];
  72. NSNumber *clearCookies = call.arguments[@"clearCookies"];
  73. NSNumber *hidden = call.arguments[@"hidden"];
  74. NSDictionary *rect = call.arguments[@"rect"];
  75. _enableAppScheme = call.arguments[@"enableAppScheme"];
  76. NSString *userAgent = call.arguments[@"userAgent"];
  77. NSNumber *withZoom = call.arguments[@"withZoom"];
  78. NSNumber *scrollBar = call.arguments[@"scrollBar"];
  79. NSNumber *withJavascript = call.arguments[@"withJavascript"];
  80. _invalidUrlRegex = call.arguments[@"invalidUrlRegex"];
  81. if (clearCache != (id)[NSNull null] && [clearCache boolValue]) {
  82. [[NSURLCache sharedURLCache] removeAllCachedResponses];
  83. }
  84. if (clearCookies != (id)[NSNull null] && [clearCookies boolValue]) {
  85. if (@available(iOS 9.0, *)) {
  86. NSSet *websiteDataTypes
  87. = [NSSet setWithArray:@[
  88. WKWebsiteDataTypeCookies,
  89. ]];
  90. NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
  91. [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
  92. }];
  93. } else {
  94. // Fallback on earlier versions
  95. }
  96. }
  97. if (userAgent != (id)[NSNull null]) {
  98. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": userAgent}];
  99. }
  100. CGRect rc;
  101. if (rect != nil) {
  102. rc = [self parseRect:rect];
  103. } else {
  104. rc = self.viewController.view.bounds;
  105. }
  106. self.webview = [[WKWebView alloc] initWithFrame:rc];
  107. self.webview.UIDelegate = self;
  108. self.webview.navigationDelegate = self;
  109. self.webview.scrollView.delegate = self;
  110. self.webview.hidden = [hidden boolValue];
  111. self.webview.scrollView.showsHorizontalScrollIndicator = [scrollBar boolValue];
  112. self.webview.scrollView.showsVerticalScrollIndicator = [scrollBar boolValue];
  113. [self.webview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
  114. WKPreferences* preferences = [[self.webview configuration] preferences];
  115. if ([withJavascript boolValue]) {
  116. [preferences setJavaScriptEnabled:YES];
  117. } else {
  118. [preferences setJavaScriptEnabled:NO];
  119. }
  120. _enableZoom = [withZoom boolValue];
  121. UIViewController* presentedViewController = self.viewController.presentedViewController;
  122. UIViewController* currentViewController = presentedViewController != nil ? presentedViewController : self.viewController;
  123. [currentViewController.view addSubview:self.webview];
  124. [self navigate:call];
  125. }
  126. - (CGRect)parseRect:(NSDictionary *)rect {
  127. return CGRectMake([[rect valueForKey:@"left"] doubleValue],
  128. [[rect valueForKey:@"top"] doubleValue],
  129. [[rect valueForKey:@"width"] doubleValue],
  130. [[rect valueForKey:@"height"] doubleValue]);
  131. }
  132. - (void) scrollViewDidScroll:(UIScrollView *)scrollView {
  133. id xDirection = @{@"xDirection": @(scrollView.contentOffset.x) };
  134. [channel invokeMethod:@"onScrollXChanged" arguments:xDirection];
  135. id yDirection = @{@"yDirection": @(scrollView.contentOffset.y) };
  136. [channel invokeMethod:@"onScrollYChanged" arguments:yDirection];
  137. }
  138. - (void)navigate:(FlutterMethodCall*)call {
  139. if (self.webview != nil) {
  140. NSString *url = call.arguments[@"url"];
  141. NSNumber *withLocalUrl = call.arguments[@"withLocalUrl"];
  142. if ( [withLocalUrl boolValue]) {
  143. NSURL *htmlUrl = [NSURL fileURLWithPath:url isDirectory:false];
  144. if (@available(iOS 9.0, *)) {
  145. [self.webview loadFileURL:htmlUrl allowingReadAccessToURL:htmlUrl];
  146. } else {
  147. @throw @"not available on version earlier than ios 9.0";
  148. }
  149. } else {
  150. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
  151. NSDictionary *headers = call.arguments[@"headers"];
  152. if (headers != nil) {
  153. [request setAllHTTPHeaderFields:headers];
  154. }
  155. [self.webview loadRequest:request];
  156. }
  157. }
  158. }
  159. - (void)evalJavascript:(FlutterMethodCall*)call
  160. completionHandler:(void (^_Nullable)(NSString * response))completionHandler {
  161. if (self.webview != nil) {
  162. NSString *code = call.arguments[@"code"];
  163. [self.webview evaluateJavaScript:code
  164. completionHandler:^(id _Nullable response, NSError * _Nullable error) {
  165. completionHandler([NSString stringWithFormat:@"%@", response]);
  166. }];
  167. } else {
  168. completionHandler(nil);
  169. }
  170. }
  171. - (void)resize:(FlutterMethodCall*)call {
  172. if (self.webview != nil) {
  173. NSDictionary *rect = call.arguments[@"rect"];
  174. CGRect rc = [self parseRect:rect];
  175. self.webview.frame = rc;
  176. }
  177. }
  178. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
  179. if ([keyPath isEqualToString:@"estimatedProgress"] && object == self.webview) {
  180. [channel invokeMethod:@"onProgressChanged" arguments:@{@"progress": @(self.webview.estimatedProgress)}];
  181. } else {
  182. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  183. }
  184. }
  185. - (void)closeWebView {
  186. if (self.webview != nil) {
  187. [self.webview stopLoading];
  188. [self.webview removeFromSuperview];
  189. self.webview.navigationDelegate = nil;
  190. [self.webview removeObserver:self forKeyPath:@"estimatedProgress"];
  191. self.webview = nil;
  192. // manually trigger onDestroy
  193. [channel invokeMethod:@"onDestroy" arguments:nil];
  194. }
  195. }
  196. - (void)reloadUrl:(FlutterMethodCall*)call {
  197. if (self.webview != nil) {
  198. NSString *url = call.arguments[@"url"];
  199. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
  200. NSDictionary *headers = call.arguments[@"headers"];
  201. if (headers != nil) {
  202. [request setAllHTTPHeaderFields:headers];
  203. }
  204. [self.webview loadRequest:request];
  205. }
  206. }
  207. - (void)show {
  208. if (self.webview != nil) {
  209. self.webview.hidden = false;
  210. }
  211. }
  212. - (void)hide {
  213. if (self.webview != nil) {
  214. self.webview.hidden = true;
  215. }
  216. }
  217. - (void)stopLoading {
  218. if (self.webview != nil) {
  219. [self.webview stopLoading];
  220. }
  221. }
  222. - (void)back {
  223. if (self.webview != nil) {
  224. [self.webview goBack];
  225. }
  226. }
  227. - (void)forward {
  228. if (self.webview != nil) {
  229. [self.webview goForward];
  230. }
  231. }
  232. - (void)reload {
  233. if (self.webview != nil) {
  234. [self.webview reload];
  235. }
  236. }
  237. - (void)cleanCookies {
  238. [[NSURLSession sharedSession] resetWithCompletionHandler:^{
  239. }];
  240. }
  241. - (bool)checkInvalidUrl:(NSURL*)url {
  242. NSString* urlString = url != nil ? [url absoluteString] : nil;
  243. if (_invalidUrlRegex != [NSNull null] && urlString != nil) {
  244. NSError* error = NULL;
  245. NSRegularExpression* regex =
  246. [NSRegularExpression regularExpressionWithPattern:_invalidUrlRegex
  247. options:NSRegularExpressionCaseInsensitive
  248. error:&error];
  249. NSTextCheckingResult* match = [regex firstMatchInString:urlString
  250. options:0
  251. range:NSMakeRange(0, [urlString length])];
  252. return match != nil;
  253. } else {
  254. return false;
  255. }
  256. }
  257. #pragma mark -- WkWebView Delegate
  258. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
  259. decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
  260. BOOL isInvalid = [self checkInvalidUrl: navigationAction.request.URL];
  261. id data = @{@"url": navigationAction.request.URL.absoluteString,
  262. @"type": isInvalid ? @"abortLoad" : @"shouldStart",
  263. @"navigationType": [NSNumber numberWithInt:navigationAction.navigationType]};
  264. [channel invokeMethod:@"onState" arguments:data];
  265. if (navigationAction.navigationType == WKNavigationTypeBackForward) {
  266. [channel invokeMethod:@"onBackPressed" arguments:nil];
  267. } else if (!isInvalid) {
  268. id data = @{@"url": navigationAction.request.URL.absoluteString};
  269. [channel invokeMethod:@"onUrlChanged" arguments:data];
  270. }
  271. if (_enableAppScheme ||
  272. ([webView.URL.scheme isEqualToString:@"http"] ||
  273. [webView.URL.scheme isEqualToString:@"https"] ||
  274. [webView.URL.scheme isEqualToString:@"about"])) {
  275. if (isInvalid) {
  276. decisionHandler(WKNavigationActionPolicyCancel);
  277. } else {
  278. decisionHandler(WKNavigationActionPolicyAllow);
  279. }
  280. } else {
  281. decisionHandler(WKNavigationActionPolicyCancel);
  282. }
  283. }
  284. - (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration
  285. forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
  286. if (!navigationAction.targetFrame.isMainFrame) {
  287. [webView loadRequest:navigationAction.request];
  288. }
  289. return nil;
  290. }
  291. - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
  292. [channel invokeMethod:@"onState" arguments:@{@"type": @"startLoad", @"url": webView.URL.absoluteString}];
  293. }
  294. - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
  295. [channel invokeMethod:@"onState" arguments:@{@"type": @"finishLoad", @"url": webView.URL.absoluteString}];
  296. }
  297. - (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
  298. [channel invokeMethod:@"onError" arguments:@{@"code": [NSString stringWithFormat:@"%ld", error.code], @"error": error.localizedDescription}];
  299. }
  300. - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
  301. if ([navigationResponse.response isKindOfClass:[NSHTTPURLResponse class]]) {
  302. NSHTTPURLResponse * response = (NSHTTPURLResponse *)navigationResponse.response;
  303. [channel invokeMethod:@"onHttpError" arguments:@{@"code": [NSString stringWithFormat:@"%ld", response.statusCode], @"url": webView.URL.absoluteString}];
  304. }
  305. decisionHandler(WKNavigationResponsePolicyAllow);
  306. }
  307. #pragma mark -- UIScrollViewDelegate
  308. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
  309. if (scrollView.pinchGestureRecognizer.isEnabled != _enableZoom) {
  310. scrollView.pinchGestureRecognizer.enabled = _enableZoom;
  311. }
  312. }
  313. @end