flutter_inappbrowser 2.0.1 flutter_inappbrowser: ^2.0.1 copied to clipboard
A Flutter plugin that allows you to add an inline webview or open an in-app browser window.
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 URL\n${(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.onPermissionRequest
: Event fired when the webview is requesting permission to access the specified resources and the permission currently isn't granted or denied (available only on Android).
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("\n\nBrowser Created!\n\n");
}
@override
Future onLoadStart(String url) async {
print("\n\nStarted $url\n\n");
}
@override
Future onLoadStop(String url) async {
print("\n\nStopped $url\n\n");
}
@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("\n\nBrowser closed!\n\n");
}
@override
void shouldOverrideUrlLoading(String url) {
print("\n\n override $url\n\n");
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("\n\nStarted $url\n\n");
}
@override
Future onLoadStop(String url) async {
print("\n\nStopped $url\n\n");
}
@override
void onLoadError(String url, int code, String message) {
print("\n\nCan't load $url.. Error: $message\n\n");
}
@override
void onExit() {
print("\n\nBrowser closed!\n\n");
}
}
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.