How To Enable Disable Javascript In Flutter Webview

admin_img Posted By Bajarangi soft , Posted On 27-11-2020

Flutter’s official WebView plugin comes with an amazing feature which is called enabling and disabling JavaScript in WebView. WebView plugin has a property named as javascriptMode which has 2 parameters JavascriptMode.disabled and JavascriptMode.unrestricted.

How To Enable Disable Javascript In Flutter Webview

Enable Disable Javascript Flutter WebView
Step 1 We cannot directly remove the time stamp from Enable Disable Javascript Flutter WebView 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
  webview_flutter: ^1.0.7

Step 2
After done saving the pubspec.yaml file, Open your flutter project root folder in Command Prompt or Terminal and execute flutter pub get command. 

flutter pub get


Complete Code For Enable Disable Javascript Flutter WebView In Flutter
main.dart
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:webview_flutter/webview_flutter.dart';


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

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  bool _isJSEnabled = false;

  _onChanged() {
    setState(() {
      _isJSEnabled = !_isJSEnabled;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          backgroundColor: Colors.indigo,
          title: Text("Enable / Disable JS In WEbview")),
      body: Stack(
        children: [
          WebView(
            initialUrl: 'https://bajarangisoft.com',
            javascriptMode: _isJSEnabled
                ? JavascriptMode.unrestricted
                : JavascriptMode.disabled,
          ),
          Positioned(
            child: Align(
              alignment: Alignment.bottomCenter,
              child: RaisedButton(
                child: Text(_isJSEnabled ? "Disable JS" : "Enable JS"),
                color: Colors.indigo,
                textColor: Colors.white,
                onPressed: _onChanged,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

 

Related Post