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. result(nil);
  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 {
  70. result(FlutterMethodNotImplemented);
  71. }
  72. }
  73. - (void)initWebview:(FlutterMethodCall*)call {
  74. NSNumber *clearCache = call.arguments[@"clearCache"];
  75. NSNumber *clearCookies = call.arguments[@"clearCookies"];
  76. NSNumber *hidden = call.arguments[@"hidden"];
  77. NSDictionary *rect = call.arguments[@"rect"];
  78. _enableAppScheme = call.arguments[@"enableAppScheme"];
  79. NSString *userAgent = call.arguments[@"userAgent"];
  80. NSNumber *withZoom = call.arguments[@"withZoom"];
  81. NSNumber *scrollBar = call.arguments[@"scrollBar"];
  82. NSNumber *withJavascript = call.arguments[@"withJavascript"];
  83. _invalidUrlRegex = call.arguments[@"invalidUrlRegex"];
  84. _javaScriptChannelNames = [[NSMutableSet alloc] init];
  85. WKUserContentController* userContentController = [[WKUserContentController alloc] init];
  86. if ([call.arguments[@"javascriptChannelNames"] isKindOfClass:[NSArray class]]) {
  87. NSArray* javaScriptChannelNames = call.arguments[@"javascriptChannelNames"];
  88. [_javaScriptChannelNames addObjectsFromArray:javaScriptChannelNames];
  89. [self registerJavaScriptChannels:_javaScriptChannelNames controller:userContentController];
  90. }
  91. if (clearCache != (id)[NSNull null] && [clearCache boolValue]) {
  92. [[NSURLCache sharedURLCache] removeAllCachedResponses];
  93. }
  94. if (clearCookies != (id)[NSNull null] && [clearCookies boolValue]) {
  95. NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  96. for (NSHTTPCookie *cookie in [storage cookies])
  97. {
  98. [storage deleteCookie:cookie];
  99. }
  100. }
  101. if (userAgent != (id)[NSNull null]) {
  102. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": userAgent}];
  103. }
  104. CGRect rc;
  105. if (rect != nil) {
  106. rc = [self parseRect:rect];
  107. } else {
  108. rc = self.viewController.view.bounds;
  109. }
  110. WKWebViewConfiguration* configuration = [[WKWebViewConfiguration alloc] init];
  111. configuration.userContentController = userContentController;
  112. self.webview = [[WKWebView alloc] initWithFrame:rc configuration:configuration];
  113. self.webview.UIDelegate = self;
  114. self.webview.navigationDelegate = self;
  115. self.webview.scrollView.delegate = self;
  116. self.webview.hidden = [hidden boolValue];
  117. self.webview.scrollView.showsHorizontalScrollIndicator = [scrollBar boolValue];
  118. self.webview.scrollView.showsVerticalScrollIndicator = [scrollBar boolValue];
  119. [self.webview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
  120. WKPreferences* preferences = [[self.webview configuration] preferences];
  121. if ([withJavascript boolValue]) {
  122. [preferences setJavaScriptEnabled:YES];
  123. } else {
  124. [preferences setJavaScriptEnabled:NO];
  125. }
  126. _enableZoom = [withZoom boolValue];
  127. UIViewController* presentedViewController = self.viewController.presentedViewController;
  128. UIViewController* currentViewController = presentedViewController != nil ? presentedViewController : self.viewController;
  129. [currentViewController.view addSubview:self.webview];
  130. [self navigate:call];
  131. }
  132. - (CGRect)parseRect:(NSDictionary *)rect {
  133. return CGRectMake([[rect valueForKey:@"left"] doubleValue],
  134. [[rect valueForKey:@"top"] doubleValue],
  135. [[rect valueForKey:@"width"] doubleValue],
  136. [[rect valueForKey:@"height"] doubleValue]);
  137. }
  138. - (void) scrollViewDidScroll:(UIScrollView *)scrollView {
  139. id xDirection = @{@"xDirection": @(scrollView.contentOffset.x) };
  140. [channel invokeMethod:@"onScrollXChanged" arguments:xDirection];
  141. id yDirection = @{@"yDirection": @(scrollView.contentOffset.y) };
  142. [channel invokeMethod:@"onScrollYChanged" arguments:yDirection];
  143. }
  144. - (void)navigate:(FlutterMethodCall*)call {
  145. if (self.webview != nil) {
  146. NSString *url = call.arguments[@"url"];
  147. NSNumber *withLocalUrl = call.arguments[@"withLocalUrl"];
  148. if ( [withLocalUrl boolValue]) {
  149. NSURL *htmlUrl = [NSURL fileURLWithPath:url isDirectory:false];
  150. NSString *localUrlScope = call.arguments[@"localUrlScope"];
  151. if (@available(iOS 9.0, *)) {
  152. if(localUrlScope == nil) {
  153. [self.webview loadFileURL:htmlUrl allowingReadAccessToURL:htmlUrl];
  154. }
  155. else {
  156. NSURL *scopeUrl = [NSURL fileURLWithPath:localUrlScope];
  157. [self.webview loadFileURL:htmlUrl allowingReadAccessToURL:scopeUrl];
  158. }
  159. } else {
  160. @throw @"not available on version earlier than ios 9.0";
  161. }
  162. } else {
  163. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
  164. NSDictionary *headers = call.arguments[@"headers"];
  165. if (headers != nil) {
  166. [request setAllHTTPHeaderFields:headers];
  167. }
  168. [self.webview loadRequest:request];
  169. }
  170. }
  171. }
  172. - (void)evalJavascript:(FlutterMethodCall*)call
  173. completionHandler:(void (^_Nullable)(NSString * response))completionHandler {
  174. if (self.webview != nil) {
  175. NSString *code = call.arguments[@"code"];
  176. [self.webview evaluateJavaScript:code
  177. completionHandler:^(id _Nullable response, NSError * _Nullable error) {
  178. completionHandler([NSString stringWithFormat:@"%@", response]);
  179. }];
  180. } else {
  181. completionHandler(nil);
  182. }
  183. }
  184. - (void)resize:(FlutterMethodCall*)call {
  185. if (self.webview != nil) {
  186. NSDictionary *rect = call.arguments[@"rect"];
  187. CGRect rc = [self parseRect:rect];
  188. self.webview.frame = rc;
  189. }
  190. }
  191. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
  192. if ([keyPath isEqualToString:@"estimatedProgress"] && object == self.webview) {
  193. [channel invokeMethod:@"onProgressChanged" arguments:@{@"progress": @(self.webview.estimatedProgress)}];
  194. } else {
  195. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  196. }
  197. }
  198. - (void)closeWebView {
  199. if (self.webview != nil) {
  200. [self.webview stopLoading];
  201. [self.webview removeFromSuperview];
  202. self.webview.navigationDelegate = nil;
  203. [self.webview removeObserver:self forKeyPath:@"estimatedProgress"];
  204. self.webview = nil;
  205. // manually trigger onDestroy
  206. [channel invokeMethod:@"onDestroy" arguments:nil];
  207. }
  208. }
  209. - (void)reloadUrl:(FlutterMethodCall*)call {
  210. if (self.webview != nil) {
  211. NSString *url = call.arguments[@"url"];
  212. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
  213. NSDictionary *headers = call.arguments[@"headers"];
  214. if (headers != nil) {
  215. [request setAllHTTPHeaderFields:headers];
  216. }
  217. [self.webview loadRequest:request];
  218. }
  219. }
  220. - (void)cleanCookies {
  221. if(self.webview != nil) {
  222. NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  223. for (NSHTTPCookie *cookie in [storage cookies])
  224. {
  225. [storage deleteCookie:cookie];
  226. }
  227. }
  228. }
  229. - (void)show {
  230. if (self.webview != nil) {
  231. self.webview.hidden = false;
  232. }
  233. }
  234. - (void)hide {
  235. if (self.webview != nil) {
  236. self.webview.hidden = true;
  237. }
  238. }
  239. - (void)stopLoading {
  240. if (self.webview != nil) {
  241. [self.webview stopLoading];
  242. }
  243. }
  244. - (void)back {
  245. if (self.webview != nil) {
  246. [self.webview goBack];
  247. }
  248. }
  249. - (void)forward {
  250. if (self.webview != nil) {
  251. [self.webview goForward];
  252. }
  253. }
  254. - (void)reload {
  255. if (self.webview != nil) {
  256. [self.webview reload];
  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