7

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

flutterWebViewPlugin.evalJavascript("require('./index.js');");

But nothing happens.

when I try to run flutter code it's shows nothing

my index.Js file contains a simple alert statement

alert('hello world');
Kashif Ahmed
  • 803
  • 9
  • 20

1 Answers1

2

First, You used "require" function. this function is not implemented in javascript itself. it's a part of NodeJs. so that function will not work.

In order to load a js file into flutter, you should consider it as a text file and load it properly. So, you need to add the file to assets folder, add into pubspec file, then load it. read the full answer here

Second, you used evalJavascript. this function can be used in many different situations. but it will work only if you have a view panel.

Check below example:

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';

main() async {
  String jsCode = await rootBundle.loadString('assets/javascript.js');

  runApp(new MaterialApp(
    home: LunchWebView(jsCode),
  ));
}

class LunchWebView extends StatelessWidget {
  final String text;
  LunchWebView(this.text);

  @override
  Widget build(BuildContext context) {
    final FlutterWebviewPlugin flutterWebviewPlugin = FlutterWebviewPlugin();
    flutterWebviewPlugin.launch('https://www.google.com');
    flutterWebviewPlugin.evalJavascript(text);
    return Container();
  }
}

NOTE: : I didn't handle reloading and other exceptions. you should check if there is any webview object open and then call Lunch method.

Yamin
  • 2,868
  • 1
  • 19
  • 22