FlutterWebviewPlugin.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. NSString *localUrlScope = call.arguments[@"localUrlScope"];
  156. if (@available(iOS 9.0, *)) {
  157. if(localUrlScope == nil) {
  158. [self.webview loadFileURL:htmlUrl allowingReadAccessToURL:htmlUrl];
  159. }
  160. else {
  161. NSURL *scopeUrl = [NSURL fileURLWithPath:localUrlScope];
  162. [self.webview loadFileURL:htmlUrl allowingReadAccessToURL:scopeUrl];
  163. }
  164. } else {
  165. @throw @"not available on version earlier than ios 9.0";
  166. }
  167. } else {
  168. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
  169. NSDictionary *headers = call.arguments[@"headers"];
  170. if (headers != nil) {
  171. [request setAllHTTPHeaderFields:headers];
  172. }
  173. [self.webview loadRequest:request];
  174. }
  175. }
  176. }
  177. - (void)evalJavascript:(FlutterMethodCall*)call
  178. completionHandler:(void (^_Nullable)(NSString * response))completionHandler {
  179. if (self.webview != nil) {
  180. NSString *code = call.arguments[@"code"];
  181. [self.webview evaluateJavaScript:code
  182. completionHandler:^(id _Nullable response, NSError * _Nullable error) {
  183. completionHandler([NSString stringWithFormat:@"%@", response]);
  184. }];
  185. } else {
  186. completionHandler(nil);
  187. }
  188. }
  189. - (void)resize:(FlutterMethodCall*)call {
  190. if (self.webview != nil) {
  191. NSDictionary *rect = call.arguments[@"rect"];
  192. CGRect rc = [self parseRect:rect];
  193. self.webview.frame = rc;
  194. }
  195. }
  196. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
  197. if ([keyPath isEqualToString:@"estimatedProgress"] && object == self.webview) {
  198. [channel invokeMethod:@"onProgressChanged" arguments:@{@"progress": @(self.webview.estimatedProgress)}];
  199. } else {
  200. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  201. }
  202. }
  203. - (void)closeWebView {
  204. if (self.webview != nil) {
  205. [self.webview stopLoading];
  206. [self.webview removeFromSuperview];
  207. self.webview.navigationDelegate = nil;
  208. [self.webview removeObserver:self forKeyPath:@"estimatedProgress"];
  209. self.webview = nil;
  210. // manually trigger onDestroy
  211. [channel invokeMethod:@"onDestroy" arguments:nil];
  212. }
  213. }
  214. - (void)reloadUrl:(FlutterMethodCall*)call {
  215. if (self.webview != nil) {
  216. NSString *url = call.arguments[@"url"];
  217. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
  218. NSDictionary *headers = call.arguments[@"headers"];
  219. if (headers != nil) {
  220. [request setAllHTTPHeaderFields:headers];
  221. }
  222. [self.webview loadRequest:request];
  223. }
  224. }
  225. - (void)show {
  226. if (self.webview != nil) {
  227. self.webview.hidden = false;
  228. }
  229. }
  230. - (void)hide {
  231. if (self.webview != nil) {
  232. self.webview.hidden = true;
  233. }
  234. }
  235. - (void)stopLoading {
  236. if (self.webview != nil) {
  237. [self.webview stopLoading];
  238. }
  239. }
  240. - (void)back {
  241. if (self.webview != nil) {
  242. [self.webview goBack];
  243. }
  244. }
  245. - (void)forward {
  246. if (self.webview != nil) {
  247. [self.webview goForward];
  248. }
  249. }
  250. - (void)reload {
  251. if (self.webview != nil) {
  252. [self.webview reload];
  253. }
  254. }
  255. - (void)cleanCookies {
  256. [[NSURLSession sharedSession] resetWithCompletionHandler:^{
  257. }];
  258. }
  259. - (bool)checkInvalidUrl:(NSURL*)url {
  260. NSString* urlString = url != nil ? [url absoluteString] : nil;
  261. if (_invalidUrlRegex != [NSNull null] && urlString != nil) {
  262. NSError* error = NULL;
  263. NSRegularExpression* regex =
  264. [NSRegularExpression regularExpressionWithPattern:_invalidUrlRegex
  265. options:NSRegularExpressionCaseInsensitive
  266. error:&error];
  267. NSTextCheckingResult* match = [regex firstMatchInString:urlString
  268. options:0
  269. range:NSMakeRange(0, [urlString length])];
  270. return match != nil;
  271. } else {
  272. return false;
  273. }
  274. }
  275. #pragma mark -- WkWebView Delegate
  276. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
  277. decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
  278. BOOL isInvalid = [self checkInvalidUrl: navigationAction.request.URL];
  279. id data = @{@"url": navigationAction.request.URL.absoluteString,
  280. @"type": isInvalid ? @"abortLoad" : @"shouldStart",
  281. @"navigationType": [NSNumber numberWithInt:navigationAction.navigationType]};
  282. [channel invokeMethod:@"onState" arguments:data];
  283. if (navigationAction.navigationType == WKNavigationTypeBackForward) {
  284. [channel invokeMethod:@"onBackPressed" arguments:nil];
  285. } else if (!isInvalid) {
  286. id data = @{@"url": navigationAction.request.URL.absoluteString};
  287. [channel invokeMethod:@"onUrlChanged" arguments:data];
  288. }
  289. if (_enableAppScheme ||
  290. ([webView.URL.scheme isEqualToString:@"http"] ||
  291. [webView.URL.scheme isEqualToString:@"https"] ||
  292. [webView.URL.scheme isEqualToString:@"about"] ||
  293. [webView.URL.scheme isEqualToString:@"file"])) {
  294. if (isInvalid) {
  295. decisionHandler(WKNavigationActionPolicyCancel);
  296. } else {
  297. decisionHandler(WKNavigationActionPolicyAllow);
  298. }
  299. } else {
  300. decisionHandler(WKNavigationActionPolicyCancel);
  301. }
  302. }
  303. - (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration
  304. forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
  305. if (!navigationAction.targetFrame.isMainFrame) {
  306. [webView loadRequest:navigationAction.request];
  307. }
  308. return nil;
  309. }
  310. - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
  311. [channel invokeMethod:@"onState" arguments:@{@"type": @"startLoad", @"url": webView.URL.absoluteString}];
  312. }
  313. - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
  314. [channel invokeMethod:@"onState" arguments:@{@"type": @"finishLoad", @"url": webView.URL.absoluteString}];
  315. }
  316. - (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
  317. [channel invokeMethod:@"onError" arguments:@{@"code": [NSString stringWithFormat:@"%ld", error.code], @"error": error.localizedDescription}];
  318. }
  319. - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
  320. if ([navigationResponse.response isKindOfClass:[NSHTTPURLResponse class]]) {
  321. NSHTTPURLResponse * response = (NSHTTPURLResponse *)navigationResponse.response;
  322. [channel invokeMethod:@"onHttpError" arguments:@{@"code": [NSString stringWithFormat:@"%ld", response.statusCode], @"url": webView.URL.absoluteString}];
  323. }
  324. decisionHandler(WKNavigationResponsePolicyAllow);
  325. }
  326. - (void)registerJavaScriptChannels:(NSSet*)channelNames
  327. controller:(WKUserContentController*)userContentController {
  328. for (NSString* channelName in channelNames) {
  329. FLTJavaScriptChannel* _channel =
  330. [[FLTJavaScriptChannel alloc] initWithMethodChannel: channel
  331. javaScriptChannelName:channelName];
  332. [userContentController addScriptMessageHandler:_channel name:channelName];
  333. NSString* wrapperSource = [NSString
  334. stringWithFormat:@"window.%@ = webkit.messageHandlers.%@;", channelName, channelName];
  335. WKUserScript* wrapperScript =
  336. [[WKUserScript alloc] initWithSource:wrapperSource
  337. injectionTime:WKUserScriptInjectionTimeAtDocumentStart
  338. forMainFrameOnly:NO];
  339. [userContentController addUserScript:wrapperScript];
  340. }
  341. }
  342. #pragma mark -- UIScrollViewDelegate
  343. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
  344. if (scrollView.pinchGestureRecognizer.isEnabled != _enableZoom) {
  345. scrollView.pinchGestureRecognizer.enabled = _enableZoom;
  346. }
  347. }
  348. @end