flutter_inappbrowser.dart 32.5 KB
Newer Older
pichillilorenzo's avatar
pichillilorenzo committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

pichillilorenzo's avatar
pichillilorenzo committed
22
import 'dart:io';
pichillilorenzo's avatar
pichillilorenzo committed
23
import 'dart:async';
24
import 'dart:collection';
25
import 'dart:typed_data';
26
import 'dart:convert';
pichillilorenzo's avatar
pichillilorenzo committed
27 28

import 'package:flutter/services.dart';
29
import 'package:uuid/uuid.dart';
pichillilorenzo's avatar
pichillilorenzo committed
30
import 'package:mime/mime.dart';
31 32

typedef Future<dynamic> ListenerCallback(MethodCall call);
33
typedef Future<void> JavaScriptHandlerCallback(List<dynamic> arguments);
34

35 36 37 38 39 40 41
var _uuidGenerator = new Uuid();

///
enum ConsoleMessageLevel {
  DEBUG, ERROR, LOG, TIP, WARNING
}

42 43
///Public class representing a resource request of the [InAppBrowser] WebView.
///It is used by the method [InAppBrowser.onLoadResource()].
44 45 46 47 48 49 50 51 52 53
class WebResourceRequest {

  String url;
  Map<String, String> headers;
  String method;

  WebResourceRequest(this.url, this.headers, this.method);

}

54 55
///Public class representing a resource response of the [InAppBrowser] WebView.
///It is used by the method [InAppBrowser.onLoadResource()].
56 57 58 59 60
class WebResourceResponse {

  String url;
  Map<String, String> headers;
  int statusCode;
61 62
  int startTime;
  int duration;
63 64
  Uint8List data;

65
  WebResourceResponse(this.url, this.headers, this.statusCode, this.startTime, this.duration, this.data);
66 67 68

}

69 70 71 72 73 74 75 76 77 78 79 80 81
///Public class representing a JavaScript console message from WebCore.
///This could be a issued by a call to one of the console logging functions (e.g. console.log('...')) or a JavaScript error on the page.
///
///To receive notifications of these messages, override the [InAppBrowser.onConsoleMessage()] function.
class ConsoleMessage {

  String sourceURL = "";
  int lineNumber = 1;
  String message = "";
  ConsoleMessageLevel messageLevel = ConsoleMessageLevel.LOG;

  ConsoleMessage(this.sourceURL, this.lineNumber, this.message, this.messageLevel);
}
pichillilorenzo's avatar
pichillilorenzo committed
82

83 84 85
class _ChannelManager {
  static const MethodChannel channel = const MethodChannel('com.pichillilorenzo/flutter_inappbrowser');
  static final initialized = false;
86
  static final listeners = HashMap<String, ListenerCallback>();
87 88

  static Future<dynamic> _handleMethod(MethodCall call) async {
89
    String uuid = call.arguments["uuid"];
pichillilorenzo's avatar
pichillilorenzo committed
90
    return await listeners[uuid](call);
91 92
  }

93
  static void addListener (String key, ListenerCallback callback) {
94 95
    if (!initialized)
      init();
96
    listeners.putIfAbsent(key, () => callback);
97 98 99 100 101 102 103 104 105
  }

  static void init () {
    channel.setMethodCallHandler(_handleMethod);
  }
}

///InAppBrowser class.
///
106
///This class uses the native WebView of the platform.
pichillilorenzo's avatar
pichillilorenzo committed
107 108
class InAppBrowser {

109
  String uuid;
110
  Map<String, List<JavaScriptHandlerCallback>> javaScriptHandlersMap = HashMap<String, List<JavaScriptHandlerCallback>>();
pichillilorenzo's avatar
pichillilorenzo committed
111 112
  HttpServer _server;
  bool _isOpened = false;
113

pichillilorenzo's avatar
pichillilorenzo committed
114 115
  ///
  InAppBrowser () {
116
    uuid = _uuidGenerator.v4();
117
    _ChannelManager.addListener(uuid, _handleMethod);
pichillilorenzo's avatar
pichillilorenzo committed
118
    _isOpened = false;
pichillilorenzo's avatar
pichillilorenzo committed
119 120 121 122
  }

