Run some Javascript file like index.js in Flutter Webview

1,968

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.

Share:
1,968
Kashif Ahmed
Author by

Kashif Ahmed

I'm a Creative Mobile App Developer, Self-motivated and Results-oriented professional with proven leadership, interpersonal and problem-solving skills. I love to keep my hands dirty in coding, designing solutions, code review & in most of all kind of tech work. I'm skilled at project delivery, project management, methodologies, training, mentoring, assessments, and quality reviews. I have an extensive experience of developing innovative and complex Mobile Apps.

Updated on December 11, 2022

Comments

  • Kashif Ahmed
    Kashif Ahmed over 1 year

    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');