Run some Javascript file like index.js in Flutter Webview Run some Javascript file like index.js in Flutter Webview flutter flutter

Run some Javascript file like index.js in Flutter Webview


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.