  Future<dynamic> _handleMethod(MethodCall call) async {
    switch(call.method) {
123
      case "onLoadStart":
pichillilorenzo's avatar
pichillilorenzo committed
124 125 126
        String url = call.arguments["url"];
        onLoadStart(url);
        break;
127
      case "onLoadStop":
pichillilorenzo's avatar
pichillilorenzo committed
128 129 130
        String url = call.arguments["url"];
        onLoadStop(url);
        break;
131
      case "onLoadError":
pichillilorenzo's avatar
pichillilorenzo committed
132
        String url = call.arguments["url"];
133
        int code = call.arguments["code"];
pichillilorenzo's avatar
pichillilorenzo committed
134 135 136
        String message = call.arguments["message"];
        onLoadError(url, code, message);
        break;
137
      case "onExit":
pichillilorenzo's avatar
pichillilorenzo committed
138 139
        this._closeServer();
        this._isOpened = false;
pichillilorenzo's avatar
pichillilorenzo committed
140 141
        onExit();
        break;
142 143 144 145
      case "shouldOverrideUrlLoading":
        String url = call.arguments["url"];
        shouldOverrideUrlLoading(url);
        break;
146
      case "onLoadResource":
147 148 149 150 151 152 153 154 155
        Map<dynamic, dynamic> rawResponse = call.arguments["response"];
        rawResponse = rawResponse.cast<String, dynamic>();
        Map<dynamic, dynamic> rawRequest = call.arguments["request"];
        rawRequest = rawRequest.cast<String, dynamic>();

        String urlResponse = rawResponse["url"];
        Map<dynamic, dynamic> headersResponse = rawResponse["headers"];
        headersResponse = headersResponse.cast<String, String>();
        int statusCode = rawResponse["statusCode"];
156 157
        int startTime = rawResponse["startTime"];
        int duration = rawResponse["duration"];
158 159 160 161 162 163 164
        Uint8List data = rawResponse["data"];

        String urlRequest = rawRequest["url"];
        Map<dynamic, dynamic> headersRequest = rawRequest["headers"];
        headersRequest = headersResponse.cast<String, String>();
        String method = rawRequest["method"];

165
        var response = new WebResourceResponse(urlResponse, headersResponse, statusCode, startTime, duration, data);
166 167 168
        var request = new WebResourceRequest(urlRequest, headersRequest, method);

        onLoadResource(response, request);
169
        break;
170 171 172 173 174 175 176 177 178 179 180 181 182
      case "onConsoleMessage":
        String sourceURL = call.arguments["sourceURL"];
        int lineNumber = call.arguments["lineNumber"];
        String message = call.arguments["message"];
        ConsoleMessageLevel messageLevel;
        ConsoleMessageLevel.values.forEach((element) {
          if ("ConsoleMessageLevel." + call.arguments["messageLevel"] == element.toString()) {
            messageLevel = element;
            return;
          }
        });
        onConsoleMessage(ConsoleMessage(sourceURL, lineNumber, message, messageLevel));
        break;
183 184 185 186 187 188 189 190 191
      case "onCallJsHandler":
        String handlerName = call.arguments["handlerName"];
        List<dynamic> args = jsonDecode(call.arguments["args"]);
        if (javaScriptHandlersMap.containsKey(handlerName)) {
          for (var handler in javaScriptHandlersMap[handlerName]) {
            handler(args);
          }
        }
        break;
pichillilorenzo's avatar
pichillilorenzo committed
192 193
      default:
        throw UnimplementedError("Unimplemented ${call.method} method");
pichillilorenzo's avatar
pichillilorenzo committed
194 195 196
    }
  }

pichillilorenzo's avatar
pichillilorenzo committed
197 198 199
  ///Opens an [url] in a new [InAppBrowser] instance or in the system browser (`openWithSystemBrowser: true`).
  ///
  ///**NOTE**: If you open the given [url] with the system browser (`openWithSystemBrowser: true`), you wont be able to use the [InAppBrowser] methods!
pichillilorenzo's avatar
pichillilorenzo committed
200
  ///
201
  ///- [url]: The [url] to load. Call [encodeUriComponent()] on this if the [url] contains Unicode characters. The default value is `about:blank`.
pichillilorenzo's avatar
pichillilorenzo committed
202
  ///
203
  ///- [headers]: The additional headers to be used in the HTTP request for this URL, specified as a map from name to value.
pichillilorenzo's avatar
pichillilorenzo committed
204
  ///
205
  ///- [options]: Options for the [InAppBrowser].
pichillilorenzo's avatar
pichillilorenzo committed
206
  ///
pichillilorenzo's avatar
pichillilorenzo committed
207 208 209 210 211 212 213 214 215 216 217 218 219 220
  ///  - All platforms support:
  ///    - __useShouldOverrideUrlLoading__: Set to `true` to be able to listen at the [shouldOverrideUrlLoading()] event. The default value is `false`.
  ///    - __useOnLoadResource__: Set to `true` to be able to listen at the [onLoadResource()] event. The default value is `false`.
  ///    - __openWithSystemBrowser__: Set to `true` to open the given `url` with the system browser. The default value is `false`.
  ///    - __isLocalFile__: Set to `true` if the [url] is pointing to a local file (the file must be addded in the `assets` section of your `pubspec.yaml`. See [loadFile()] explanation). The default value is `false`.
  ///    - __clearCache__: Set to `true` to have all the browser's cache cleared before the new window is opened. The default value is `false`.
  ///    - __userAgent___: Set the custom WebView's user-agent.
  ///    - __javaScriptEnabled__: Set to `true` to enable JavaScript. The default value is `true`.
  ///    - __javaScriptCanOpenWindowsAutomatically__: Set to `true` to allow JavaScript open windows without user interaction. The default value is `false`.
  ///    - __hidden__: Set to `true` to create the browser and load the page, but not show it. The `onLoadStop` event fires when loading is complete. Omit or set to `false` (default) to have the browser open and load normally.
  ///    - __toolbarTop__: Set to `false` to hide the toolbar at the top of the WebView. The default value is `true`.
  ///    - __toolbarTopBackgroundColor__: Set the custom background color of the toolbat at the top.
  ///    - __hideUrlBar__: Set to `true` to hide the url bar on the toolbar at the top. The default value is `false`.
  ///    - __mediaPlaybackRequiresUserGesture__: Set to `true` to prevent HTML5 audio or video from autoplaying. The default value is `true`.
pichillilorenzo's avatar
pichillilorenzo committed
221
  ///
pichillilorenzo's avatar
pichillilorenzo committed
222
  ///  - **Android** supports these additional options:
pichillilorenzo's avatar
pichillilorenzo committed
223
  ///
pichillilorenzo's avatar
pichillilorenzo committed
224 225 226 227 228 229 230 231 232 233
  ///    - __hideTitleBar__: Set to `true` if you want the title should be displayed. The default value is `false`.
  ///    - __closeOnCannotGoBack__: Set to `false` to not close the InAppBrowser when the user click on the back button and the WebView cannot go back to the history. The default value is `true`.
  ///    - __clearSessionCache__: Set to `true` to have the session cookie cache cleared before the new window is opened.
  ///    - __builtInZoomControls__: Set to `true` if the WebView should use its built-in zoom mechanisms. The default value is `false`.
  ///    - __supportZoom__: Set to `false` if the WebView should not support zooming using its on-screen zoom controls and gestures. The default value is `true`.
  ///    - __databaseEnabled__: Set to `true` if you want the database storage API is enabled. The default value is `false`.
  ///    - __domStorageEnabled__: Set to `true` if you want the DOM storage API is enabled. The default value is `false`.
  ///    - __useWideViewPort__: Set to `true` if the WebView should enable support for the "viewport" HTML meta tag or should use a wide viewport. When the value of the setting is false, the layout width is always set to the width of the WebView control in device-independent (CSS) pixels. When the value is true and the page contains the viewport meta tag, the value of the width specified in the tag is used. If the page does not contain the tag or does not provide a width, then a wide viewport will be used. The default value is `true`.
  ///    - __safeBrowsingEnabled__: Set to `true` if you want the Safe Browsing is enabled. Safe Browsing allows WebView to protect against malware and phishing attacks by verifying the links. The default value is `true`.
  ///    - __progressBar__: Set to `false` to hide the progress bar at the bottom of the toolbar at the top. The default value is `true`.
pichillilorenzo's avatar
pichillilorenzo committed
234
  ///
pichillilorenzo's avatar
pichillilorenzo committed
235
  ///  - **iOS** supports these additional options:
pichillilorenzo's avatar
pichillilorenzo committed
236
  ///
pichillilorenzo's avatar
pichillilorenzo committed
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
  ///    - __disallowOverScroll__: Set to `true` to disable the bouncing of the WebView when the scrolling has reached an edge of the content. The default value is `false`.
  ///    - __toolbarBottom__: Set to `false` to hide the toolbar at the bottom of the WebView. The default value is `true`.
  ///    - __toolbarBottomBackgroundColor__: Set the custom background color of the toolbat at the bottom.
  ///    - __toolbarBottomTranslucent__: Set to `true` to set the toolbar at the bottom translucent. The default value is `true`.
  ///    - __closeButtonCaption__: Set the custom text for the close button.
  ///    - __closeButtonColor__: Set the custom color for the close button.
  ///    - __presentationStyle__: Set the custom modal presentation style when presenting the WebView. The default value is `0 //fullscreen`. See [UIModalPresentationStyle](https://developer.apple.com/documentation/uikit/uimodalpresentationstyle) for all the available styles.
  ///    - __transitionStyle__: Set to the custom transition style when presenting the WebView. The default value is `0 //crossDissolve`. See [UIModalTransitionStyle](https://developer.apple.com/documentation/uikit/uimodaltransitionStyle) for all the available styles.
  ///    - __enableViewportScale__: Set to `true` to allow a viewport meta tag to either disable or restrict the range of user scaling. The default value is `false`.
  ///    - __suppressesIncrementalRendering__: Set to `true` if you want the WebView suppresses content rendering until it is fully loaded into memory.. The default value is `false`.
  ///    - __allowsAirPlayForMediaPlayback__: Set to `true` to allow AirPlay. The default value is `true`.
  ///    - __allowsBackForwardNavigationGestures__: Set to `true` to allow the horizontal swipe gestures trigger back-forward list navigations. The default value is `true`.
  ///    - __allowsLinkPreview__: Set to `true` to allow that pressing on a link displays a preview of the destination for the link. The default value is `true`.
  ///    - __ignoresViewportScaleLimits__: Set to `true` if you want that the WebView should always allow scaling of the webpage, regardless of the author's intent. The ignoresViewportScaleLimits property overrides the `user-scalable` HTML property in a webpage. The default value is `false`.
  ///    - __allowsInlineMediaPlayback__: Set to `true` to allow HTML5 media playback to appear inline within the screen layout, using browser-supplied controls rather than native controls. For this to work, add the `webkit-playsinline` attribute to any `<video>` elements. The default value is `false`.
  ///    - __allowsPictureInPictureMediaPlayback__: Set to `true` to allow HTML5 videos play picture-in-picture. The default value is `true`.
  ///    - __spinner__: Set to `false` to hide the spinner when the WebView is loading a page. The default value is `true`.
  Future<void> open({String url = "about:blank", Map<String, String> headers = const {}, Map<String, dynamic> options = const {}}) async {
    this._throwIsAlreadyOpened(message: 'Cannot open $url!');
pichillilorenzo's avatar
pichillilorenzo committed
256
    Map<String, dynamic> args = <String, dynamic>{};
257
    args.putIfAbsent('uuid', () => uuid);
pichillilorenzo's avatar
pichillilorenzo committed
258
    args.putIfAbsent('url', () => url);
259
    args.putIfAbsent('headers', () => headers);
pichillilorenzo's avatar
pichillilorenzo committed
260
    args.putIfAbsent('options', () => options);
261
    args.putIfAbsent('useChromeSafariBrowser', () => false);
pichillilorenzo's avatar
pichillilorenzo committed
262 263 264 265 266 267 268 269 270 271 272 273 274
    await _ChannelManager.channel.invokeMethod('open', args);
    this._isOpened = true;
  }

