Plugin that allow Flutter to communicate with a native WebView.

Last update: Aug 10, 2022

pub package

interactive_webview

Plugin that allow Flutter to communicate with a native WebView.

Warning: This is not a display WebView. This plugin is designed to make communication between Flutter and WebView javascript. You can call a Javascript function; in the other hand, you can send messgage (postMessage) from Javascript to Flutter

  • Android: using JavascriptInterface
  • iOS: using WKUserContentController

Getting Started

For help getting started with Flutter, view our online documentation.

How it works

InteractiveWebView provide a singleton instance linked to one unique webview, so you can take control of the webview from anywhere in the app. You don't need to care where is the webview. It is hidden and automatically added to the keyWindow (iOS) and decorView (Android)

Load HTML string with/without a base url

InteractiveWebView allow you to load an HTML string with different base url

final _webView = new InteractiveWebView();

_webView.loadHTML("<html><head></head><script> src='https://code.jquery.com/jquery-3.3.1.min.js'></script><body></body></html>", baseUrl: "https://www.google.com/");

by using base url, you can do some hacking work on Javascript such as embedding iframe and AJAX request from Javascript. Normally you cannot do these things if your base url is different from url you are requesting

Load url

final _webView = new InteractiveWebView();

_webView.loadUrl("https://www.google.com/");

Listen for events

final _webView = new InteractiveWebView();

_webView.stateChanged.listen((state) {
  // state.type: enum (didStatrt and didFinish)
  // state.url
});

_webView.didReceiveMessage.listen((message) {
  // message.name
  // message.data (should be a Map/List/String)
});

Call Javascript function

final _webView = new InteractiveWebView();

_webView.evalJavascript("<your javascript function>");

Set restricted schemes

Sometimes you want the webview to restrict from loading specific urls/schemes. You can archieve that by using:

final _webView = new InteractiveWebView();

_webView.setOptions(restrictedSchemes: <String>["google.com"]); // google.com will not allow to load in webview

How to post message from Javascript

As mentioned above, you can post message from Javascript to Flutter.

Both iOS and Android defined a message handler called 'native':

  • iOS: you can access this handler by using webkit.messageHandlers.native
  • Android: you can access this handler by using window.native

So you only need to check which one is available in the webview, for example:

const nativeCommunicator = typeof webkit !== 'undefined' ? webkit.messageHandlers.native : window.native;

Then you can post message to Flutter

Warning: postMessage accepts String value only. So if you want to send an object/array, you need to using JSON.stringify to convert it to JSON string. InteractiveWebView will convert it back to Map/List respectively.

// send an array data
const array = [{name: "Hello"}, 1, true, "from", "WebView!!!"];
nativeCommunicator.postMessage(JSON.stringify(array));

// send and object data
const obj = {action: "my_action", text: "Hello from WebView!!!", number: 1, bool: false};
nativeCommunicator.postMessage(JSON.stringify(obj));

// send a text data
const text = "Hello from WebView!!!";
nativeCommunicator.postMessage(text);

To listen to post message from Flutter, you can use didReceiveMessage, see Listen for events

GitHub

