FlutterWebviewPlugin.m 15 KB

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