  ///This is a static method that opens an [url] in the system browser.
  ///This has the same behaviour of an [InAppBrowser] instance calling the [open()] method with option `openWithSystemBrowser: true`.
  static Future<void> openWithSystemBrowser(String url) async {
    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent('uuid', () => "");
    args.putIfAbsent('url', () => url);
    args.putIfAbsent('headers', () => {});
    args.putIfAbsent('options', () => {"openWithSystemBrowser": true});
    args.putIfAbsent('useChromeSafariBrowser', () => false);
275
    return await _ChannelManager.channel.invokeMethod('open', args);
pichillilorenzo's avatar
pichillilorenzo committed
276 277
  }

pichillilorenzo's avatar
pichillilorenzo committed
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
  Future<void> _startServer({int port = 8080}) async {

    this._closeServer();
    var completer = new Completer();

    runZoned(() {
      HttpServer.bind('127.0.0.1', port).then((server) {
        print('Server running at http://127.0.0.1:' + port.toString());

        this._server = server;

        server.listen((HttpRequest request) async {
          var body = List<int>();
          var path = request.requestedUri.path;
          path = (path.startsWith('/')) ? path.substring(1) : path;
          path += (path.endsWith('/')) ? 'index.html' : '';

          try {
            body = (await rootBundle.load(path))
                .buffer.asUint8List();
          } catch (e) {
            print(e.toString());
            request.response.close();
            return;
          }

          var contentType = ['text', 'html'];
          if (!request.requestedUri.path.endsWith('/') && request.requestedUri.pathSegments.isNotEmpty) {
            var mimeType = lookupMimeType(request.requestedUri.path, headerBytes: body);
            if (mimeType != null) {
              contentType = mimeType.split('/');
            }
          }

          request.response.headers.contentType = new ContentType(contentType[0], contentType[1], charset: 'utf-8');
          request.response.add(body);
          request.response.close();
        });

        completer.complete();
      });
    }, onError: (e, stackTrace) => print('Error: $e $stackTrace'));

    return completer.future;
  }