https://github.com/duyduong/interactive_webview
Comments
  • 1. Null print when postMessage from JS

    Hi, I was testing out your example and it worked totally fine but when I tried to modify the JS script inside the html file I encountered this problem when I try to send back to flutter the modified data. Do you know why happens this or any way to solve it? I tried also declaring global variables and storing the 'text' variable inside but nothing, still sends null.

    Perhaps the stateChanged WebViewState.didFinish event has something to do?

    Thank you!

    index.html

    <script>
        const nativeCommunicator = typeof webkit !== 'undefined' ? webkit.messageHandlers.native : window.native;
        function test(text) {
          var s = text + "123";
          console.log(s);
          nativeCommunicator.postMessage(JSON.stringify(s));
          //nativeCommunicator.postMessage(s);
        }
    </script>
    

    Output

    I/flutter ( 9409): stateChanged WebViewState.didStart http://bilutv.net/
    I/flutter ( 9409): stateChanged WebViewState.didFinish http://bilutv.net/
    I/chromium( 9409): [INFO:CONSOLE(11)] "Hello from Native!!!123", source: http://bilutv.net/ (11)
    I/flutter ( 9409): null             <--- THAT nativeCommunicator.postMessage
    
    Reviewed by cTatu at 2019-01-08 12:46
  • 2. generic example

    This is really useful for running differnt background code. Can you make a genric example showing messages flowing back and forth. Please include the html and javascript in the example.

    Reviewed by ghost at 2018-11-11 15:01
  • 3. Long Running Javascript does not continue running in the background on iOS

    I'm using an interactive webview to run a javascript library in the background of my flutter app. On android this long running library works just great, but on iOS it seems that the webview stops running, and stops being able to respond to evalJavascript. Are there different "rules" on iOS compared to Android when it comes to webviews in the background?

    My code is here if you are interested: https://pastebin.com/evfJ21Qs

    Reviewed by singerbj at 2019-11-25 22:22
  • 4. postMessage from Javascript is not getting captured in the Flutter

    Messages from the Javascript to Webview( Flutter ) are not received. I have tried sending events like:

    window.postMessage('data');
    postMessage('data');
    

    I am expecting them to be received in the below callback:

    jsWebview.didReceiveMessage.listen((message) {
          print(message.data);
        });
    
    

    However, it is never received on the flutter end. Although, the communication from the flutter to javascript works.

    Reviewed by saarang1995 at 2019-12-29 12:06
  • 5. Kotlin version

    FAILURE: Build failed with an exception.
    
    * What went wrong:
    The Android Gradle plugin supports only Kotlin Gradle plugin version 1.3.0 and higher.
    The following dependencies do not satisfy the required version:
    project ':interactive_webview' -> org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.71
    
    Reviewed by ScottEAdams at 2019-02-08 00:31
  • 6. localStorage

    I/chromium( 3269): [INFO:CONSOLE(1)] "Uncaught SecurityError: Failed to read the 'localStorage' property from 'Window': Storage is disabled inside 'data:' URLs." How can i fix it?

    Reviewed by Gorniv at 2019-02-14 20:42
  • 7. Modularize JS files

    Hi, I'm using a JS API and I'm wondering if I can use a single .js file from the 'asset' folder wit all my functions instead of the index.html file. Or at least be able to import a js file from the assets folder inside the index.html.

    Thank you and nice work! 😉

    Reviewed by cTatu at 2019-01-05 15:35
  • 8. WSS connections not supported in iOS

    Hi. I have a html file that creates a new instance of the deepstream.io client library with the endpoint of a secure web socket connection as its argument. While this is running without any problem on Android, iOS does not connect. Can you confirm that wss is supposed to work for iOS in this plugin ? If this is expected behavior, is there a way to enable wss inside the interactive webview ? Thank you !

    Reviewed by HeikoMueller at 2020-05-04 00:01
  • 9. `interactive_webview` does not specify a Swift version

    When I try to run on IOS I get this error

        [!] Unable to determine Swift version for the following pods:
    
        - `interactive_webview` does not specify a Swift version and none of the targets (`Runner`) integrating it have the `SWIFT_VERSION` attribute set. Please contact the
        author or set the `SWIFT_VERSION` attribute in at least one of the targets that integrate this pod.
    
        /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.7.1/lib/cocoapods/installer/xcode/target_validator.rb:122:in `verify_swift_pods_swift_version'
        /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.7.1/lib/cocoapods/installer/xcode/target_validator.rb:37:in `validate!'
        /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.7.1/lib/cocoapods/installer.rb:578:in `validate_targets'
        /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.7.1/lib/cocoapods/installer.rb:158:in `install!'
        /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.7.1/lib/cocoapods/command/install.rb:51:in `run'
        /Library/Ruby/Gems/2.3.0/gems/claide-1.0.2/lib/claide/command.rb:334:in `run'
        /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.7.1/lib/cocoapods/command.rb:52:in `run'
        /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.7.1/bin/pod:55:in `<top (required)>'
        /usr/local/bin/pod:22:in `load'
    
    Reviewed by abozanona at 2020-01-02 20:07
  • 10. Native code must call result callback

    Currently the native code is not returning a future to flutter. If you call await loadUrl, the await never gets resolved. This simple fix will properly return from native code.

    Reviewed by tmorone-rezi at 2019-11-08 14:18
  • 11. how to reference another JS file in one JS file

    Hello, first of all, I initially used it on Android, which really surprised me. Then I want to ask a question, how to reference another JS file in one JS

    Reviewed by zhubinsheng at 2020-07-01 09:11
  • 12. Can it be used with flutter_webview_plugin?

    it cant work for me. `import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_webview_plugin/flutter_webview_plugin.dart'; import 'package:interactive_webview/interactive_webview.dart';

    const String url = 'http://192.168.1.3:3000';

    void main() { runApp(MyApp()); }

    class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( // This is the theme of your application. // // Try running your application with "flutter run". You'll see the // application has a blue toolbar. Then, without quitting the app, try // changing the primarySwatch below to Colors.green and then invoke // "hot reload" (press "r" in the console where you ran "flutter run", // or simply save your changes to "hot reload" in a Flutter IDE). // Notice that the counter didn't reset back to zero; the application // is not restarted. primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } }

    class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key);

    // This widget is the home page of your application. It is stateful, meaning // that it has a State object (defined below) that contains fields that affect // how it looks.

    // This class is the configuration for the state. It holds the values (in this // case the title) provided by the parent (in this case the App widget) and // used by the build method of the State. Fields in a Widget subclass are // always marked "final".

    final String title;

    @override _MyHomePageState createState() => _MyHomePageState(); }

    class _MyHomePageState extends State { final _webView = new InteractiveWebView();

    @override void initState() { super.initState(); init(); }

    init() async { _webView.stateChanged.listen((state) { print('------------------------'); print(state); }); _webView.didReceiveMessage.listen((message) { print('-----------------------'); print(message.data.toString()); }); _webView.loadUrl(url); }

    @override Widget build(BuildContext context) { return Scaffold( body: Padding( padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top), child: Column( children: [ Row( children: [ RaisedButton( onPressed: () async {}, child: Text('back'), ), ], ), Expanded( child: WebviewScaffold( url: url, clearCache: true, )) ], ), ), ); } } `

    Reviewed by lyqiai at 2019-06-23 05:05
  • 13. Xcode Version 10.1 Supported values are: 3.0, 4.0, 4.2.

    Xcode Version 10.1

    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. This setting can be set in the build settings editor.

    Reviewed by iBinbro at 2019-01-23 07:04

Related

A simplistic mobile application with Material design that helps you communicate using different phonetic alphabets
A simplistic mobile application with Material design that helps you communicate using different phonetic alphabets

Speak NATO A simplistic mobile application with Material design that helps you communicate using different phonetic alphabets. Installation Screenshot

Oct 9, 2021
dna, dart native access. A lightweight dart to native super channel plugin

dna, dart native access. A lightweight dart to native super channel plugin, You can use it to invoke any native code directly in contextual and chained dart code.

Jul 11, 2022
A complete tutorial series on Flutter webview.
A complete tutorial series on Flutter webview.

Flutter Webview | Tech With Sam Flutter Webview Tutorial - Watch on youtube ✌   App Preview App Screenshot App Screenshot A new Flutter project. Getti

Aug 5, 2022
Tech News Application by Flutter WebView .
Tech News Application by Flutter WebView .

Tech News APP developed by flutter_web_view Tech News developed by Flutter (Dart) it is a simple WebView that run on Android & iOS. *New changes: Migr

Oct 31, 2021
A feature-rich cross-platform webview using webview_flutter for mobile and iframe for web. JS interop-ready.
A feature-rich cross-platform webview using webview_flutter for mobile and iframe for web. JS interop-ready.

A feature-rich cross-platform webview using webview_flutter for mobile and iframe for web. JS interop-ready. Getting started Gallery Basic usage Featu

Mar 17, 2022
A Flutter plugin than allow expand and collapse text dynamically
A Flutter plugin than allow expand and collapse text dynamically

readmore A Flutter plugin than allow expand and collapse text. usage: add to your pubspec readmore: ^1.0.2 and import: import 'package:readmore/readm

Aug 7, 2022
how to Integrating facebook audience network to flutter app for banner, interstitial, rewarded, native and native banner

fb_ads_flutter_12 A new Flutter project. Getting Started Watch the complite tutorial for integrating Facebook ads into the Flutter app in our Youtube

Jul 30, 2022
Flutter native ads - Show AdMob Native Ads use PlatformView
Flutter native ads - Show AdMob Native Ads use PlatformView

flutter_native_ads Flutter plugin for AdMob Native Ads. Compatible with Android and iOS using PlatformView. Android iOS Getting Started Android Androi

May 25, 2022
react-native native module for In App Purchase.
react-native native module for In App Purchase.

Documentation Published in website. Announcement Version 8.0.0 is currently in release candidate. The module is completely rewritten with Kotlin and S

Aug 10, 2022
Now UI Flutter is a fully coded app template built for Flutter which will allow you to create powerful and beautiful e-commerce mobile applications
Now UI Flutter is a fully coded app template built for Flutter which will allow you to create powerful and beautiful e-commerce mobile applications

Now UI Flutter is a fully coded app template built for Flutter which will allow you to create powerful and beautiful e-commerce mobile applications. We have redesigned all the usual components to make it look like our Now UI Design, minimalistic and easy to use.

Jul 7, 2022
A Flutter package that extends IndexedStack to allow for lazy loading.

lazy_load_indexed_stack A package that extends IndexedStack to allow for lazy loading. Motivation If you use the IndexedStack with bottom navigation,

Aug 1, 2022
Leverages libphonenumber to allow for asynchronous and synchronous formatting of phone numbers in Flutter apps
Leverages libphonenumber to allow for asynchronous and synchronous formatting of phone numbers in Flutter apps

Leverages libphonenumber to allow for asynchronous and synchronous formatting of phone numbers in Flutter apps. Includes a TextInputFormatter to allow real-time AsYouType formatting.

May 19, 2022
Flutter application for latest news by top newspapers . And allow for share articles with friends. Now available in night mode. Also landscape mode is available
Flutter application for latest news by top newspapers . And allow for share articles with friends. Now available in night mode. Also landscape mode is available

Breaking News Latest news for almost 55 country. Feature of saving article and search ariticles. Used API https://newsapi.org/ Note: if data is not ge

Mar 30, 2022
shared_versions is a command line tool that allow share the versions for multiple packages in Flutter

shared_versions shared_versions is a CLI tool that allow share the versions for multiple packages in Flutter. Usage shared_versions will match the pac

Apr 1, 2022
Flutter package for Android and iOS allow you to show a wide range of hyperlinks either in the input field or in an article view
Flutter package for Android and iOS allow you to show a wide range of hyperlinks either in the input field or in an article view

Tagtly package help you to detect a lot of hyperlink text such as.. email, url, social media tags, hashtag and more either when user type in text field or when appear a text read only.

Jul 25, 2022
The Integration Test Helper has pre-configured methods that allow for faster test deployment for end to end (e2e) test coverage.
The Integration Test Helper has pre-configured methods that allow for faster test deployment for end to end (e2e) test coverage.

The Integration Test Helper has pre-configured methods that allow for faster test deployment for end to end (e2e) test coverage (using Android and iOS

Apr 7, 2022
FlutterBoost is a Flutter plugin which enables hybrid integration of Flutter for your existing native apps with minimum efforts
FlutterBoost is a Flutter plugin which enables hybrid integration of Flutter for your existing native apps with minimum efforts

中文文档 中文介绍 Release Note v3.0-preview.17 PS: Before updating the beta version, please read the CHANGELOG to see if there are any BREAKING CHANGE Flutter

Aug 8, 2022
A Flutter plugin for authenticating users by using the native TwitterKit SDKs on Android & iOS.

flutter_twitter_login A Flutter plugin for using the native TwitterKit SDKs on Android and iOS. This plugin uses the new Gradle 4.1 and Android Studio

May 3, 2022
A flutter plugin for retrieving, creating, saving, and watching contacts on native devices

flutter_contact A Flutter plugin to access and manage the device's native contacts. Usage To use this plugin, add flutter_contact as a dependency in y

Jul 28, 2022