FlutterWebviewPlugin.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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 if ([@"canGoBack" isEqualToString:call.method]) {
  70. [self onCanGoBack:call result:result];
  71. } else if ([@"canGoForward" isEqualToString:call.method]) {
  72. [self onCanGoForward:call result:result];
  73. } else {
  74. result(FlutterMethodNotImplemented);
  75. }
  76. }
  77. - (void)initWebview:(FlutterMethodCall*)call {
  78. NSNumber *clearCache = call.arguments[@"clearCache"];
  79. NSNumber *clearCookies = call.arguments[@"clearCookies"];
  80. NSNumber *hidden = call.arguments[@"hidden"];
  81. NSDictionary *rect = call.arguments[@"rect"];
  82. _enableAppScheme = call.arguments[@"enableAppScheme"];
  83. NSString *userAgent = call.arguments[@"userAgent"];
  84. NSNumber *withZoom = call.arguments[@"withZoom"];
  85. NSNumber *scrollBar = call.arguments[@"scrollBar"];
  86. NSNumber *withJavascript = call.arguments[@"withJavascript"];
  87. _invalidUrlRegex = call.arguments[@"invalidUrlRegex"];
  88. _javaScriptChannelNames = [[NSMutableSet alloc] init];
  89. WKUserContentController* userContentController = [[WKUserContentController alloc] init];
  90. if ([call.arguments[@"javascriptChannelNames"] isKindOfClass:[NSArray class]]) {
  91. NSArray* javaScriptChannelNames = call.arguments[@"javascriptChannelNames"];
  92. [_javaScriptChannelNames addObjectsFromArray:javaScriptChannelNames];
  93. [self registerJavaScriptChannels:_javaScriptChannelNames controller:userContentController];
  94. }
  95. if (clearCache != (id)[NSNull null] && [clearCache boolValue]) {
  96. [[NSURLCache sharedURLCache] removeAllCachedResponses];
  97. }
  98. if (clearCookies != (id)[NSNull null] && [clearCookies boolValue]) {
  99. NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  100. for (NSHTTPCookie *cookie in [storage cookies])
  101. {
  102. [storage deleteCookie:cookie];
  103. }
  104. }
  105. if (userAgent != (id)[NSNull null]) {
  106. [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent": userAgent}];
  107. }
  108. CGRect rc;
  109. if (rect != nil) {
  110. rc = [self parseRect:rect];
  111. } else {
  112. rc = self.viewController.view.bounds;
  113. }
  114. WKWebViewConfiguration* configuration = [[WKWebViewConfiguration alloc] init];
  115. configuration.userContentController = userContentController;
  116. self.webview = [[WKWebView alloc] initWithFrame:rc configuration:configuration];
  117. self.webview.UIDelegate = self;
  118. self.webview.navigationDelegate = self;
  119. self.webview.scrollView.delegate = self;
  120. self.webview.hidden = [hidden boolValue];
  121. self.webview.scrollView.showsHorizontalScrollIndicator = [scrollBar boolValue];
  122. self.webview.scrollView.showsVerticalScrollIndicator = [scrollBar boolValue];
  123. [self.webview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
  124. WKPreferences* preferences = [[self.webview configuration] preferences];
  125. if ([withJavascript boolValue]) {
  126. [preferences setJavaScriptEnabled:YES];
  127. } else {
  128. [preferences setJavaScriptEnabled:NO];
  129. }
  130. _enableZoom = [withZoom boolValue];
  131. UIViewController* presentedViewController = self.viewController.presentedViewController;
  132. UIViewController* currentViewController = presentedViewController != nil ? presentedViewController : self.viewController;
  133. [currentViewController.view addSubview:self.webview];
  134. [self navigate:call];
  135. }
  136. - (CGRect)parseRect:(NSDictionary *)rect {
  137. return CGRectMake([[rect valueForKey:@"left"] doubleValue],
  138. [[rect valueForKey:@"top"] doubleValue],
  139. [[rect valueForKey:@"width"] doubleValue],
  140. [[rect valueForKey:@"height"] doubleValue]);
  141. }
  142. - (void) scrollViewDidScroll:(UIScrollView *)scrollView {
  143. id xDirection = @{@"xDirection": @(scrollView.contentOffset.x) };
  144. [channel invokeMethod:@"onScrollXChanged" arguments:xDirection];
  145. id yDirection = @{@"yDirection": @(scrollView.contentOffset.y) };
  146. [channel invokeMethod:@"onScrollYChanged" arguments:yDirection];
  147. }
  148. - (void)navigate:(FlutterMethodCall*)call {
  149. if (self.webview != nil) {
  150. NSString *url = call.arguments[@"url"];
  151. NSNumber *withLocalUrl = call.arguments[@"withLocalUrl"];
  152. if ( [withLocalUrl boolValue]) {
  153. NSURL *htmlUrl = [NSURL fileURLWithPath:url isDirectory:false];
  154. NSString *localUrlScope = call.arguments[@"localUrlScope"];
  155. if (@available(iOS 9.0, *)) {
  156. if(localUrlScope == nil) {
  157. [self.webview loadFileURL:htmlUrl allowingReadAccessToURL:htmlUrl];
  158. }
  159. else {
  160. NSURL *scopeUrl = [NSURL fileURLWithPath:localUrlScope];
  161. [self.webview loadFileURL:htmlUrl allowingReadAccessToURL:scopeUrl];
  162. }
  163. } else {
  164. @throw @"not available on version earlier than ios 9.0";
  165. }
  166. } else {
  167. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
  168. NSDictionary *headers = call.arguments[@"headers"];
  169. if (headers != nil) {
  170. [request setAllHTTPHeaderFields:headers];
  171. }
  172. [self.webview loadRequest:request];
  173. }
  174. }
  175. }
  176. - (void)evalJavascript:(FlutterMethodCall*)call
  177. completionHandler:(void (^_Nullable)(NSString * response))completionHandler {
  178. if (self.webview != nil) {
  179. NSString *code = call.arguments[@"code"];
  180. [self.webview evaluateJavaScript:code
  181. completionHandler:^(id _Nullable response, NSError * _Nullable error) {
  182. completionHandler([NSString stringWithFormat:@"%@", response]);
  183. }];
  184. } else {
  185. completionHandler(nil);
  186. }
  187. }
  188. - (void)resize:(FlutterMethodCall*)call {
  189. if (self.webview != nil) {
  190. NSDictionary *rect = call.arguments[@"rect"];
  191. CGRect rc = [self parseRect:rect];
  192. self.webview.frame = rc;
  193. }
  194. }
  195. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
  196. if ([keyPath isEqualToString:@"estimatedProgress"] && object == self.webview) {
  197. [channel invokeMethod:@"onProgressChanged" arguments:@{@"progress": @(self.webview.estimatedProgress)}];
  198. } else {
  199. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  200. }
  201. }
  202. - (void)closeWebView {
  203. if (self.webview != nil) {
  204. [self.webview stopLoading];
  205. [self.webview removeFromSuperview];
  206. self.webview.navigationDelegate = nil;
  207. [self.webview removeObserver:self forKeyPath:@"estimatedProgress"];
  208. self.webview = nil;
  209. // manually trigger onDestroy
  210. [channel invokeMethod:@"onDestroy" arguments:nil];
  211. }
  212. }
  213. - (void)reloadUrl:(FlutterMethodCall*)call {
  214. if (self.webview != nil) {
  215. NSString *url = call.arguments[@"url"];
  216. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
  217. NSDictionary *headers = call.arguments[@"headers"];
  218. if (headers != nil) {
  219. [request setAllHTTPHeaderFields:headers];
  220. }
  221. [self.webview loadRequest:request];
  222. }
  223. }
  224. - (void)cleanCookies {
  225. if(self.webview != nil) {
  226. NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  227. for (NSHTTPCookie *cookie in [storage cookies])
  228. {
  229. [storage deleteCookie:cookie];
  230. }
  231. }
  232. }
  233. - (void)show {
  234. if (self.webview != nil) {
  235. self.webview.hidden = false;
  236. }
  237. }
  238. - (void)hide {
  239. if (self.webview != nil) {
  240. self.webview.hidden = true;
  241. }
  242. }
  243. - (void)stopLoading {
  244. if (self.webview != nil) {
  245. [self.webview stopLoading];
  246. }
  247. }
  248. - (void)back {
  249. if (self.webview != nil) {
  250. [self.webview goBack];
  251. }
  252. }
  253. - (void)onCanGoBack:(FlutterMethodCall*)call result:(FlutterResult)result {
  254. BOOL canGoBack = [self.webview canGoBack];
  255. result([NSNumber numberWithBool:canGoBack]);
  256. }
  257. - (void)onCanGoForward:(FlutterMethodCall*)call result:(FlutterResult)result {
  258. BOOL canGoForward = [self.webview canGoForward];
  259. result([NSNumber numberWithBool:canGoForward]);
  260. }
  261. - (void)forward {
  262. if (self.webview != nil) {
  263. [self.webview goForward];
  264. }
  265. }
  266. - (void)reload {
  267. if (self.webview != nil) {
  268. [self.webview reload];
  269. }
  270. }
  271. - (bool)checkInvalidUrl:(NSURL*)url {
  272. NSString* urlString = url != nil ? [url absoluteString] : nil;
  273. if (_invalidUrlRegex != [NSNull null] && urlString != nil) {
  274. NSError* error = NULL;
  275. NSRegularExpression* regex =
  276. [NSRegularExpression regularExpressionWithPattern:_invalidUrlRegex
  277. options:NSRegularExpressionCaseInsensitive
  278. error:&error];
  279. NSTextCheckingResult* match = [regex firstMatchInString:urlString
  280. options:0
  281. range:NSMakeRange(0, [urlString length])];
  282. return match != nil;
  283. } else {
  284. return false;
  285. }
  286. }
  287. #pragma mark -- WkWebView Delegate
  288. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
  289. decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
  290. BOOL isInvalid = [self checkInvalidUrl: navigationAction.request.URL];
  291. id data = @{@"url": navigationAction.request.URL.absoluteString,
  292. @"type": isInvalid ? @"abortLoad" : @"shouldStart",
  293. @"navigationType": [NSNumber numberWithInt:navigationAction.navigationType]};
  294. [channel invokeMethod:@"onState" arguments:data];
  295. if (navigationAction.navigationType == WKNavigationTypeBackForward) {
  296. [channel invokeMethod:@"onBackPressed" arguments:nil];
  297. } else if (!isInvalid) {
  298. id data = @{@"url": navigationAction.request.URL.absoluteString};
  299. [channel invokeMethod:@"onUrlChanged" arguments:data];
  300. }
  301. if (_enableAppScheme ||
  302. ([webView.URL.scheme isEqualToString:@"http"] ||
  303. [webView.URL.scheme isEqualToString:@"https"] ||
  304. [webView.URL.scheme isEqualToString:@"about"] ||
  305. [webView.URL.scheme isEqualToString:@"file"])) {
  306. if (isInvalid) {
  307. decisionHandler(WKNavigationActionPolicyCancel);
  308. } else {
  309. decisionHandler(WKNavigationActionPolicyAllow);
  310. }
  311. } else {
  312. decisionHandler(WKNavigationActionPolicyCancel);
  313. }
  314. }
  315. - (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration
  316. forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
  317. if (!navigationAction.targetFrame.isMainFrame) {
  318. [webView loadRequest:navigationAction.request];
  319. }
  320. return nil;
  321. }
  322. - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
  323. [channel invokeMethod:@"onState" arguments:@{@"type": @"startLoad", @"url": webView.URL.absoluteString}];
  324. }
  325. - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
  326. NSString* url = webView.URL == nil ? @"?" : webView.URL.absoluteString;
  327. [channel invokeMethod:@"onHttpError" arguments:@{@"code": [NSString stringWithFormat:@"%ld", error.code], @"url": url}];
  328. }
  329. - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
  330. [channel invokeMethod:@"onState" arguments:@{@"type": @"finishLoad", @"url": webView.URL.absoluteString}];
  331. }
  332. - (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
  333. [channel invokeMethod:@"onHttpError" arguments:@{@"code": [NSString stringWithFormat:@"%ld", error.code], @"error": error.localizedDescription}];
  334. }
  335. - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
  336. if ([navigationResponse.response isKindOfClass:[NSHTTPURLResponse class]]) {
  337. NSHTTPURLResponse * response = (NSHTTPURLResponse *)navigationResponse.response;
  338. if (response.statusCode >= 400) {
  339. [channel invokeMethod:@"onHttpError" arguments:@{@"code": [NSString stringWithFormat:@"%ld", response.statusCode], @"url": webView.URL.absoluteString}];
  340. }
  341. }
  342. decisionHandler(WKNavigationResponsePolicyAllow);
  343. }
  344. - (void)registerJavaScriptChannels:(NSSet*)channelNames
  345. controller:(WKUserContentController*)userContentController {
  346. for (NSString* channelName in channelNames) {
  347. FLTJavaScriptChannel* _channel =
  348. [[FLTJavaScriptChannel alloc] initWithMethodChannel: channel
  349. javaScriptChannelName:channelName];
  350. [userContentController addScriptMessageHandler:_channel name:channelName];
  351. NSString* wrapperSource = [NSString
  352. stringWithFormat:@"window.%@ = webkit.messageHandlers.%@;", channelName, channelName];
  353. WKUserScript* wrapperScript =
  354. [[WKUserScript alloc] initWithSource:wrapperSource
  355. injectionTime:WKUserScriptInjectionTimeAtDocumentStart
  356. forMainFrameOnly:NO];
  357. [userContentController addUserScript:wrapperScript];
  358. }
  359. }
  360. #pragma mark -- UIScrollViewDelegate
  361. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
  362. if (scrollView.pinchGestureRecognizer.isEnabled != _enableZoom) {
  363. scrollView.pinchGestureRecognizer.enabled = _enableZoom;
  364. }
  365. }
  366. @end