  Future<void> _closeServer() async {
    if (this._server != null) {
      final port = this._server.port;
      await this._server.close(force: true);
      print('Server running at http://127.0.0.1:$port closed');
      this._server = null;
    }
  }

  ///Serve the [assetFilePath] from Flutter assets on http://localhost:[port]/. It is similar to [InAppBrowser.open()] with option `isLocalFile: true`, but it starts a server.
  ///
  ///**NOTE for iOS**: For the iOS Platform, you need to add the `NSAllowsLocalNetworking` key with `true` in the `Info.plist` file (See [ATS Configuration Basics](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW35):
  ///```xml
  ///<key>NSAppTransportSecurity</key>
  ///<dict>
  ///    <key>NSAllowsLocalNetworking</key>
  ///    <true/>
  ///</dict>
  ///```
  ///The `NSAllowsLocalNetworking` key is available since **iOS 10**.
  Future<void> openOnLocalhost(String assetFilePath, {int port = 8080, Map<String, String> headers = const {}, Map<String, dynamic> options = const {}}) async {
    this._throwIsAlreadyOpened(message: 'Cannot open $assetFilePath!');
    await this._startServer(port: port);
    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent('uuid', () => uuid);
    args.putIfAbsent('url', () => 'http://localhost:${this._server.port}/' + assetFilePath);
    args.putIfAbsent('headers', () => headers);
    options["isLocalFile"] = false;
    args.putIfAbsent('options', () => options);
    args.putIfAbsent('useChromeSafariBrowser', () => false);
    await _ChannelManager.channel.invokeMethod('open', args);
    this._isOpened = true;
  }

358
  ///Loads the given [url] with optional [headers] specified as a map from name to value.
359
  Future<void> loadUrl(String url, {Map<String, String> headers = const {}}) async {
pichillilorenzo's avatar
pichillilorenzo committed
360
    this._throwIsNotOpened(message: 'Cannot laod $url!');
361
    Map<String, dynamic> args = <String, dynamic>{};
362
    args.putIfAbsent('uuid', () => uuid);
363 364
    args.putIfAbsent('url', () => url);
    args.putIfAbsent('headers', () => headers);
pichillilorenzo's avatar
pichillilorenzo committed
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
    await _ChannelManager.channel.invokeMethod('loadUrl', args);
  }

