base.dart 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. import 'dart:async';
  2. import 'dart:ui';
  3. import 'package:flutter/material.dart';
  4. import 'package:flutter/services.dart';
  5. const _kChannel = 'flutter_webview_plugin';
  6. // TODO: more general state for iOS/android
  7. enum WebViewState { shouldStart, startLoad, finishLoad, abortLoad }
  8. // TODO: use an id by webview to be able to manage multiple webview
  9. /// Singleton class that communicate with a Webview Instance
  10. class FlutterWebviewPlugin {
  11. factory FlutterWebviewPlugin() => _instance ??= FlutterWebviewPlugin._();
  12. FlutterWebviewPlugin._() {
  13. _channel.setMethodCallHandler(_handleMessages);
  14. }
  15. static FlutterWebviewPlugin _instance;
  16. final _channel = const MethodChannel(_kChannel);
  17. final _onBack = StreamController<Null>.broadcast();
  18. final _onDestroy = StreamController<Null>.broadcast();
  19. final _onUrlChanged = StreamController<String>.broadcast();
  20. final _onStateChanged = StreamController<WebViewStateChanged>.broadcast();
  21. final _onScrollXChanged = StreamController<double>.broadcast();
  22. final _onScrollYChanged = StreamController<double>.broadcast();
  23. final _onProgressChanged = new StreamController<double>.broadcast();
  24. final _onHttpError = StreamController<WebViewHttpError>.broadcast();
  25. Future<Null> _handleMessages(MethodCall call) async {
  26. switch (call.method) {
  27. case 'onBack':
  28. _onBack.add(null);
  29. break;
  30. case 'onDestroy':
  31. _onDestroy.add(null);
  32. break;
  33. case 'onUrlChanged':
  34. _onUrlChanged.add(call.arguments['url']);
  35. break;
  36. case 'onScrollXChanged':
  37. _onScrollXChanged.add(call.arguments['xDirection']);
  38. break;
  39. case 'onScrollYChanged':
  40. _onScrollYChanged.add(call.arguments['yDirection']);
  41. break;
  42. case "onProgressChanged":
  43. _onProgressChanged.add(call.arguments["progress"]);
  44. break;
  45. case 'onState':
  46. _onStateChanged.add(
  47. WebViewStateChanged.fromMap(
  48. Map<String, dynamic>.from(call.arguments),
  49. ),
  50. );
  51. break;
  52. case 'onHttpError':
  53. _onHttpError.add(WebViewHttpError(call.arguments['code'], call.arguments['url']));
  54. break;
  55. }
  56. }
  57. /// Listening the OnDestroy LifeCycle Event for Android
  58. Stream<Null> get onDestroy => _onDestroy.stream;
  59. /// Listening the back key press Event for Android
  60. Stream<Null> get onBack => _onBack.stream;
  61. /// Listening url changed
  62. Stream<String> get onUrlChanged => _onUrlChanged.stream;
  63. /// Listening the onState Event for iOS WebView and Android
  64. /// content is Map for type: {shouldStart(iOS)|startLoad|finishLoad}
  65. /// more detail than other events
  66. Stream<WebViewStateChanged> get onStateChanged => _onStateChanged.stream;
  67. /// Listening web view loading progress estimation, value between 0.0 and 1.0
  68. Stream<double> get onProgressChanged => _onProgressChanged.stream;
  69. /// Listening web view y position scroll change
  70. Stream<double> get onScrollYChanged => _onScrollYChanged.stream;
  71. /// Listening web view x position scroll change
  72. Stream<double> get onScrollXChanged => _onScrollXChanged.stream;
  73. Stream<WebViewHttpError> get onHttpError => _onHttpError.stream;
  74. /// Start the Webview with [url]
  75. /// - [headers] specify additional HTTP headers
  76. /// - [withJavascript] enable Javascript or not for the Webview
  77. /// - [clearCache] clear the cache of the Webview
  78. /// - [clearCookies] clear all cookies of the Webview
  79. /// - [hidden] not show
  80. /// - [rect]: show in rect, fullscreen if null
  81. /// - [enableAppScheme]: false will enable all schemes, true only for httt/https/about
  82. /// android: Not implemented yet
  83. /// - [userAgent]: set the User-Agent of WebView
  84. /// - [withZoom]: enable zoom on webview
  85. /// - [withLocalStorage] enable localStorage API on Webview
  86. /// Currently Android only.
  87. /// It is always enabled in UIWebView of iOS and can not be disabled.
  88. /// - [withLocalUrl]: allow url as a local path
  89. /// Allow local files on iOs > 9.0
  90. /// - [scrollBar]: enable or disable scrollbar
  91. /// - [supportMultipleWindows] enable multiple windows support in Android
  92. /// - [invalidUrlRegex] is the regular expression of URLs that web view shouldn't load.
  93. /// For example, when webview is redirected to a specific URL, you want to intercept
  94. /// this process by stopping loading this URL and replacing webview by another screen.
  95. /// Android only settings:
  96. /// - [displayZoomControls]: display zoom controls on webview
  97. /// - [withOverviewMode]: enable overview mode for Android webview ( setLoadWithOverviewMode )
  98. /// - [useWideViewPort]: use wide viewport for Android webview ( setUseWideViewPort )
  99. Future<Null> launch(String url, {
  100. Map<String, String> headers,
  101. bool withJavascript,
  102. bool clearCache,
  103. bool clearCookies,
  104. bool hidden,
  105. bool enableAppScheme,
  106. Rect rect,
  107. String userAgent,
  108. bool withZoom,
  109. bool displayZoomControls,
  110. bool withLocalStorage,
  111. bool withLocalUrl,
  112. bool withOverviewMode,
  113. bool scrollBar,
  114. bool supportMultipleWindows,
  115. bool appCacheEnabled,
  116. bool allowFileURLs,
  117. bool useWideViewPort,
  118. String invalidUrlRegex,
  119. bool geolocationEnabled,
  120. bool debuggingEnabled,
  121. }) async {
  122. final args = <String, dynamic>{
  123. 'url': url,
  124. 'withJavascript': withJavascript ?? true,
  125. 'clearCache': clearCache ?? false,
  126. 'hidden': hidden ?? false,
  127. 'clearCookies': clearCookies ?? false,
  128. 'enableAppScheme': enableAppScheme ?? true,
  129. 'userAgent': userAgent,
  130. 'withZoom': withZoom ?? false,
  131. 'displayZoomControls': displayZoomControls ?? false,
  132. 'withLocalStorage': withLocalStorage ?? true,
  133. 'withLocalUrl': withLocalUrl ?? false,
  134. 'scrollBar': scrollBar ?? true,
  135. 'supportMultipleWindows': supportMultipleWindows ?? false,
  136. 'appCacheEnabled': appCacheEnabled ?? false,
  137. 'allowFileURLs': allowFileURLs ?? false,
  138. 'useWideViewPort': useWideViewPort ?? false,
  139. 'invalidUrlRegex': invalidUrlRegex,
  140. 'geolocationEnabled': geolocationEnabled ?? false,
  141. 'withOverviewMode': withOverviewMode ?? false,
  142. 'debuggingEnabled': debuggingEnabled ?? false,
  143. };
  144. if (headers != null) {
  145. args['headers'] = headers;
  146. }
  147. if (rect != null) {
  148. args['rect'] = {
  149. 'left': rect.left,
  150. 'top': rect.top,
  151. 'width': rect.width,
  152. 'height': rect.height,
  153. };
  154. }
  155. await _channel.invokeMethod('launch', args);
  156. }
  157. /// Execute Javascript inside webview
  158. Future<String> evalJavascript(String code) async {
  159. final res = await _channel.invokeMethod('eval', {'code': code});
  160. return res;
  161. }
  162. /// Close the Webview
  163. /// Will trigger the [onDestroy] event
  164. Future<Null> close() async => await _channel.invokeMethod('close');
  165. /// Reloads the WebView.
  166. Future<Null> reload() async => await _channel.invokeMethod('reload');
  167. /// Navigates back on the Webview.
  168. Future<Null> goBack() async => await _channel.invokeMethod('back');
  169. /// Navigates forward on the Webview.
  170. Future<Null> goForward() async => await _channel.invokeMethod('forward');
  171. // Hides the webview
  172. Future<Null> hide() async => await _channel.invokeMethod('hide');
  173. // Shows the webview
  174. Future<Null> show() async => await _channel.invokeMethod('show');
  175. // Reload webview with a url
  176. Future<Null> reloadUrl(String url) async {
  177. final args = <String, String>{'url': url};
  178. await _channel.invokeMethod('reloadUrl', args);
  179. }
  180. // Clean cookies on WebView
  181. Future<Null> cleanCookies() async => await _channel.invokeMethod('cleanCookies');
  182. // Stops current loading process
  183. Future<Null> stopLoading() async => await _channel.invokeMethod('stopLoading');
  184. /// Close all Streams
  185. void dispose() {
  186. _onDestroy.close();
  187. _onUrlChanged.close();
  188. _onStateChanged.close();
  189. _onProgressChanged.close();
  190. _onScrollXChanged.close();
  191. _onScrollYChanged.close();
  192. _onHttpError.close();
  193. _instance = null;
  194. }
  195. Future<Map<String, String>> getCookies() async {
  196. final cookiesString = await evalJavascript('document.cookie');
  197. final cookies = <String, String>{};
  198. if (cookiesString?.isNotEmpty == true) {
  199. cookiesString.split(';').forEach((String cookie) {
  200. final split = cookie.split('=');
  201. cookies[split[0]] = split[1];
  202. });
  203. }
  204. return cookies;
  205. }
  206. /// resize webview
  207. Future<Null> resize(Rect rect) async {
  208. final args = {};
  209. args['rect'] = {
  210. 'left': rect.left,
  211. 'top': rect.top,
  212. 'width': rect.width,
  213. 'height': rect.height,
  214. };
  215. await _channel.invokeMethod('resize', args);
  216. }
  217. }
  218. class WebViewStateChanged {
  219. WebViewStateChanged(this.type, this.url, this.navigationType);
  220. factory WebViewStateChanged.fromMap(Map<String, dynamic> map) {
  221. WebViewState t;
  222. switch (map['type']) {
  223. case 'shouldStart':
  224. t = WebViewState.shouldStart;
  225. break;
  226. case 'startLoad':
  227. t = WebViewState.startLoad;
  228. break;
  229. case 'finishLoad':
  230. t = WebViewState.finishLoad;
  231. break;
  232. case 'abortLoad':
  233. t = WebViewState.abortLoad;
  234. break;
  235. }
  236. return WebViewStateChanged(t, map['url'], map['navigationType']);
  237. }
  238. final WebViewState type;
  239. final String url;
  240. final int navigationType;
  241. }
  242. class WebViewHttpError {
  243. WebViewHttpError(this.code, this.url);
  244. final String url;
  245. final String code;
  246. }