Flutter webview alert not working

Flutter WebView Alert Not Working

When using the Flutter WebView plugin, there could be several reasons why alerts are not working. Here are some possible causes and solutions:

  1. JavaScript support: Make sure JavaScript is enabled in your WebView. You can enable it by setting the ‘javascriptMode’ property to ‘JavascriptMode.unrestricted’. Example:

WebView(
  initialUrl: 'https://example.com',
  javascriptMode: JavascriptMode.unrestricted,
)
  
  1. Alert handling: By default, WebView does not handle JavaScript alerts. You need to listen for JavaScript alerts manually and display them using Flutter’s native dialog box. Here’s an example:

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

class MyWebView extends StatefulWidget {
  @override
  _MyWebViewState createState() => _MyWebViewState();
}

class _MyWebViewState extends State {
  final flutterWebViewPlugin = FlutterWebviewPlugin();

  @override
  void initState() {
    super.initState();
    // Listen for JavaScript alerts
    flutterWebViewPlugin.onJsAlert.listen((event) {
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text(event['title']),
            content: Text(event['message']),
            actions: [
              FlatButton(
                child: Text('OK'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        },
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return WebviewScaffold(
      url: 'https://example.com',
    );
  }

  @override
  void dispose() {
    flutterWebViewPlugin.dispose();
    super.dispose();
  }
}
  

With the above code, whenever a JavaScript alert is triggered within the WebView, a native dialog box will be displayed in Flutter.

Remember to add the ‘flutter_webview_plugin’ package to your dependencies in the pubspec.yaml file and import the required libraries.

Leave a comment