  ///Loads the given [assetFilePath] with optional [headers] specified as a map from name to value.
  ///
  ///To be able to load your local files (assets, js, css, etc.), you need to add them in the `assets` section of the `pubspec.yaml` file, otherwise they cannot be found!
  ///
  ///Example of a `pubspec.yaml` file:
  ///```yaml
  ///...
  ///
  ///# The following section is specific to Flutter.
  ///flutter:
  ///
  ///  # The following line ensures that the Material Icons font is
  ///  # included with your application, so that you can use the icons in
  ///  # the material Icons class.
  ///  uses-material-design: true
  ///
  ///  assets:
  ///    - assets/index.html
  ///    - assets/css/
  ///    - assets/images/
  ///
  ///...
  ///```
  ///Example of a `main.dart` file:
  ///```dart
  ///...
  ///inAppBrowser.loadFile("assets/index.html");
  ///...
  ///```
  Future<void> loadFile(String assetFilePath, {Map<String, String> headers = const {}}) async {
    this._throwIsNotOpened(message: 'Cannot laod $assetFilePath!');
    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent('uuid', () => uuid);
    args.putIfAbsent('url', () => assetFilePath);
    args.putIfAbsent('headers', () => headers);
    await _ChannelManager.channel.invokeMethod('loadFile', args);
404 405
  }

pichillilorenzo's avatar
pichillilorenzo committed
406 407
  ///Displays an [InAppBrowser] window that was opened hidden. Calling this has no effect if the [InAppBrowser] was already visible.
  Future<void> show() async {
pichillilorenzo's avatar
pichillilorenzo committed
408
    this._throwIsNotOpened();
409 410
    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent('uuid', () => uuid);
pichillilorenzo's avatar
pichillilorenzo committed
411
    await _ChannelManager.channel.invokeMethod('show', args);
pichillilorenzo's avatar
pichillilorenzo committed
412 413 414 415
  }

  ///Hides the [InAppBrowser] window. Calling this has no effect if the [InAppBrowser] was already hidden.
  Future<void> hide() async {
pichillilorenzo's avatar
pichillilorenzo committed
416
    this._throwIsNotOpened();
417 418
    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent('uuid', () => uuid);
pichillilorenzo's avatar
pichillilorenzo committed
419
    await _ChannelManager.channel.invokeMethod('hide', args);
pichillilorenzo's avatar
pichillilorenzo committed
420 421 422 423
  }

  ///Closes the [InAppBrowser] window.
  Future<void> close() async {
pichillilorenzo's avatar
pichillilorenzo committed
424
    this._throwIsNotOpened();
425 426
    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent('uuid', () => uuid);
pichillilorenzo's avatar
pichillilorenzo committed
427
    await _ChannelManager.channel.invokeMethod('close', args);
pichillilorenzo's avatar
pichillilorenzo committed
428 429
  }

pichillilorenzo's avatar
pichillilorenzo committed
430 431
  ///Reloads the [InAppBrowser] window.
  Future<void> reload() async {
pichillilorenzo's avatar
pichillilorenzo committed
432
    this._throwIsNotOpened();
433 434
    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent('uuid', () => uuid);
pichillilorenzo's avatar
pichillilorenzo committed
435
    await _ChannelManager.channel.invokeMethod('reload', args);
pichillilorenzo's avatar
pichillilorenzo committed
436 437 438 439
  }

  ///Goes back in the history of the [InAppBrowser] window.
  Future<void> goBack() async {
pichillilorenzo's avatar
pichillilorenzo committed
440
    this._throwIsNotOpened();
441 442
    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent('uuid', () => uuid);
pichillilorenzo's avatar
pichillilorenzo committed
443
    await _ChannelManager.channel.invokeMethod('goBack', args);
pichillilorenzo's avatar
pichillilorenzo committed
444 445 446 447
  }

  ///Goes forward in the history of the [InAppBrowser] window.
  Future<void> goForward() async {
pichillilorenzo's avatar
pichillilorenzo committed
448
    this._throwIsNotOpened();
449 450
    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent('uuid', () => uuid);
pichillilorenzo's avatar
pichillilorenzo committed
451
    await _ChannelManager.channel.invokeMethod('goForward', args);
pichillilorenzo's avatar
pichillilorenzo committed
452 453 454 455
  }

