FlutterWebviewPlugin.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. [[NSURLSession sharedSession] resetWithCompletionHandler:^{
  86. }];
  87. }
  88. if (userAgent != (id)[NSNull null]) {
  89. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": userAgent}];
  90. }
  91. CGRect rc;
  92. if (rect != nil) {
  93. rc = [self parseRect:rect];
  94. } else {
  95. rc = self.viewController.view.bounds;
  96. }
  97. self.webview = [[WKWebView alloc] initWithFrame:rc];
  98. self.webview.UIDelegate = self;
  99. self.webview.navigationDelegate = self;
  100. self.webview.scrollView.delegate = self;
  101. self.webview.hidden = [hidden boolValue];
  102. self.webview.scrollView.showsHorizontalScrollIndicator = [scrollBar boolValue];
  103. self.webview.scrollView.showsVerticalScrollIndicator = [scrollBar boolValue];
  104. [self.webview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
  105. WKPreferences* preferences = [[self.webview configuration] preferences];
  106. if ([withJavascript boolValue]) {
  107. [preferences setJavaScriptEnabled:YES];
  108. } else {
  109. [preferences setJavaScriptEnabled:NO];
  110. }
  111. _enableZoom = [withZoom boolValue];
  112. UIViewController* presentedViewController = self.viewController.presentedViewController;
  113. UIViewController* currentViewController = presentedViewController != nil ? presentedViewController : self.viewController;
  114. [currentViewController.view addSubview:self.webview];
  115. [self navigate:call];
  116. }
  117. - (CGRect)parseRect:(NSDictionary *)rect {
  118. return CGRectMake([[rect valueForKey:@"left"] doubleValue],
  119. [[rect valueForKey:@"top"] doubleValue],
  120. [[rect valueForKey:@"width"] doubleValue],
  121. [[rect valueForKey:@"height"] doubleValue]);
  122. }
  123. - (void) scrollViewDidScroll:(UIScrollView *)scrollView {
  124. id xDirection = @{@"xDirection": @(scrollView.contentOffset.x) };
  125. [channel invokeMethod:@"onScrollXChanged" arguments:xDirection];
  126. id yDirection = @{@"yDirection": @(scrollView.contentOffset.y) };
  127. [channel invokeMethod:@"onScrollYChanged" arguments:yDirection];
  128. }
  129. - (void)navigate:(FlutterMethodCall*)call {
  130. if (self.webview != nil) {
  131. NSString *url = call.arguments[@"url"];
  132. NSNumber *withLocalUrl = call.arguments[@"withLocalUrl"];
  133. if ( [withLocalUrl boolValue]) {
  134. NSURL *htmlUrl = [NSURL fileURLWithPath:url isDirectory:false];
  135. NSString *localUrlScope = call.arguments[@"localUrlScope"];
  136. if (@available(iOS 9.0, *)) {
  137. if(localUrlScope == nil) {
  138. [self.webview loadFileURL:htmlUrl allowingReadAccessToURL:htmlUrl];
  139. }
  140. else {
  141. NSURL *scopeUrl = [NSURL fileURLWithPath:localUrlScope];
  142. [self.webview loadFileURL:htmlUrl allowingReadAccessToURL:scopeUrl];
  143. }
  144. } else {
  145. @throw @"not available on version earlier than ios 9.0";
  146. }
  147. } else {
  148. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
  149. NSDictionary *headers = call.arguments[@"headers"];
  150. if (headers != nil) {
  151. [request setAllHTTPHeaderFields:headers];
  152. }
  153. [self.webview loadRequest:request];
  154. }
  155. }
  156. }
  157. - (void)evalJavascript:(FlutterMethodCall*)call
  158. completionHandler:(void (^_Nullable)(NSString * response))completionHandler {
  159. if (self.webview != nil) {
  160. NSString *code = call.arguments[@"code"];
  161. [self.webview evaluateJavaScript:code
  162. completionHandler:^(id _Nullable response, NSError * _Nullable error) {
  163. completionHandler([NSString stringWithFormat:@"%@", response]);
  164. }];
  165. } else {
  166. completionHandler(nil);
  167. }
  168. }
  169. - (void)resize:(FlutterMethodCall*)call {
  170. if (self.webview != nil) {
  171. NSDictionary *rect = call.arguments[@"rect"];
  172. CGRect rc = [self parseRect:rect];
  173. self.webview.frame = rc;
  174. }
  175. }
  176. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
  177. if ([keyPath isEqualToString:@"estimatedProgress"] && object == self.webview) {
  178. [channel invokeMethod:@"onProgressChanged" arguments:@{@"progress": @(self.webview.estimatedProgress)}];
  179. } else {
  180. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  181. }
  182. }
  183. - (void)closeWebView {
  184. if (self.webview != nil) {
  185. [self.webview stopLoading];
  186. [self.webview removeFromSuperview];
  187. self.webview.navigationDelegate = nil;
  188. [self.webview removeObserver:self forKeyPath:@"estimatedProgress"];
  189. self.webview = nil;
  190. // manually trigger onDestroy
  191. [channel invokeMethod:@"onDestroy" arguments:nil];
  192. }
  193. }
  194. - (void)reloadUrl:(FlutterMethodCall*)call {
  195. if (self.webview != nil) {
  196. NSString *url = call.arguments[@"url"];
  197. NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
  198. [self.webview loadRequest:request];
  199. }
  200. }
  201. - (void)show {
  202. if (self.webview != nil) {
  203. self.webview.hidden = false;
  204. }
  205. }
  206. - (void)hide {
  207. if (self.webview != nil) {
  208. self.webview.hidden = true;
  209. }
  210. }
  211. - (void)stopLoading {
  212. if (self.webview != nil) {
  213. [self.webview stopLoading];
  214. }
  215. }
  216. - (void)back {
  217. if (self.webview != nil) {
  218. [self.webview goBack];
  219. }
  220. }
  221. - (void)forward {
  222. if (self.webview != nil) {
  223. [self.webview goForward];
  224. }
  225. }
  226. - (void)reload {
  227. if (self.webview != nil) {
  228. [self.webview reload];
  229. }
  230. }
  231. - (void)cleanCookies {
  232. [[NSURLSession sharedSession] resetWithCompletionHandler:^{
  233. }];
  234. }
  235. - (bool)checkInvalidUrl:(NSURL*)url {
  236. NSString* urlString = url != nil ? [url absoluteString] : nil;
  237. if (_invalidUrlRegex != [NSNull null] && urlString != nil) {
  238. NSError* error = NULL;
  239. NSRegularExpression* regex =
  240. [NSRegularExpression regularExpressionWithPattern:_invalidUrlRegex
  241. options:NSRegularExpressionCaseInsensitive
  242. error:&error];
  243. NSTextCheckingResult* match = [regex firstMatchInString:urlString
  244. options:0
  245. range:NSMakeRange(0, [urlString length])];
  246. return match != nil;
  247. } else {
  248. return false;
  249. }
  250. }
  251. #pragma mark -- WkWebView Delegate
  252. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
  253. decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
  254. BOOL isInvalid = [self checkInvalidUrl: navigationAction.request.URL];
  255. id data = @{@"url": navigationAction.request.URL.absoluteString,
  256. @"type": isInvalid ? @"abortLoad" : @"shouldStart",
  257. @"navigationType": [NSNumber numberWithInt:navigationAction.navigationType]};
  258. [channel invokeMethod:@"onState" arguments:data];
  259. if (navigationAction.navigationType == WKNavigationTypeBackForward) {
  260. [channel invokeMethod:@"onBackPressed" arguments:nil];
  261. } else if (!isInvalid) {
  262. id data = @{@"url": navigationAction.request.URL.absoluteString};
  263. [channel invokeMethod:@"onUrlChanged" arguments:data];
  264. }
  265. if (_enableAppScheme ||
  266. ([webView.URL.scheme isEqualToString:@"http"] ||
  267. [webView.URL.scheme isEqualToString:@"https"] ||
  268. [webView.URL.scheme isEqualToString:@"about"] ||
  269. [webView.URL.scheme isEqualToString:@"file"])) {
  270. if (isInvalid) {
  271. decisionHandler(WKNavigationActionPolicyCancel);
  272. } else {
  273. decisionHandler(WKNavigationActionPolicyAllow);
  274. }
  275. } else {
  276. decisionHandler(WKNavigationActionPolicyCancel);
  277. }
  278. }
  279. - (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration
  280. forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
  281. if (!navigationAction.targetFrame.isMainFrame) {
  282. [webView loadRequest:navigationAction.request];
  283. }
  284. return nil;
  285. }
  286. - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
  287. [channel invokeMethod:@"onState" arguments:@{@"type": @"startLoad", @"url": webView.URL.absoluteString}];
  288. }
  289. - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
  290. [channel invokeMethod:@"onState" arguments:@{@"type": @"finishLoad", @"url": webView.URL.absoluteString}];
  291. }
  292. - (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
  293. [channel invokeMethod:@"onError" arguments:@{@"code": [NSString stringWithFormat:@"%ld", error.code], @"error": error.localizedDescription}];
  294. }
  295. - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
  296. if ([navigationResponse.response isKindOfClass:[NSHTTPURLResponse class]]) {
  297. NSHTTPURLResponse * response = (NSHTTPURLResponse *)navigationResponse.response;
  298. [channel invokeMethod:@"onHttpError" arguments:@{@"code": [NSString stringWithFormat:@"%ld", response.statusCode], @"url": webView.URL.absoluteString}];
  299. }
  300. decisionHandler(WKNavigationResponsePolicyAllow);
  301. }
  302. #pragma mark -- UIScrollViewDelegate
  303. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
  304. if (scrollView.pinchGestureRecognizer.isEnabled != _enableZoom) {
  305. scrollView.pinchGestureRecognizer.enabled = _enableZoom;
  306. }
  307. }
  308. @end