Run some Javascript in Flutter Webview

Asked
Active3 hr before
Viewed126 times

7 Answers

javascript
90%

Future<dynamic> evaluateJavascript({@required String source}): Evaluates JavaScript code into the WebView and returns the result of the evaluation.,Future<void> injectJavascriptFileFromUrl({@required String urlFile}): Injects an external JavaScript file into the WebView from a defined url.,Future<void> injectJavascriptFileFromAsset({@required String assetFilePath}): Injects a JavaScript file into the WebView from the flutter assets directory (see more here on how to load a file from the assets folder).,Well, nothing happened because flutter webview does not support javascript alert function. Try writing a javascript function that changes the value of the innerText of an HTML element and then call the function using .evalJavascript to see the result.

flutterWebviewPlugin.evalJavascript('<script language="JavaScript" type="text/javascript">
   alert("Hello World")
</script>')

expects JavaScript, not HTML

<script language="JavaScript" type="text/javascript">
   alert("Hello World")
</script>

Try

flutterWebviewPlugin.evalJavascript('alert("Hello World")')
load more v
88%

You can call this method multiple times to inject multiple JavaScript objects!,If a wildcard “*” is provided, it will inject the JavaScript object into all frames. A wildcard should only be used if the app wants any third-party web page to be able to use the injected object. When using a wildcard, the app must treat received messages as untrustworthy and validate any data carefully.,The communication must be initialized on the JavaScript side first, posting a message, so the Flutter App will have a JavaScriptReplyProxy object to respond.,It allows you to create a new message channel and send data through it via its two WebMessagePort properties:

To add a JavaScript Handler, you can use the InAppWebViewController.addJavaScriptHandler method. If you need to manage JavaScript Handlers as soon as the web page is loaded, this method should be called when the InAppWebView is created, like this:

onWebViewCreated: (controller) { // register a JavaScript handler with name "myHandlerName"  controller.addJavaScriptHandler(handlerName: 'myHandlerName', callback: (args) {    // print arguments coming from the JavaScript side!    print(args);    // return data to the JavaScript side!    return {      'bar': 'bar_value', 'baz': 'baz_value'    };  });},
load more v
72%

how I can run Javascript in the flutter_webview_plugin. I try it with this.,I have debug with iOS part of flutter_webview_plugin.,I thought with flutterWebviewPlugin.evalJavascript it is possible to run Javascript in a Webview. Do I some wrong?,Found it's related to iOS native part iOS WKWebView not showing javascript alert() dialog .

how I can run Javascript in the flutter_webview_plugin. I try it with this.

onPressed: () {
   flutterWebviewPlugin.evalJavascript('<script language="JavaScript" type="text/javascript">alert("Hello World")</script>');
},
load more v
65%

Now let’s add some functionality to call the fromFlutter method we defined in our local HTML file. ,In this article, we'll go over how to configure WebView in Flutter applications, and how to communicate between Flutter and Webview.,To do that, we will be adding a Floating Action Button (or FAB) to our layout and connecting its onPressed method to call the fromFlutter method.,All local assets in a Flutter application need to be in an assets directory.

After creating a new Flutter project, we need to use the webview_flutter package to be able to use a WebView. We will add the dependency to our pubspec.yaml file:

dependencies:
   flutter:
   sdk: flutter
webview_flutter: ^ 1.0 .7

Then, we need to run pub get in the terminal:

flutter pub get

Next, we import the package in our main.dart file:

import 'package:webview_flutter/webview_flutter.dart';

After you remove all the comments, the floating action button and everything related to it, you will be left with this (I added a text widget just for show):

import 'dart:convert';

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Communication Bridge',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Native - JS Communication Bridge'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {

  WebViewController _controller;

  @override
  Widget build(BuildContext context) {
    return Text(
      "Flutter JS-Native Communication Bridge"
    );
  }
}
<html>

    <head>
        <title>My Local HTML File</title>
    </head>

    <body>
        <h1 id="title">Hello World!</h1>
        <script type="text/javascript">
            function fromFlutter(newTitle) {
                document.getElementById("title").innerHTML = newTitle;
                sendBack();
             }

             function sendBack() {
                messageHandler.postMessage("Hello from JS");
             }
        </script>
    </body>
</html>
dependencies:
   flutter:
   sdk: flutter
webview_flutter: ^ 1.0 .7
cupertino_icons: ^ 1.0 .0

dev_dependencies:
   flutter_test:
   sdk: flutter

flutter:
   uses - material - design: true

assets:
   -assets / index.html

Since we already imported the package into our main.dart file, we need to replace the Text widget with a WebView widget:

class _MyHomePageState extends State<MyHomePage> {

  WebViewController _controller;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Webview')),
      body: WebView(
        initialUrl: 'about:blank',
        onWebViewCreated: (WebViewController webviewController) {
          _controller = webviewController;
          _loadHtmlFromAssets();
        },
      ),
    );
  }

  _loadHtmlFromAssets() async {
    String file = await rootBundle.loadString('assets/index.html');
    _controller.loadUrl(Uri.dataFromString(
        file,
        mimeType: 'text/html',
        encoding: Encoding.getByName('utf-8')).toString());
  }

}