  ///Check if the Web View of the [InAppBrowser] instance is in a loading state.
  Future<bool> isLoading() async {
pichillilorenzo's avatar
pichillilorenzo committed
456
    this._throwIsNotOpened();
457 458 459
    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent('uuid', () => uuid);
    return await _ChannelManager.channel.invokeMethod('isLoading', args);
pichillilorenzo's avatar
pichillilorenzo committed
460 461 462 463
  }

  ///Stops the Web View of the [InAppBrowser] instance from loading.
  Future<void> stopLoading() async {
pichillilorenzo's avatar
pichillilorenzo committed
464
    this._throwIsNotOpened();
465 466
    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent('uuid', () => uuid);
pichillilorenzo's avatar
pichillilorenzo committed
467
    await _ChannelManager.channel.invokeMethod('stopLoading', args);
pichillilorenzo's avatar
pichillilorenzo committed
468 469
  }

470 471
  ///Check if the Web View of the [InAppBrowser] instance is hidden.
  Future<bool> isHidden() async {
pichillilorenzo's avatar
pichillilorenzo committed
472
    this._throwIsNotOpened();
473 474 475
    Map<String, dynamic> args = <String, dynamic>{};
    args.putIfAbsent('uuid', () => uuid);
    return await _ChannelManager.channel.invokeMethod('isHidden', args);
476 477
  }

pichillilorenzo's avatar
pichillilorenzo committed
478
  ///Injects JavaScript code into the [InAppBrowser] window and returns the result of the evaluation.
479
  Future<String> injectScriptCode(String source) async {
pichillilorenzo's avatar
pichillilorenzo committed
480
    this._throwIsNotOpened();
pichillilorenzo's avatar
pichillilorenzo committed
481
    Map<String, dynamic> args = <String, dynamic>{};
482
    args.putIfAbsent('uuid', () => uuid);
pichillilorenzo's avatar
pichillilorenzo committed
483
    args.putIfAbsent('source', () => source);
484
    return await _ChannelManager.channel.invokeMethod('injectScriptCode', args);
pichillilorenzo's avatar
pichillilorenzo committed
485 486
  }

pichillilorenzo's avatar
pichillilorenzo committed
487
  ///Injects a JavaScript file into the [InAppBrowser] window.
pichillilorenzo's avatar
pichillilorenzo committed
488
  Future<void> injectScriptFile(String urlFile) async {
pichillilorenzo's avatar
pichillilorenzo committed
489
    this._throwIsNotOpened();
pichillilorenzo's avatar
pichillilorenzo committed
490
    Map<String, dynamic> args = <String, dynamic>{};
491
    args.putIfAbsent('uuid', () => uuid);
pichillilorenzo's avatar
pichillilorenzo committed
492
    args.putIfAbsent('urlFile', () => urlFile);
pichillilorenzo's avatar
pichillilorenzo committed
493
    await _ChannelManager.channel.invokeMethod('injectScriptFile', args);
pichillilorenzo's avatar
pichillilorenzo committed
494 495
  }

pichillilorenzo's avatar
pichillilorenzo committed
496
  ///Injects CSS into the [InAppBrowser] window.
pichillilorenzo's avatar
pichillilorenzo committed
497
  Future<void> injectStyleCode(String source) async {
pichillilorenzo's avatar
pichillilorenzo committed
498
    this._throwIsNotOpened();
pichillilorenzo's avatar
pichillilorenzo committed
499
    Map<String, dynamic> args = <String, dynamic>{};
500
    args.putIfAbsent('uuid', () => uuid);
pichillilorenzo's avatar
pichillilorenzo committed
501
    args.putIfAbsent('source', () => source);
pichillilorenzo's avatar
pichillilorenzo committed
502
    await _ChannelManager.channel.invokeMethod('injectStyleCode', args);
pichillilorenzo's avatar
pichillilorenzo committed
503 504
  }

pichillilorenzo's avatar
pichillilorenzo committed
505
  ///Injects a CSS file into the [InAppBrowser] window.
pichillilorenzo's avatar
pichillilorenzo committed
506
  Future<void> injectStyleFile(String urlFile) async {
pichillilorenzo's avatar
pichillilorenzo committed
507
    this._throwIsNotOpened();
pichillilorenzo's avatar
pichillilorenzo committed
508
    Map<String, dynamic> args = <String, dynamic>{};
509
    args.putIfAbsent('uuid', () => uuid);
pichillilorenzo's avatar
pichillilorenzo committed
510
    args.putIfAbsent('urlFile', () => urlFile);
pichillilorenzo's avatar
pichillilorenzo committed
511
    await _ChannelManager.channel.invokeMethod('injectStyleFile', args);
pichillilorenzo's avatar
pichillilorenzo committed
512 513
  }

514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
  ///Adds/Appends a JavaScript message handler [callback] ([JavaScriptHandlerCallback]) that listen to post messages sent from JavaScript by the handler with name [handlerName].
  ///Returns the position `index` of the handler that can be used to remove it with the [removeJavaScriptHandler()] method.
  ///
  ///The Android implementation uses [addJavascriptInterface](https://developer.android.com/reference/android/webkit/WebView#addJavascriptInterface(java.lang.Object,%20java.lang.String)).
  ///The iOS implementation uses [addScriptMessageHandler](https://developer.apple.com/documentation/webkit/wkusercontentcontroller/1537172-addscriptmessagehandler?language=objc)
  ///
  ///The JavaScript function that can be used to call the handler is `window.flutter_inappbrowser.callHandler(handlerName <String>, ...args);`, where `args` are [rest parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters).
  ///The `args` will be stringified automatically using `JSON.stringify(args)` method and then they will be decoded on the Dart side.
  int addJavaScriptHandler(String handlerName, JavaScriptHandlerCallback callback) {
    this.javaScriptHandlersMap.putIfAbsent(handlerName, () => List<JavaScriptHandlerCallback>());
    this.javaScriptHandlersMap[handlerName].add(callback);
    return this.javaScriptHandlersMap[handlerName].indexOf(callback);
  }

