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’sinfo.plist
file, with the keyio.flutter.embedded_views_preview
and the valueyes
. - 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 defaultport
value is8080
. - 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:
- 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 usingpost
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 givenassetfilepath
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 awebhistoryitem
from the back-forwardwebhistory.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 namehandlername
.removejavascripthandler({@required string handlername})
: removes a javascript message handler previously added with theaddjavascripthandler()
associated tohandlername
key.takescreenshot
: takes a screenshot (in png format) of the webview’s visible viewport and returns auint8list
. returnsnull
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 withnull
value if they are not set yet.getcopybackforwardlist
: gets thewebhistory
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 benull
.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. notifiesonfindresultreceived
listener.findnext({@required bool forward})
: highlights and scrolls to the next match found byfindallasync()
. notifiesonfindresultreceived
listener.clearmatches
: clears the highlighting surrounding text matches created byfindallasync()
.gettrexrunnerhtml
: gets the html (with javascript) of the chromium’s t-rex runner game. used in combination withgettrexrunnercss()
.gettrexrunnercss
: gets the css of the chromium’s t-rex runner game. used in combination withgettrexrunnerhtml()
.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 totrue
to be able to listen at theshouldoverrideurlloading
event. the default value isfalse
.useonloadresource
: set totrue
to be able to listen at theonloadresource
event. the default value isfalse
.useondownloadstart
: set totrue
to be able to listen at theondownloadstart
event. the default value isfalse
.useontargetblank
: set totrue
to be able to listen at theontargetblank
event. the default value isfalse
.clearcache
: set totrue
to have all the browser’s cache cleared before the new window is opened. the default value isfalse
.useragent
: sets the user-agent for the webview.applicationnameforuseragent
: append to the existing user-agent. setting useragent will override this.javascriptenabled
: set totrue
to enable javascript. the default value istrue
.debuggingenabled
: enables debugging of web contents (html / css / javascript) loaded into any webviews of this application.javascriptcanopenwindowsautomatically
: set totrue
to allow javascript open windows without user interaction. the default value isfalse
.mediaplaybackrequiresusergesture
: set totrue
to prevent html5 audio or video from autoplaying. the default value istrue
.minimumfontsize
: sets the minimum font size. the default value is8
for android,0
for ios.verticalscrollbarenabled
: define whether the vertical scrollbar should be drawn or not. the default value istrue
.horizontalscrollbarenabled
: define whether the horizontal scrollbar should be drawn or not. the default value istrue
.resourcecustomschemes
: list of custom schemes that the webview must handle. use theonloadresourcecustomscheme
event to intercept resource requests with custom scheme.contentblockers
: list ofcontentblocker
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 isinappwebviewuserpreferredcontentmode.recommended
.useshouldinterceptajaxrequest
: set totrue
to be able to listen at theshouldinterceptajaxrequest
event. the default value isfalse
.useshouldinterceptfetchrequest
: set totrue
to be able to listen at theshouldinterceptfetchrequest
event. the default value isfalse
.incognito
: set totrue
to open a browser window with incognito mode. the default value isfalse
.cacheenabled
: sets whether webview should use browser caching. the default value istrue
.transparentbackground
: set totrue
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 isfalse
.disableverticalscroll
: set totrue
to disable vertical scroll. the default value isfalse
.disablehorizontalscroll
: set totrue
to disable horizontal scroll. the default value isfalse
.
inappwebview
android-specific options
textzoom
: sets the text zoom of the page in percent. the default value is100
.clearsessioncache
: set totrue
to have the session cookie cache cleared before the new window is opened.builtinzoomcontrols
: set totrue
if the webview should use its built-in zoom mechanisms. the default value isfalse
.displayzoomcontrols
: set totrue
if the webview should display on-screen zoom controls when using the built-in zoom mechanisms. the default value isfalse
.supportzoom
: set tofalse
if the webview should not support zooming using its on-screen zoom controls and gestures. the default value istrue
.databaseenabled
: set totrue
if you want the database storage api is enabled. the default value isfalse
.domstorageenabled
: set totrue
if you want the dom storage api is enabled. the default value isfalse
.usewideviewport
: set totrue
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 istrue
.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 isfalse
.blocknetworkloads
: sets whether the webview should not load resources from the network. the default value isfalse
.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 is16
.defaultfontsize
: sets the default font size. the default value is16
.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 isandroidinappwebviewforcedark.force_dark_off
.geolocationenabled
: sets whether geolocation api is enabled. the default value istrue
.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 is8
.initialscale
: sets the initial scale for this webview. 0 means default. the behavior for the default scale depends on the state ofusewideviewport
andloadwithoverviewmode
.needinitialfocus
: tells the webview whether it needs to set a node. the default value istrue
.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 totrue
to disable the bouncing of the webview when the scrolling has reached an edge of the content. the default value isfalse
.enableviewportscale
: set totrue
to allow a viewport meta tag to either disable or restrict the range of user scaling. the default value isfalse
.suppressesincrementalrendering
: set totrue
if you want the webview suppresses content rendering until it is fully loaded into memory. the default value isfalse
.allowsairplayformediaplayback
: set totrue
to allow airplay. the default value istrue
.allowsbackforwardnavigationgestures
: set totrue
to allow the horizontal swipe gestures trigger back-forward list navigations. the default value istrue
.allowslinkpreview
: set totrue
to allow that pressing on a link displays a preview of the destination for the link. the default value istrue
.ignoresviewportscalelimits
: set totrue
if you want that the webview should always allow scaling of the webpage, regardless of the author’s intent.allowsinlinemediaplayback
: set totrue
to allow html5 media playback to appear inline within the screen layout, using browser-supplied controls rather than native controls.allowspictureinpicturemediaplayback
: set totrue
to allow html5 videos play picture-in-picture. the default value istrue
.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
: settrue
if shared cookies fromhttpcookiestorage.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 thecustom-scheme
while loading a resource. here you can handle the url request and return a customschemeresponse to load a specific resource encoded tobase64
.ontargetblank
: event fired when the inappwebview tries to open a link withtarget="_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 thealert()
method to display an alert dialog.onjsconfirm
: event fired when javascript calls theconfirm()
method to display a confirm dialog.onjsprompt
: event fired when javascript calls theprompt()
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 anxmlhttprequest
is sent to a server.onajaxreadystatechange
: event fired whenever thereadystate
attribute of anxmlhttprequest
changes.onajaxprogress
: event fired as anxmlhttprequest
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:
- android:
inappbrowser
methods
open({string url = "about:blank", map<string, string> headers = const {}, inappbrowserclassoptions options})
: opens anurl
in a newinappbrowser
instance.openfile({@required string assetfilepath, map<string, string> headers = const {}, inappbrowserclassoptions options})
: opens the givenassetfilepath
file in a newinappbrowser
instance. the other arguments are the same ofinappbrowser.open
.opendata({@required string data, string mimetype = "text/html", string encoding = "utf8", string baseurl = "about:blank", inappbrowserclassoptions options})
: opens a newinappbrowser
instance withdata
as a content, usingbaseurl
as the base url for it.openwithsystembrowser({@required string url})
: this is a static method that opens anurl
in the system browser. you wont be able to use theinappbrowser
methods here!show
: displays aninappbrowser
window that was opened hidden. calling this has no effect if theinappbrowser
was already visible.hide
: hides theinappbrowser
window. calling this has no effect if theinappbrowser
was already hidden.close
: closes theinappbrowser
window.ishidden
: check if the web view of theinappbrowser
instance is hidden.setoptions({@required inappbrowserclassoptions options})
: sets theinappbrowser
options with the newoptions
and evaluates them.getoptions
: gets the currentinappbrowser
options as amap
. returnsnull
if the options are not setted yet.isopened
: returnstrue
if theinappbrowser
instance is opened, otherwisefalse
.
inappbrowser
options
they are the same of the inappwebview
class.
specific options of the inappbrowser
class are:
inappbrowser
cross-platform options
hidden
: set totrue
to create the browser and load the page, but not show it. omit or set tofalse
to have the browser open and load normally. the default value isfalse
.toolbartop
: set tofalse
to hide the toolbar at the top of the webview. the default value istrue
.toolbartopbackgroundcolor
: set the custom background color of the toolbar at the top.hideurlbar
: set totrue
to hide the url bar on the toolbar at the top. the default value isfalse
.
inappbrowser
android-specific options
hidetitlebar
: set totrue
if you want the title should be displayed. the default value isfalse
.toolbartopfixedtitle
: set the action bar’s title.closeoncannotgoback
: set tofalse
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 istrue
.progressbar
: set tofalse
to hide the progress bar at the bottom of the toolbar at the top. the default value istrue
.
inappbrowser
ios-specific options
toolbarbottom
: set tofalse
to hide the toolbar at the bottom of the webview. the default value istrue
.toolbarbottombackgroundcolor
: set the custom background color of the toolbar at the bottom.toolbarbottomtranslucent
: set totrue
to set the toolbar at the bottom translucent. the default value istrue
.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 isioswebviewoptionspresentationstyle.full_screen
.transitionstyle
: set to the custom transition style when presenting the webview. the default value isioswebviewoptionstransitionstyle.cover_vertical
.spinner
: set tofalse
to hide the spinner when the webview is loading a page. the default value istrue
.
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 theinappbrowser
is created.onexit
: event fired when theinappbrowser
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:
- android:
chromesafaribrowser
methods
open({@required string url, chromesafaribrowserclassoptions options, map<string, string> headersfallback = const {}, inappbrowserclassoptions optionsfallback})
: opens anurl
in a newchromesafaribrowser
instance.isopened
: returnstrue
if thechromesafaribrowser
instance is opened, otherwisefalse
.
chromesafaribrowser
options
chromesafaribrowser
android-specific options
addsharebutton
: set tofalse
if you don’t want the default share button. the default value istrue
.showtitle
: set tofalse
if the title shouldn’t be shown in the custom tab. the default value istrue
.toolbarbackgroundcolor
: set the custom background color of the toolbar.enableurlbarhiding
: set totrue
to enable the url bar to hide as the user scrolls down on the page. the default value isfalse
.instantappsenabled
: set totrue
to enable instant apps. the default value isfalse
.
chromesafaribrowser
ios-specific options
entersreaderifavailable
: set totrue
if reader mode should be entered automatically when it is available for the webpage. the default value isfalse
.barcollapsingenabled
: set totrue
to enable bar collapsing. the default value isfalse
.dismissbuttonstyle
: set the custom style for the dismiss button. the default value isiossafarioptionsdismissbuttonstyle.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 isioswebviewoptionspresentationstyle.full_screen
.transitionstyle
: set to the custom transition style when presenting the webview. the default value isioswebviewoptionstransitionstyle.cover_vertical
.
chromesafaribrowser
events
onopened
: event fires when thechromesafaribrowser
is opened.onloaded
: event fires when thechromesafaribrowser
is loaded.onclosed
: event fires when thechromesafaribrowser
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 onhttp://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 givenurl
. any existing cookie with the samehost
,path
andname
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 givenurl
.getcookie({@required string url, @required string name})
: gets a cookie by itsname
for the givenurl
.deletecookie({@required string url, @required string name, string domain = "", string path = "/"})
: removes a cookie by itsname
for the givenurl
,domain
andpath
.deletecookies({@required string url, string domain = "", string path = "/"})
: removes all cookies for the givenurl
,domain
andpath
.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 thatprotectionspace
.sethttpauthcredential({@required protectionspace protectionspace, @required httpauthcredential credential})
: saves an http authcredential
for thatprotectionspace
.removehttpauthcredential({@required protectionspace protectionspace, @required httpauthcredential credential})
: removes an http authcredential
for thatprotectionspace
.removehttpauthcredentials({@required protectionspace protectionspace})
: removes all the http auth credentials saved for thatprotectionspace
.clearallauthcredentials()
: removes all the http auth credentials saved in the database.
Comments are closed.