base.dart 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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 }
  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 _onDestroy = StreamController<Null>.broadcast();
  18. final _onUrlChanged = StreamController<String>.broadcast();
  19. final _onStateChanged = StreamController<WebViewStateChanged>.broadcast();
  20. final _onScrollXChanged = StreamController<double>.broadcast();
  21. final _onScrollYChanged = StreamController<double>.broadcast();
  22. final _onHttpError = StreamController<WebViewHttpError>.broadcast();
  23. Future<Null> _handleMessages(MethodCall call) async {
  24. switch (call.method) {
  25. case 'onDestroy':
  26. _onDestroy.add(null);
  27. break;
  28. case 'onUrlChanged':
  29. _onUrlChanged.add(call.arguments['url']);
  30. break;
  31. case 'onScrollXChanged':
  32. _onScrollXChanged.add(call.arguments['xDirection']);
  33. break;
  34. case 'onScrollYChanged':
  35. _onScrollYChanged.add(call.arguments['yDirection']);
  36. break;
  37. case 'onState':
  38. _onStateChanged.add(
  39. WebViewStateChanged.fromMap(
  40. Map<String, dynamic>.from(call.arguments),
  41. ),
  42. );
  43. break;
  44. case 'onHttpError':
  45. _onHttpError.add(WebViewHttpError(call.arguments['code'], call.arguments['url']));
  46. break;
  47. }
  48. }
  49. /// Listening the OnDestroy LifeCycle Event for Android
  50. Stream<Null> get onDestroy => _onDestroy.stream;
  51. /// Listening url changed
  52. Stream<String> get onUrlChanged => _onUrlChanged.stream;
  53. /// Listening the onState Event for iOS WebView and Android
  54. /// content is Map for type: {shouldStart(iOS)|startLoad|finishLoad}
  55. /// more detail than other events
  56. Stream<WebViewStateChanged> get onStateChanged => _onStateChanged.stream;
  57. /// Listening web view y position scroll change
  58. Stream<double> get onScrollYChanged => _onScrollYChanged.stream;
  59. /// Listening web view x position scroll change
  60. Stream<double> get onScrollXChanged => _onScrollXChanged.stream;
  61. Stream<WebViewHttpError> get onHttpError => _onHttpError.stream;
  62. /// Start the Webview with [url]
  63. /// - [headers] specify additional HTTP headers
  64. /// - [withJavascript] enable Javascript or not for the Webview
  65. /// iOS WebView: Not implemented yet
  66. /// - [clearCache] clear the cache of the Webview
  67. /// - [clearCookies] clear all cookies of the Webview
  68. /// - [hidden] not show
  69. /// - [rect]: show in rect, fullscreen if null
  70. /// - [enableAppScheme]: false will enable all schemes, true only for httt/https/about
  71. /// android: Not implemented yet
  72. /// - [userAgent]: set the User-Agent of WebView
  73. /// - [withZoom]: enable zoom on webview
  74. /// - [withLocalStorage] enable localStorage API on Webview
  75. /// Currently Android only.
  76. /// It is always enabled in UIWebView of iOS and can not be disabled.
  77. /// - [withLocalUrl]: allow url as a local path
  78. /// Allow local files on iOs > 9.0
  79. /// - [scrollBar]: enable or disable scrollbar
  80. Future<Null> launch(String url, {
  81. Map<String, String> headers,
  82. bool withJavascript,
  83. bool clearCache,
  84. bool clearCookies,
  85. bool hidden,
  86. bool enableAppScheme,
  87. Rect rect,
  88. String userAgent,
  89. bool withZoom,
  90. bool withLocalStorage,
  91. bool withLocalUrl,
  92. bool scrollBar,
  93. bool supportMultipleWindows,
  94. bool appCacheEnabled,
  95. bool allowFileURLs,
  96. bool geolocationEnabled,
  97. }) async {
  98. final args = <String, dynamic>{
  99. 'url': url,
  100. 'withJavascript': withJavascript ?? true,
  101. 'clearCache': clearCache ?? false,
  102. 'hidden': hidden ?? false,
  103. 'clearCookies': clearCookies ?? false,
  104. 'enableAppScheme': enableAppScheme ?? true,
  105. 'userAgent': userAgent,
  106. 'withZoom': withZoom ?? false,
  107. 'withLocalStorage': withLocalStorage ?? true,
  108. 'withLocalUrl': withLocalUrl ?? false,
  109. 'scrollBar': scrollBar ?? true,
  110. 'supportMultipleWindows': supportMultipleWindows ?? false,
  111. 'appCacheEnabled': appCacheEnabled ?? false,
  112. 'allowFileURLs': allowFileURLs ?? false,
  113. 'geolocationEnabled': geolocationEnabled ?? false,
  114. };
  115. if (headers != null) {
  116. args['headers'] = headers;
  117. }
  118. if (rect != null) {
  119. args['rect'] = {
  120. 'left': rect.left,
  121. 'top': rect.top,
  122. 'width': rect.width,
  123. 'height': rect.height,
  124. };
  125. }
  126. await _channel.invokeMethod('launch', args);
  127. }
  128. /// Execute Javascript inside webview
  129. Future<String> evalJavascript(String code) async {
  130. final res = await _channel.invokeMethod('eval', {'code': code});
  131. return res;
  132. }
  133. /// Close the Webview
  134. /// Will trigger the [onDestroy] event
  135. Future<Null> close() async => await _channel.invokeMethod('close');
  136. /// Reloads the WebView.
  137. Future<Null> reload() async => await _channel.invokeMethod('reload');
  138. /// Navigates back on the Webview.
  139. Future<Null> goBack() async => await _channel.invokeMethod('back');
  140. /// Navigates forward on the Webview.
  141. Future<Null> goForward() async => await _channel.invokeMethod('forward');
  142. // Hides the webview
  143. Future<Null> hide() async => await _channel.invokeMethod('hide');
  144. // Shows the webview
  145. Future<Null> show() async => await _channel.invokeMethod('show');
  146. // Reload webview with a url
  147. Future<Null> reloadUrl(String url) async {
  148. final args = <String, String>{'url': url};
  149. await _channel.invokeMethod('reloadUrl', args);
  150. }
  151. // Clean cookies on WebView
  152. Future<Null> cleanCookies() async => await _channel.invokeMethod('cleanCookies');
  153. // Stops current loading process
  154. Future<Null> stopLoading() async => await _channel.invokeMethod('stopLoading');
  155. /// Close all Streams
  156. void dispose() {
  157. _onDestroy.close();
  158. _onUrlChanged.close();
  159. _onStateChanged.close();
  160. _onScrollXChanged.close();
  161. _onScrollYChanged.close();
  162. _onHttpError.close();
  163. _instance = null;
  164. }
  165. Future<Map<String, String>> getCookies() async {
  166. final cookiesString = await evalJavascript('document.cookie');
  167. final cookies = <String, String>{};
  168. if (cookiesString?.isNotEmpty == true) {
  169. cookiesString.split(';').forEach((String cookie) {
  170. final split = cookie.split('=');
  171. cookies[split[0]] = split[1];
  172. });
  173. }
  174. return cookies;
  175. }
  176. /// resize webview
  177. Future<Null> resize(Rect rect) async {
  178. final args = {};
  179. args['rect'] = {
  180. 'left': rect.left,
  181. 'top': rect.top,
  182. 'width': rect.width,
  183. 'height': rect.height,
  184. };
  185. await _channel.invokeMethod('resize', args);
  186. }
  187. }
  188. class WebViewStateChanged {
  189. WebViewStateChanged(this.type, this.url, this.navigationType);
  190. factory WebViewStateChanged.fromMap(Map<String, dynamic> map) {
  191. WebViewState t;
  192. switch (map['type']) {
  193. case 'shouldStart':
  194. t = WebViewState.shouldStart;
  195. break;
  196. case 'startLoad':
  197. t = WebViewState.startLoad;
  198. break;
  199. case 'finishLoad':
  200. t = WebViewState.finishLoad;
  201. break;
  202. }
  203. return WebViewStateChanged(t, map['url'], map['navigationType']);
  204. }
  205. final WebViewState type;
  206. final String url;
  207. final int navigationType;
  208. }
  209. class WebViewHttpError {
  210. WebViewHttpError(this.code, this.url);
  211. final String url;
  212. final String code;
  213. }