  ///Removes a JavaScript message handler previously added with the [addJavaScriptHandler()] method in the [handlerName] list by its position [index].
  ///Returns `true` if the callback is removed, otherwise `false`.
  bool removeJavaScriptHandler(String handlerName, int index) {
    try {
      this.javaScriptHandlersMap[handlerName].removeAt(index);
      return true;
    }
    on RangeError catch(e) {
      print(e);
    }
    return false;
  }

pichillilorenzo's avatar
pichillilorenzo committed
541 542 543 544 545 546 547 548 549 550 551
  ///Event fires when the [InAppBrowser] starts to load an [url].
  void onLoadStart(String url) {

  }

  ///Event fires when the [InAppBrowser] finishes loading an [url].
  void onLoadStop(String url) {

  }

  ///Event fires when the [InAppBrowser] encounters an error loading an [url].
552
  void onLoadError(String url, int code, String message) {
pichillilorenzo's avatar
pichillilorenzo committed
553 554 555 556 557 558 559 560

  }

  ///Event fires when the [InAppBrowser] window is closed.
  void onExit() {

  }

561
  ///Give the host application a chance to take control when a URL is about to be loaded in the current WebView.
562
  ///
563
  ///**NOTE**: In order to be able to listen this event, you need to set `useShouldOverrideUrlLoading` option to `true`.
564 565 566 567
  void shouldOverrideUrlLoading(String url) {

  }

568
  ///Event fires when the [InAppBrowser] webview loads a resource.
569
  ///
570
  ///**NOTE**: In order to be able to listen this event, you need to set `useOnLoadResource` option to `true`.
571
  ///
pichillilorenzo's avatar
pichillilorenzo committed
572
  ///**NOTE only for iOS**: In some cases, the [response.data] of a [response] with `text/assets` encoding could be empty.
573
  void onLoadResource(WebResourceResponse response, WebResourceRequest request) {
574 575 576

  }

577 578 579 580 581
  ///Event fires when the [InAppBrowser] webview receives a [ConsoleMessage].
  void onConsoleMessage(ConsoleMessage consoleMessage) {

  }

pichillilorenzo's avatar
pichillilorenzo committed
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
  ///Returns `true` if the browser is opened, otherwise `false`.
  bool isOpened() {
    return this._isOpened;
  }

  void _throwIsAlreadyOpened({String message = ''}) {
    if (this.isOpened()) {
      throw Exception(['Error: ${ (message.isEmpty) ? '' : message + ' '}The browser is already opened.']);
    }
  }

  void _throwIsNotOpened({String message = ''}) {
    if (!this.isOpened()) {
      throw Exception(['Error: ${ (message.isEmpty) ? '' : message + ' '}The browser is not opened.']);
    }
  }
pichillilorenzo's avatar
pichillilorenzo committed
598
}
599 600 601 602 603 604 605 606

///ChromeSafariBrowser class.
///
///This class uses native [Chrome Custom Tabs](https://developer.android.com/reference/android/support/customtabs/package-summary) on Android
///and [SFSafariViewController](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller) on iOS.
///
///[browserFallback] represents the [InAppBrowser] instance fallback in case [Chrome Custom Tabs]/[SFSafariViewController] is not available.
class ChromeSafariBrowser {
607
  String uuid;
608
  InAppBrowser browserFallback;
pichillilorenzo's avatar
pichillilorenzo committed
609
  bool _isOpened = false;
610

611
  ///Initialize the [ChromeSafariBrowser] instance with a [InAppBrowser] fallback instance or `null`.
612
  ChromeSafariBrowser (bf) {
613
    uuid = _uuidGenerator.v4();
614 615
    browserFallback = bf;
    _ChannelManager.addListener(uuid, _handleMethod);
pichillilorenzo's avatar
pichillilorenzo committed
616
    _isOpened = false;
617 618 619 620 621 622 623 624 625 626 627 628
  }