This is also the reason behind the usage of the Scaffold widget – so we can easily add a FAB:

@override
Widget build(BuildContext context) {
   return Scaffold(
      appBar: AppBar(title: Text('Webview')),
      body: WebView(
         initialUrl: 'about:blank',
         javascriptMode: JavascriptMode.unrestricted,
         onWebViewCreated: (WebViewController webviewController) {
            _controller = webviewController;
            _loadHtmlFromAssets();
         },
      ),
      floatingActionButton: FloatingActionButton(
         child: const Icon(Icons.arrow_upward),
            onPressed: () {
               _controller.evaluateJavascript('fromFlutter("From Flutter")');
            },
      ),
   );
}

Remember how I said we will talk about the contents of our sendBack method? Let's do that now:

function sendBack() {
   messageHandler.postMessage("Hello from JS");
}

How is this object added to the JavaScript layer in our application, you might ask? By adding the JavascriptChannels attribute to our WebView widget:

class _MyHomePageState extends State<MyHomePage> {

  WebViewController _controller;
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(title: Text('Webview')),
      body: WebView(
        initialUrl: 'about:blank',
        javascriptMode: JavascriptMode.unrestricted,
        javascriptChannels: Set.from([
          JavascriptChannel(
              name: 'messageHandler',
              onMessageReceived: (JavascriptMessage message) {
               _scaffoldKey.currentState.showSnackBar(
                  SnackBar(
                      content: Text(message)
                  )
                 );
              })
        ]),
        onWebViewCreated: (WebViewController webviewController) {
          _controller = webviewController;
          _loadHtmlFromAssets();
        },
      ),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.arrow_upward),
        onPressed: () {
          _controller.evaluateJavascript('fromFlutter("From Flutter")');
        },
      ),
    );

  }
load more v
75%

In this article, we will see how to load a Webview in Flutter with Local Html and call a Javascript function inside it from Flutter.,Flutter App Development,The first thing you need is the webview plugin itself and you can get it from the below linkhttps://pub.dev/packages/webview_flutter,Below is the sample HTML code that we are going to load into the webviewI have saved this file under a folder named “files” in the root of the project.

Open pubspec.yaml file and add the dependency

dependencies: webview_flutter: ^ 1.0 .7
load more v
40%

Here is an example of how to register a JavaScript handler:,Here is an example of communication:,And then, you can dispatch the custom JavaScript event whenever and wherever you want:,CommunicationJavaScript HandlersWeb Message ChannelsWeb Message Listeners

Here is an example of how to register a JavaScript handler:

onWebViewCreated: (controller) {
   // register a JavaScript handler with name "myHandlerName"
   controller.addJavaScriptHandler(handlerName: 'myHandlerName', callback: (args) {
      // print arguments coming from the JavaScript side!
      print(args);

      // return data to the JavaScript side!
      return {
         'bar': 'bar_value',
         'baz': 'baz_value'
      };
   });
},
load more v
22%

 Webview Run Javascript Step 1 We cannot directly remove the time stamp from  Webview Run Javascript  but using the intl.dart package we can easily filter the date stamp from time stamp. So open your flutter project’s pubspec.yaml in code .

dependencies:
   flutter:
   sdk: flutter
flutter_webview_plugin: 0.3 .0 + 2
load more v

Other "javascript-undefined" queries related to "Run some Javascript in Flutter Webview"