Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

flutter inappbrowser plugin

a flutter plugin that allows you to add an inline webview or open an in-app browser window.

requirements

  • dart sdk: “>=2.0.0-dev.68.0 <3.0.0”
  • flutter: “>=1.9.1+hotfix.5 <2.0.0”
  • android: minsdkversion 17
  • ios: --ios-language swift

note for android

during the build, if android fails with error: uses-sdk:minsdkversion 16 cannot be smaller than version 17 declared in library, it means that you need to update the minsdkversion of your build.gradle file to at least 17.

because of flutter androidx compatibility, the latest version that doesn’t use androidx is 0.6.0.

important note for ios

if you are starting a new fresh app, you need to create the flutter app with flutter create -i swift (see flutter/flutter#13422 (comment)), otherwise, you will get this message:

=== build target flutter_inappbrowser of project pods with configuration debug ===
the “swift language version” (swift_version) build setting must be set to a supported value for targets which use swift. supported values are: 3.0, 4.0, 4.2, 5.0. this setting can be set in the build settings editor.

if you still have this problem, try to edit ios podfile like this (see #15):

target 'runner' do
  use_frameworks!  # required by simple_permission
  ...
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['swift_version'] = '5.0'  # required by simple_permission
      config.build_settings['enable_bitcode'] = 'no'
    end
  end
end

instead, if you have already a non-swift project, you can check this issue to solve the problem: friction adding swift plugin to objective-c project.

getting started

for help getting started with flutter, view our online
documentation.

for help on editing plugin code, view the documentation.

installation

first, add flutter_inappbrowser as a dependency in your pubspec.yaml file.

usage

classes:

  • inappwebview: flutter widget for adding an inline native webview integrated into the flutter widget tree. to use inappwebview class on ios you need to opt-in for the embedded views preview by adding a boolean property to the app’s info.plist file, with the key io.flutter.embedded_views_preview and the value yes.
  • inappbrowser: in-app browser using native webview.
  • chromesafaribrowser: in-app browser using chrome custom tabs on android / sfsafariviewcontroller on ios.
  • inapplocalhostserver: this class allows you to create a simple server on http://localhost:[port]/. the default port value is 8080.
  • cookiemanager: this class implements a singleton object (shared instance) which manages the cookies used by webview instances. note for ios: available from ios 11.0+.
  • httpauthcredentialdatabase: this class implements a singleton object (shared instance) which manages the shared http auth credentials cache.

api reference

see the online api reference to get the full documentation.

load a file inside assets folder

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:

...

# 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/

...

inappwebview class

flutter widget for adding an inline native webview integrated into the flutter widget tree.

the plugin relies on flutter’s mechanism (in developers preview) for embedding android and ios native views: androidview and uikitview.
known issues are tagged with the platform-views label in the flutter official repo.
keyboard support within webviews is also experimental.

to use inappwebview class on ios you need to opt-in for the embedded views preview by adding a boolean property to the app’s info.plist file, with the key io.flutter.embedded_views_preview and the value yes.

use inappwebviewcontroller to control the webview instance.
example:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappbrowser/flutter_inappbrowser.dart';

future main() async {
  runapp(new myapp());
}

class myapp extends statefulwidget {
  @override
  _myappstate createstate() => new _myappstate();
}

class _myappstate extends state<myapp> {

  inappwebviewcontroller webview;
  string url = "";
  double progress = 0;

  @override
  void initstate() {
    super.initstate();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  widget build(buildcontext context) {
    return materialapp(
      home: scaffold(
        appbar: appbar(
          title: const text('inappwebview example'),
        ),
        body: container(
          child: column(children: <widget>[
            container(
              padding: edgeinsets.all(20.0),
              child: text(
                  "current urln${(url.length > 50) ? url.substring(0, 50) + "..." : url}"),
            ),
            container(
                padding: edgeinsets.all(10.0),
                child: progress < 1.0
                    ? linearprogressindicator(value: progress)
                    : container()),
            expanded(
              child: container(
                margin: const edgeinsets.all(10.0),
                decoration:
                    boxdecoration(border: border.all(color: colors.blueaccent)),
                child: inappwebview(
                  initialurl: "https://flutter.dev/",
                  initialheaders: {},
                  initialoptions: inappwebviewwidgetoptions(
                    inappwebviewoptions: inappwebviewoptions(
                        debuggingenabled: true,
                    )
                  ),
                  onwebviewcreated: (inappwebviewcontroller controller) {
                    webview = controller;
                  },
                  onloadstart: (inappwebviewcontroller controller, string url) {
                    setstate(() {
                      this.url = url;
                    });
                  },
                  onloadstop: (inappwebviewcontroller controller, string url) async {
                    setstate(() {
                      this.url = url;
                    });
                  },
                  onprogresschanged: (inappwebviewcontroller controller, int progress) {
                    setstate(() {
                      this.progress = progress / 100;
                    });
                  },
                ),
              ),
            ),
            buttonbar(
              alignment: mainaxisalignment.center,
              children: <widget>[
                raisedbutton(
                  child: icon(icons.arrow_back),
                  onpressed: () {
                    if (webview != null) {
                      webview.goback();
                    }
                  },
                ),
                raisedbutton(
                  child: icon(icons.arrow_forward),
                  onpressed: () {
                    if (webview != null) {
                      webview.goforward();
                    }
                  },
                ),
                raisedbutton(
                  child: icon(icons.refresh),
                  onpressed: () {
                    if (webview != null) {
                      webview.reload();
                    }
                  },
                ),
              ],
            ),
        ])),
      ),
    );
  }
}

screenshots:

  • android:

inline webview

  • ios:

ios

inappwebviewcontroller methods

  • geturl: gets the url for the current page.
  • gettitle: gets the title for the current page.
  • getprogress: gets the progress for the current page. the progress value is between 0 and 100.
  • gethtml: gets the content html of the page.
  • getfavicons: gets the list of all favicons for the current page.
  • loadurl({@required string url, map<string, string> headers = const {}}): loads the given url with optional headers specified as a map from name to value.
  • posturl({@required string url, @required uint8list postdata}): loads the given url with postdata using post method into this webview.
  • loaddata({@required string data, string mimetype = "text/html", string encoding = "utf8", string baseurl = "about:blank"}): loads the given data into this webview.
  • loadfile({@required string assetfilepath, map<string, string> headers = const {}}): loads the given assetfilepath with optional headers specified as a map from name to value.
  • reload: reloads the webview.
  • goback: goes back in the history of the webview.
  • cangoback: returns a boolean value indicating whether the webview can move backward.
  • goforward: goes forward in the history of the webview.
  • cangoforward: returns a boolean value indicating whether the webview can move forward.
  • gobackorforward({@required int steps}): goes to the history item that is the number of steps away from the current item. steps is negative if backward and positive if forward.
  • cangobackorforward({@required int steps}): returns a boolean value indicating whether the webview can go back or forward the given number of steps. steps is negative if backward and positive if forward.
  • goto({@required webhistoryitem historyitem}): navigates to a webhistoryitem from the back-forward webhistory.list and sets it as the current item.
  • isloading: check if the webview instance is in a loading state.
  • stoploading: stops the webview from loading.
  • evaluatejavascript({@required string source}): evaluates javascript code into the webview and returns the result of the evaluation.
  • injectjavascriptfilefromurl({@required string urlfile}): injects an external javascript file into the webview from a defined url.
  • injectjavascriptfilefromasset({@required string assetfilepath}): injects a javascript file into the webview from the flutter assets directory.
  • injectcsscode({@required string source}): injects css into the webview.
  • injectcssfilefromurl({@required string urlfile}): injects an external css file into the webview from a defined url.
  • injectcssfilefromasset({@required string assetfilepath}): injects a css file into the webview from the flutter assets directory.
  • addjavascripthandler({@required string handlername, @required javascripthandlercallback callback}): adds a javascript message handler callback that listen to post messages sent from javascript by the handler with name handlername.
  • removejavascripthandler({@required string handlername}): removes a javascript message handler previously added with the addjavascripthandler() associated to handlername key.
  • takescreenshot: takes a screenshot (in png format) of the webview’s visible viewport and returns a uint8list. returns null if it wasn’t be able to take it.
  • setoptions({@required inappwebviewwidgetoptions options}): sets the webview options with the new options and evaluates them.
  • getoptions: gets the current webview options. returns the options with null value if they are not set yet.
  • getcopybackforwardlist: gets the webhistory for this webview. this contains the back/forward list for use in querying each item in the history stack.
  • startsafebrowsing: starts safe browsing initialization (available only on android).
  • setsafebrowsingwhitelist({@required list<string> hosts}): sets the list of hosts (domain names/ip addresses) that are exempt from safebrowsing checks. the list is global for all the webviews (available only on android).
  • getsafebrowsingprivacypolicyurl: returns a url pointing to the privacy policy for safe browsing reporting. this value will never be null.
  • clearcache: clears all the webview’s cache.
  • clearsslpreferences: clears the ssl preferences table stored in response to proceeding with ssl certificate errors (available only on android).
  • clearclientcertpreferences: clears the client certificate preferences stored in response to proceeding/cancelling client cert requests (available only on android).
  • findallasync({@required string find}): finds all instances of find on the page and highlights them. notifies onfindresultreceived listener.
  • findnext({@required bool forward}): highlights and scrolls to the next match found by findallasync(). notifies onfindresultreceived listener.
  • clearmatches: clears the highlighting surrounding text matches created by findallasync().
  • gettrexrunnerhtml: gets the html (with javascript) of the chromium’s t-rex runner game. used in combination with gettrexrunnercss().
  • gettrexrunnercss: gets the css of the chromium’s t-rex runner game. used in combination with gettrexrunnerhtml().
  • scrollto({@required int x, @required int y}): scrolls the webview to the position.
  • scrollby({@required int x, @required int y}): moves the scrolled position of the webview.
about the javascript handler

the android implementation uses addjavascriptinterface.
the ios implementation uses addscriptmessagehandler

the javascript function that can be used to call the handler is window.flutter_inappbrowser.callhandler(handlername <string>, ...args), where args are rest parameters.
the args will be stringified automatically using json.stringify(args) method and then they will be decoded on the dart side.

in order to call window.flutter_inappbrowser.callhandler(handlername <string>, ...args) properly, you need to wait and listen the javascript event flutterinappbrowserplatformready.
this event will be dispatched as soon as the platform (android or ios) is ready to handle the callhandler method.

   window.addeventlistener("flutterinappbrowserplatformready", function(event) {
     console.log("ready");
   });

window.flutter_inappbrowser.callhandler returns a javascript promise
that can be used to get the json result returned by [javascripthandlercallback].
in this case, simply return data that you want to send and it will be automatically json encoded using [jsonencode] from the dart:convert library.

so, on the javascript side, to get data coming from the dart side, you will use:

<script>
   window.addeventlistener("flutterinappbrowserplatformready", function(event) {
     window.flutter_inappbrowser.callhandler('handlerfoo').then(function(result) {
       console.log(result);
     });

     window.flutter_inappbrowser.callhandler('handlerfoowithargs', 1, true, ['bar', 5], {foo: 'baz'}).then(function(result) {
       console.log(result);
     });
   });
</script>

instead, on the onloadstop webview event, you can use callhandler directly:

  // inject javascript that will receive data back from flutter
  inappwebviewcontroller.evaluatejavascript(source: """
    window.flutter_inappbrowser.callhandler('test', 'text from javascript').then(function(result) {
      console.log(result);
    });
  """);

inappwebview options

inappwebview cross-platform options
  • 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.
  • useondownloadstart: set to true to be able to listen at the ondownloadstart event. the default value is false.
  • useontargetblank: set to true to be able to listen at the ontargetblank event. 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: sets the user-agent for the webview.
  • applicationnameforuseragent: append to the existing user-agent. setting useragent will override this.
  • javascriptenabled: set to true to enable javascript. the default value is true.
  • debuggingenabled: enables debugging of web contents (html / css / javascript) loaded into any webviews of this application.
  • javascriptcanopenwindowsautomatically: set to true to allow javascript open windows without user interaction. the default value is false.
  • mediaplaybackrequiresusergesture: set to true to prevent html5 audio or video from autoplaying. the default value is true.
  • minimumfontsize: sets the minimum font size. the default value is 8 for android, 0 for ios.
  • verticalscrollbarenabled: define whether the vertical scrollbar should be drawn or not. the default value is true.
  • horizontalscrollbarenabled: define whether the horizontal scrollbar should be drawn or not. the default value is true.
  • resourcecustomschemes: list of custom schemes that the webview must handle. use the onloadresourcecustomscheme event to intercept resource requests with custom scheme.
  • contentblockers: list of contentblocker that are a set of rules used to block content in the browser window.
  • preferredcontentmode: sets the content mode that the webview needs to use when loading and rendering a webpage. the default value is inappwebviewuserpreferredcontentmode.recommended.
  • useshouldinterceptajaxrequest: set to true to be able to listen at the shouldinterceptajaxrequest event. the default value is false.
  • useshouldinterceptfetchrequest: set to true to be able to listen at the shouldinterceptfetchrequest event. the default value is false.
  • incognito: set to true to open a browser window with incognito mode. the default value is false.
  • cacheenabled: sets whether webview should use browser caching. the default value is true.
  • transparentbackground: set to true to make the background of the webview transparent. if your app has a dark theme, this can prevent a white flash on initialization. the default value is false.
  • disableverticalscroll: set to true to disable vertical scroll. the default value is false.
  • disablehorizontalscroll: set to true to disable horizontal scroll. the default value is false.
inappwebview android-specific options
  • textzoom: sets the text zoom of the page in percent. the default value is 100.
  • 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.
  • displayzoomcontrols: set to true if the webview should display on-screen zoom controls when using the 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.
  • safebrowsingenabled: sets whether safe browsing is enabled. safe browsing allows webview to protect against malware and phishing attacks by verifying the links.
  • mixedcontentmode: configures the webview’s behavior when a secure origin attempts to load a resource from an insecure origin.
  • allowcontentaccess: enables or disables content url access within webview. content url access allows webview to load content from a content provider installed in the system. the default value is true.
  • allowfileaccess: enables or disables file access within webview. note that this enables or disables file system access only.
  • allowfileaccessfromfileurls: sets whether javascript running in the context of a file scheme url should be allowed to access content from other file scheme urls.
  • allowuniversalaccessfromfileurls: sets whether javascript running in the context of a file scheme url should be allowed to access content from any origin.
  • appcachepath: sets the path to the application caches files. in order for the application caches api to be enabled, this option must be set a path to which the application can write.
  • blocknetworkimage: sets whether the webview should not load image resources from the network (resources accessed via http and https uri schemes). the default value is false.
  • blocknetworkloads: sets whether the webview should not load resources from the network. the default value is false.
  • cachemode: overrides the way the cache is used. the way the cache is used is based on the navigation type. for a normal page load, the cache is checked and content is re-validated as needed.
  • cursivefontfamily: sets the cursive font family name. the default value is "cursive".
  • defaultfixedfontsize: sets the default fixed font size. the default value is 16.
  • defaultfontsize: sets the default font size. the default value is 16.
  • defaulttextencodingname: sets the default text encoding name to use when decoding html pages. the default value is "utf-8".
  • disabledactionmodemenuitems: disables the action mode menu items according to menuitems flag.
  • fantasyfontfamily: sets the fantasy font family name. the default value is "fantasy".
  • fixedfontfamily: sets the fixed font family name. the default value is "monospace".
  • forcedark: set the force dark mode for this webview. the default value is androidinappwebviewforcedark.force_dark_off.
  • geolocationenabled: sets whether geolocation api is enabled. the default value is true.
  • layoutalgorithm: sets the underlying layout algorithm. this will cause a re-layout of the webview.
  • loadwithoverviewmode: sets whether the webview loads pages in overview mode, that is, zooms out the content to fit on screen by width.
  • loadsimagesautomatically: sets whether the webview should load image resources. note that this method controls loading of all images, including those embedded using the data uri scheme.
  • minimumlogicalfontsize: sets the minimum logical font size. the default is 8.
  • initialscale: sets the initial scale for this webview. 0 means default. the behavior for the default scale depends on the state of usewideviewport and loadwithoverviewmode.
  • needinitialfocus: tells the webview whether it needs to set a node. the default value is true.
  • offscreenpreraster: sets whether this webview should raster tiles when it is offscreen but attached to a window.
  • sansseriffontfamily: sets the sans-serif font family name. the default value is "sans-serif".
  • seriffontfamily: sets the serif font family name. the default value is "sans-serif".
  • standardfontfamily: sets the standard font family name. the default value is "sans-serif".
  • saveformdata: sets whether the webview should save form data. in android o, the platform has implemented a fully functional autofill feature to store form data.
  • thirdpartycookiesenabled: boolean value to enable third party cookies in the webview.
  • hardwareacceleration: boolean value to enable hardware acceleration in the webview.
inappwebview ios-specific options
  • 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.
  • 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.
  • allowsinlinemediaplayback: set to true to allow html5 media playback to appear inline within the screen layout, using browser-supplied controls rather than native controls.
  • allowspictureinpicturemediaplayback: set to true to allow html5 videos play picture-in-picture. the default value is true.
  • isfraudulentwebsitewarningenabled: a boolean value indicating whether warnings should be shown for suspected fraudulent content such as phishing or malware.
  • selectiongranularity: the level of granularity with which the user can interactively select content in the web view.
  • datadetectortypes: specifying a datadetectorytypes value adds interactivity to web content that matches the value.
  • sharedcookiesenabled: set true if shared cookies from httpcookiestorage.shared should used for every load request in the webview.

inappwebview events

  • onwebviewcreated: event fired when the inappwebview is created.
  • onloadstart: event fired when the inappwebview starts to load an url.
  • onloadstop: event fired when the inappwebview finishes loading an url.
  • onloaderror: event fired when the inappwebview encounters an error loading an url.
  • onloadhttperror: event fired when the inappwebview main page receives an http error.
  • onprogresschanged: event fired when the current progress of loading a page is changed.
  • onconsolemessage: event fired when the inappwebview receives a consolemessage.
  • shouldoverrideurlloading: give the host application a chance to take control when a url is about to be loaded in the current webview.
  • onloadresource: event fired when the inappwebview loads a resource.
  • onscrollchanged: event fired when the inappwebview scrolls.
  • ondownloadstart: event fired when inappwebview recognizes and starts a downloadable file.
  • onloadresourcecustomscheme: event fired when the inappwebview finds the custom-scheme while loading a resource. here you can handle the url request and return a customschemeresponse to load a specific resource encoded to base64.
  • ontargetblank: event fired when the inappwebview tries to open a link with target="_blank".
  • ongeolocationpermissionsshowprompt: event that notifies the host application that web content from the specified origin is attempting to use the geolocation api, but no permission state is currently set for that origin (available only on android).
  • onjsalert: event fired when javascript calls the alert() method to display an alert dialog.
  • onjsconfirm: event fired when javascript calls the confirm() method to display a confirm dialog.
  • onjsprompt: event fired when javascript calls the prompt() method to display a prompt dialog.
  • onsafebrowsinghit: event fired when the webview notifies that a loading url has been flagged by safe browsing (available only on android).
  • onreceivedhttpauthrequest: event fired when the webview received an http authentication request. the default behavior is to cancel the request.
  • onreceivedservertrustauthrequest: event fired when the webview need to perform server trust authentication (certificate validation).
  • onreceivedclientcertrequest: notify the host application to handle a ssl client certificate request.
  • onfindresultreceived: event fired as find-on-page operations progress.
  • shouldinterceptajaxrequest: event fired when an xmlhttprequest is sent to a server.
  • onajaxreadystatechange: event fired whenever the readystate attribute of an xmlhttprequest changes.
  • onajaxprogress: event fired as an xmlhttprequest progress.
  • shouldinterceptfetchrequest: event fired when a request is sent to a server through fetch api.
  • onnavigationstatechange: event fired when the navigation state of the inappwebview changes.

inappbrowser class

in-app browser using native webview.

inappbrowser.webviewcontroller can be used to access the inappwebview api.

create a class that extends the inappbrowser class in order to override the callbacks to manage the browser events.
example:

import 'package:flutter/material.dart';
import 'package:flutter_inappbrowser/flutter_inappbrowser.dart';

class myinappbrowser extends inappbrowser {
  @override
  future onbrowsercreated() async {
    print("nnbrowser created!nn");
  }

  @override
  future onloadstart(string url) async {
    print("nnstarted $urlnn");
  }

  @override
  future onloadstop(string url) async {
    print("nnstopped $urlnn");
  }

  @override
  void onloaderror(string url, int code, string message) {
    print("can't load $url.. error: $message");
  }

  @override
  void onprogresschanged(int progress) {
    print("progress: $progress");
  }

  @override
  void onexit() {
    print("nnbrowser closed!nn");
  }

  @override
  void shouldoverrideurlloading(string url) {
    print("nn override $urlnn");
    this.webviewcontroller.loadurl(url: url);
  }

  @override
  void onloadresource(loadedresource response) {
    print("started at: " +
        response.starttime.tostring() +
        "ms ---> duration: " +
        response.duration.tostring() +
        "ms " +
        response.url);
  }

  @override
  void onconsolemessage(consolemessage consolemessage) {
    print("""
    console output:
      message: ${consolemessage.message}
      messagelevel: ${consolemessage.messagelevel.tovalue()}
   """);
  }
}

void main() => runapp(new myapp());

class myapp extends statefulwidget {
  final myinappbrowser browser = new myinappbrowser();
  
  @override
  _myappstate createstate() => new _myappstate();
}

class _myappstate extends state<myapp> {

  @override
  widget build(buildcontext context) {
    return materialapp(
      home: scaffold(
        appbar: appbar(
          title: const text('inappbrowser example'),
        ),
        body: center(
          child: raisedbutton(
              onpressed: () {
                widget.browser.openfile(
                    assetfilepath: "assets/index.html",
                    options: inappbrowserclassoptions(
                        inappwebviewwidgetoptions: inappwebviewwidgetoptions(
                            inappwebviewoptions: inappwebviewoptions(
                              useshouldoverrideurlloading: true,
                              useonloadresource: true,
                            ))));
              },
              child: text("open inappbrowser")),
        ),
      ),
    );
  }
}

screenshots:

  • ios:

ios

  • android:

android

inappbrowser methods

  • open({string url = "about:blank", map<string, string> headers = const {}, inappbrowserclassoptions options}): opens an url in a new inappbrowser instance.
  • openfile({@required string assetfilepath, map<string, string> headers = const {}, inappbrowserclassoptions options}): opens the given assetfilepath file in a new inappbrowser instance. the other arguments are the same of inappbrowser.open.
  • opendata({@required string data, string mimetype = "text/html", string encoding = "utf8", string baseurl = "about:blank", inappbrowserclassoptions options}): opens a new inappbrowser instance with data as a content, using baseurl as the base url for it.
  • openwithsystembrowser({@required string url}): this is a static method that opens an url in the system browser. you wont be able to use the inappbrowser methods here!
  • show: displays an inappbrowser window that was opened hidden. calling this has no effect if the inappbrowser was already visible.
  • hide: hides the inappbrowser window. calling this has no effect if the inappbrowser was already hidden.
  • close: closes the inappbrowser window.
  • ishidden: check if the web view of the inappbrowser instance is hidden.
  • setoptions({@required inappbrowserclassoptions options}): sets the inappbrowser options with the new options and evaluates them.
  • getoptions: gets the current inappbrowser options as a map. returns null if the options are not setted yet.
  • isopened: returns true if the inappbrowser instance is opened, otherwise false.

inappbrowser options

they are the same of the inappwebview class.
specific options of the inappbrowser class are:

inappbrowser cross-platform options
  • hidden: set to true to create the browser and load the page, but not show it. omit or set to false to have the browser open and load normally. the default value is false.
  • 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 toolbar at the top.
  • hideurlbar: set to true to hide the url bar on the toolbar at the top. the default value is false.
inappbrowser android-specific options
  • hidetitlebar: set to true if you want the title should be displayed. the default value is false.
  • toolbartopfixedtitle: set the action bar’s title.
  • 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.
  • progressbar: set to false to hide the progress bar at the bottom of the toolbar at the top. the default value is true.
inappbrowser ios-specific options
  • 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 toolbar 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 ioswebviewoptionspresentationstyle.full_screen.
  • transitionstyle: set to the custom transition style when presenting the webview. the default value is ioswebviewoptionstransitionstyle.cover_vertical.
  • spinner: set to false to hide the spinner when the webview is loading a page. the default value is true.

inappbrowser events

they are the same of the inappwebview class, except for inappwebview.onwebviewcreated event.
specific events of the inappbrowser class are:

  • onbrowsercreated: event fired when the inappbrowser is created.
  • onexit: event fired when the inappbrowser window is closed.

chromesafaribrowser class

chrome custom tabs on android / sfsafariviewcontroller on ios.

you can initialize the chromesafaribrowser instance with an inappbrowser fallback instance.

create a class that extends the chromesafaribrowser class in order to override the callbacks to manage the browser events. example:

import 'package:flutter/material.dart';
import 'package:flutter_inappbrowser/flutter_inappbrowser.dart';

class myinappbrowser extends inappbrowser {

  @override
  future onloadstart(string url) async {
    print("nnstarted $urlnn");
  }

  @override
  future onloadstop(string url) async {
    print("nnstopped $urlnn");
  }

  @override
  void onloaderror(string url, int code, string message) {
    print("nncan't load $url.. error: $messagenn");
  }

  @override
  void onexit() {
    print("nnbrowser closed!nn");
  }

}

class mychromesafaribrowser extends chromesafaribrowser {
  
  mychromesafaribrowser(browserfallback) : super(bfallback: browserfallback);

  @override
  void onopened() {
    print("chromesafari browser opened");
  }

  @override
  void onloaded() {
    print("chromesafari browser loaded");
  }

  @override
  void onclosed() {
    print("chromesafari browser closed");
  }
}

void main() => runapp(new myapp());

class myapp extends statefulwidget {
  final chromesafaribrowser browser = new mychromesafaribrowser(new myinappbrowser());
  
  @override
  _myappstate createstate() => new _myappstate();
}

class _myappstate extends state<myapp> {

  @override
  void initstate() {
    super.initstate();
  }

  @override
  widget build(buildcontext context) {
    return materialapp(
      home: scaffold(
        appbar: appbar(
          title: const text('chromesafaribrowser example'),
        ),
        body: center(
          child: raisedbutton(
              onpressed: () async {
                await widget.browser.open(
                    url: "https://flutter.dev/",
                    options: chromesafaribrowserclassoptions(
                        androidchromecustomtabsoptions: androidchromecustomtabsoptions(addsharebutton: false),
                        iossafarioptions: iossafarioptions(barcollapsingenabled: true)));
              },
              child: text("open chrome safari browser")),
        ),
      ),
    );
  }
}

screenshots:

  • ios:

ios

  • android:

android

chromesafaribrowser methods

  • open({@required string url, chromesafaribrowserclassoptions options, map<string, string> headersfallback = const {}, inappbrowserclassoptions optionsfallback}): opens an url in a new chromesafaribrowser instance.
  • isopened: returns true if the chromesafaribrowser instance is opened, otherwise false.

chromesafaribrowser options

chromesafaribrowser android-specific 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.
chromesafaribrowser ios-specific options
  • 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 iossafarioptionsdismissbuttonstyle.done.
  • 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 ioswebviewoptionspresentationstyle.full_screen.
  • transitionstyle: set to the custom transition style when presenting the webview. the default value is ioswebviewoptionstransitionstyle.cover_vertical.

chromesafaribrowser events

  • onopened: event fires when the chromesafaribrowser is opened.
  • onloaded: event fires when the chromesafaribrowser is loaded.
  • onclosed: event fires when the chromesafaribrowser is closed.

inapplocalhostserver class

this class allows you to create a simple server on http://localhost:[port]/ in order to be able to load your assets file on a server. the default port value is 8080.

example:

// ...

inapplocalhostserver localhostserver = new inapplocalhostserver();

future main() async {
  await localhostserver.start();
  runapp(new myapp());
}

// ...

  @override
  widget build(buildcontext context) {
    return materialapp(
      home: scaffold(
        appbar: appbar(
          title: const text('inappwebview example'),
        ),
        body: container(
          child: column(children: <widget>[
            expanded(
              child: container(
                child: inappwebview(
                  initialurl: "http://localhost:8080/assets/index.html",
                  initialheaders: {},
                  initialoptions: inappwebviewwidgetoptions(
                      inappwebviewoptions: inappwebviewoptions(
                        debuggingenabled: true,
                      )
                  ),
                  onwebviewcreated: (inappwebviewcontroller controller) {
  
                  },
                  onloadstart: (inappwebviewcontroller controller, string url) {
  
                  },
                  onloadstop: (inappwebviewcontroller controller, string url) {
  
                  },
                ),
              ),
            )]
          )
        ),
      ),
    );
  }

// ...

inapplocalhostserver methods

  • start: starts a server on http://localhost:[port]/.
  • close: closes the server.

cookiemanager class

this class implements a singleton object (shared instance) which manages the cookies used by webview instances.

note for ios: available from ios 11.0+.

cookiemanager methods

  • instance: gets the cookie manager shared instance.
  • setcookie({@required string url, @required string name, @required string value, string domain, string path = "/", int expiresdate, int maxage, bool issecure }): sets a cookie for the given url. any existing cookie with the same host, path and name will be replaced with the new cookie. the cookie being set will be ignored if it is expired.
  • getcookies({@required string url}): gets all the cookies for the given url.
  • getcookie({@required string url, @required string name}): gets a cookie by its name for the given url.
  • deletecookie({@required string url, @required string name, string domain = "", string path = "/"}): removes a cookie by its name for the given url, domain and path.
  • deletecookies({@required string url, string domain = "", string path = "/"}): removes all cookies for the given url, domain and path.
  • deleteallcookies(): removes all cookies.

httpauthcredentialdatabase class

this class implements a singleton object (shared instance) which manages the shared http auth credentials cache.
on ios, this class uses the urlcredentialstorage class.
on android, this class has a custom implementation using android.database.sqlite.sqlitedatabase because webviewdatabase doesn’t offer the same functionalities as ios urlcredentialstorage.

httpauthcredentialdatabase methods

  • instance: gets the database shared instance.
  • getallauthcredentials: gets a map list of all http auth credentials saved.
  • gethttpauthcredentials({@required protectionspace protectionspace}): gets all the http auth credentials saved for that protectionspace.
  • sethttpauthcredential({@required protectionspace protectionspace, @required httpauthcredential credential}): saves an http auth credential for that protectionspace.
  • removehttpauthcredential({@required protectionspace protectionspace, @required httpauthcredential credential}): removes an http auth credential for that protectionspace.
  • removehttpauthcredentials({@required protectionspace protectionspace}): removes all the http auth credentials saved for that protectionspace.
  • clearallauthcredentials(): removes all the http auth credentials saved in the database.

Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

Comments are closed.