  Future<dynamic> _handleMethod(MethodCall call) async {
    switch(call.method) {
      case "onChromeSafariBrowserOpened":
        onOpened();
        break;
      case "onChromeSafariBrowserLoaded":
        onLoaded();
        break;
      case "onChromeSafariBrowserClosed":
        onClosed();
pichillilorenzo's avatar
pichillilorenzo committed
629
        this._isOpened = false;
630
        break;
pichillilorenzo's avatar
pichillilorenzo committed
631 632
      default:
        throw UnimplementedError("Unimplemented ${call.method} method");
633 634 635
    }
  }

636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
  ///Opens an [url] in a new [ChromeSafariBrowser] instance or the system browser.
  ///
  ///- [url]: The [url] to load. Call [encodeUriComponent()] on this if the [url] contains Unicode characters.
  ///
  ///- [options]: Options for the [ChromeSafariBrowser].
  ///
  ///- [headersFallback]: The additional header of the [InAppBrowser] instance fallback to be used in the HTTP request for this URL, specified as a map from name to value.
  ///
  ///- [optionsFallback]: Options used by the [InAppBrowser] instance fallback.
  ///
  ///**Android** supports these options:
  ///
  ///- __addShareButton__: Set to `false` if you don't want the default share button. The default value is `true`.
  ///- __showTitle__: Set to `false` if the title shouldn't be shown in the custom tab. The default value is `true`.
  ///- __toolbarBackgroundColor__: Set the custom background color of the toolbar.
  ///- __enableUrlBarHiding__: Set to `true` to enable the url bar to hide as the user scrolls down on the page. The default value is `false`.
  ///- __instantAppsEnabled__: Set to `true` to enable Instant Apps. The default value is `false`.
  ///
  ///**iOS** supports these options:
655
  ///
656 657 658 659 660 661 662
  ///- __entersReaderIfAvailable__: Set to `true` if Reader mode should be entered automatically when it is available for the webpage. The default value is `false`.
  ///- __barCollapsingEnabled__: Set to `true` to enable bar collapsing. The default value is `false`.
  ///- __dismissButtonStyle__: Set the custom style for the dismiss button. The default value is `0 //done`. See [SFSafariViewController.DismissButtonStyle](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller/dismissbuttonstyle) for all the available styles.
  ///- __preferredBarTintColor__: Set the custom background color of the navigation bar and the toolbar.
  ///- __preferredControlTintColor__: Set the custom color of the control buttons on the navigation bar and the toolbar.
  ///- __presentationStyle__: Set the custom modal presentation style when presenting the WebView. The default value is `0 //fullscreen`. See [UIModalPresentationStyle](https://developer.apple.com/documentation/uikit/uimodalpresentationstyle) for all the available styles.
  ///- __transitionStyle__: Set to the custom transition style when presenting the WebView. The default value is `0 //crossDissolve`. See [UIModalTransitionStyle](https://developer.apple.com/documentation/uikit/uimodaltransitionStyle) for all the available styles.
663
  Future<void> open(String url, {Map<String, dynamic> options = const {}, Map<String, String> headersFallback = const {}, Map<String, dynamic> optionsFallback = const {}}) async {
pichillilorenzo's avatar
pichillilorenzo committed
664
    this._throwIsAlreadyOpened(message: 'Cannot open $url!');
665
    Map<String, dynamic> args = <String, dynamic>{};
666 667
    args.putIfAbsent('uuid', () => uuid);
    args.putIfAbsent('uuidFallback', () => (browserFallback != null) ? browserFallback.uuid : '');
668 669 670 671 672
    args.putIfAbsent('url', () => url);
    args.putIfAbsent('headers', () => headersFallback);
    args.putIfAbsent('options', () => options);
    args.putIfAbsent('optionsFallback', () => optionsFallback);
    args.putIfAbsent('useChromeSafariBrowser', () => true);
pichillilorenzo's avatar
pichillilorenzo committed
673 674
    await _ChannelManager.channel.invokeMethod('open', args);
    this._isOpened = true;
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
  }

  ///Event fires when the [ChromeSafariBrowser] is opened.
  void onOpened() {

  }

  ///Event fires when the [ChromeSafariBrowser] is loaded.
  void onLoaded() {

  }

  ///Event fires when the [ChromeSafariBrowser] is closed.
  void onClosed() {

  }
pichillilorenzo's avatar
pichillilorenzo committed
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706

  bool isOpened() {
    return this._isOpened;
  }

  void _throwIsAlreadyOpened({String message = ''}) {
    if (this.isOpened()) {
      throw Exception(['Error: ${ (message.isEmpty) ? '' : message + ' '}The browser is already opened.']);
    }
  }

  void _throwIsNotOpened({String message = ''}) {
    if (!this.isOpened()) {
      throw Exception(['Error: ${ (message.isEmpty) ? '' : message + ' '}The browser is not opened.']);
    }
  }
707
}