Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

alert() method doesn't work in WebView #30358

Closed
yumi0629 opened this issue Apr 2, 2019 · 28 comments · Fixed by flutter/packages#5670
Closed

alert() method doesn't work in WebView #30358

yumi0629 opened this issue Apr 2, 2019 · 28 comments · Fixed by flutter/packages#5670
Labels
found in release: 3.10 Found to occur in 3.10 found in release: 3.11 Found to occur in 3.11 has reproducible steps The issue has been confirmed reproducible and is ready to work on p: webview The WebView plugin P3 Issues that we currently consider unimportant package flutter/packages repository. See also p: labels. platform-android Android applications specifically platform-ios iOS applications specifically platform-views: vd Issues specific to the Android VirtualDisplay platform views backend r: fixed Issue is closed as already fixed in a newer version team-ecosystem Owned by Ecosystem team triaged-ecosystem Triaged by Ecosystem team

Comments

@yumi0629
Copy link

yumi0629 commented Apr 2, 2019

I use the plugin webview_flutter to load a html page below:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <title>Amaze UI 在线调试</title>
  <link rel="stylesheet" href="http://cdn.amazeui.org/amazeui/2.5.0/css/amazeui.min.css"/>
</head>
<body>
  <button onclick="alert(123456)">alert</button>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://cdn.amazeui.org/amazeui/2.5.0/js/amazeui.min.js"></script>
</body>
</html>

But when I click the button "alert", the alert dialog doesn't show in Flutter. I open the html in Chrome, everything works well.

Does alert() method not support in Flutter?

output of flutter doctor -v:

[✓] Flutter (Channel beta, v1.3.8, on Mac OS X 10.13.6 17G65, locale zh-Hans-CN)
• Flutter version 1.3.8 at /Users/yumi/Library/Android/flutter
• Framework revision e5b1ed7 (4 weeks ago), 2019-03-06 14:23:37 -0800
• Engine revision f4951df
• Dart version 2.2.1 (build 2.2.1-dev.0.0 571ea80e11)

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
• Android SDK at /Users/yumi/Library/Android/sdk
• Android NDK location not configured (optional; useful for native profiling
support)
• Platform android-28, build-tools 28.0.3
• ANDROID_HOME = /Users/yumi/Library/Android/sdk
• Java binary at: /Applications/Android
Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build
1.8.0_152-release-1248-b01)
• All Android licenses accepted.

[✓] iOS toolchain - develop for iOS devices (Xcode 9.4.1)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 9.4.1, Build version 9F2000
• ios-deploy 2.0.0
• CocoaPods version 1.5.3

[✓] Android Studio (version 3.3)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin version 31.3.3
• Dart plugin version 182.5215
• Java version OpenJDK Runtime Environment (build
1.8.0_152-release-1248-b01)

[✓] Connected device (2 available)
• M5 Note • 621QECQP4P2HM • android-arm64 • Android 7.0 (API 24)
• VKY AL00 • WJX7N17815008179 • android-arm64 • Android 7.0 (API 24)

@ushang000

This comment was marked as off-topic.

@xuyu461989426
Copy link

alert&confirm currently are not supported in webview_flutter , if u want it working , you must rebuild webview_flutter on native platform library or don't use alert in html(use self-build alert instead)

@jerryzhoujw

This comment was marked as off-topic.

@escamoteur

This comment was marked as off-topic.

@iapicca
Copy link
Contributor

iapicca commented Jan 14, 2020

Hi @yumi0629
are you referring to the first party plugin webview_flutter or the third party flutter_webview_plugin?
If the latter you may want to open an issue in the dedicated github, otherwise,
if you are still experiencing the issue with the latest stable version of Flutter
please provide your update flutter doctor -v
and your flutter run --verbose?
Also, to better address the issue, would be helpful
if you could post a reproducible minimal code sample
or the steps to reproduce the problem.
Thank you

@iapicca iapicca added waiting for customer response The Flutter team cannot make further progress on this issue until the original reporter responds platform-android Android applications specifically labels Jan 14, 2020
@simpleblack
Copy link

When i using alert, I had a good experience.

onPageFinished: (url) async {
  try {
    var javascript = '''
      window.alert = function (e){
        Alert.postMessage(e);
      }
    ''';
    await _webViewController?.evaluateJavascript(javascript);
  } catch (_) {}
  setState(() {
     isLoading = false;
   });
},
JavascriptChannel(
  name: 'Alert',
  onMessageReceived: (JavascriptMessage message) {
    // TODO popup
  },
 )

@deandreamatias
Copy link

When i using alert, I had a good experience.

onPageFinished: (url) async {
  try {
    var javascript = '''
      window.alert = function (e){
        Alert.postMessage(e);
      }
    ''';
    await _webViewController?.evaluateJavascript(javascript);
  } catch (_) {}
  setState(() {
     isLoading = false;
   });
},
JavascriptChannel(
  name: 'Alert',
  onMessageReceived: (JavascriptMessage message) {
    // TODO popup
  },
 )

What is your configuration?
You try whit popup directly in web site?

@simpleblack
Copy link

@deandreamatias
Reconfigure alert on your website to use as channel.

@deandreamatias
Copy link

@deandreamatias
Reconfigure alert on your website to use as channel.

The website isn't mine :/

@simpleblack
Copy link

@deandreamatias
It's okay if it's not my website.

It is important to reconstruct window.alert

var javascript = '''
  window.alert = function (str){
    Alert.postMessage(str);
  }
''';
await _webViewController?.evaluateJavascript(javascript);

Example Code

WebView(
  initialUrl: 'https://flutter.dev',
  javascriptMode: JavascriptMode.unrestricted,
  onWebViewCreated: (controller) {
    _webViewController = controller;
  },
  onPageFinished: (url) async {
    try {
      var javascript = '''
            window.alert = function (str){
              Alert.postMessage(str);
            }
          ''';
      await _webViewController?.evaluateJavascript(javascript);
    } catch (_) {}

    try {
      var testAlert = '''
            alert('Test alert Message');
          ''';
      await _webViewController?.evaluateJavascript(testAlert);
    } catch (_) {}
  },
  javascriptChannels: Set.from(
    [
      JavascriptChannel(
        name: 'Alert',
        onMessageReceived: (JavascriptMessage message) {
          // alert message = Test alert Message
          print(message.message)
          // TODO popup
        },
      )
    ],
  ),
),

@iapicca iapicca added customer: crowd Affects or could affect many people, though not necessarily a specific customer. and removed customer: crowd Affects or could affect many people, though not necessarily a specific customer. labels Jan 30, 2020
@iapicca
Copy link
Contributor

iapicca commented Feb 21, 2020

Without additional information, we are unfortunately not sure how to resolve this issue. We are therefore reluctantly going to close this bug for now. Please don't hesitate to comment on the bug if you have any more information for us; we will reopen it right away!
Thanks for your contribution.

Could everyone who still has this problem please file a new issue with the exact descriptions what happens, logs and the output of 'flutter doctor -v' please.
All system setups can be slightly different so it's always better to open new issues and reference related issues.

@iapicca iapicca closed this as completed Feb 21, 2020
@andynvt
Copy link

andynvt commented Apr 17, 2020

When i using alert, I had a good experience.

onPageFinished: (url) async {
  try {
    var javascript = '''
      window.alert = function (e){
        Alert.postMessage(e);
      }
    ''';
    await _webViewController?.evaluateJavascript(javascript);
  } catch (_) {}
  setState(() {
     isLoading = false;
   });
},
JavascriptChannel(
  name: 'Alert',
  onMessageReceived: (JavascriptMessage message) {
    // TODO popup
  },
 )

Thank you, you save my life.
For further information, I try to handle alert showing in webview. But no hope. There is another plugin here from community that solved the alert and show it with native alert dialog. You guys can check it here: https://pub.dev/packages/flutter_webview_plugin

But, in my case. I need an widget-webview just like webview_flutter. And then I can also handle the alert() in webview through onMessageReceived as Mr. @simpleblack mentioned. Thank you again.

From here, you guys can you Flutter showDialog with AlertDialog as normal.

@shinriyo
Copy link

@andynvt wow!! it is good ida.
but, confirm can't get return value.

window.confirm = function(str) {
  if (typeof Confirm !== 'undefined') {
    Confirm.postMessage(str);
  }
};
    return JavascriptChannel(
      name: 'Confirm',
      onMessageReceived: (JavascriptMessage message) async {
    return showDialog<bool>(
      context: context,
      builder: (_) {
        return AlertDialog(
          content: Text(message.message),
          actions: <Widget>[
            FlatButton(
              child: Text("Cancel"),
              onPressed: () {
                Navigator.pop(context, false);
              },
            ),
            FlatButton(
              child: Text("OK"),
              onPressed: () {
                Navigator.pop(context, true);
              },
            ),
          ],
        );
      },
    );
  
        // true / false
        print(a);
      },
    );

@pedromassangocode pedromassangocode removed the waiting for customer response The Flutter team cannot make further progress on this issue until the original reporter responds label Oct 21, 2020
@ostup17

This comment was marked as off-topic.

@dam-ease
Copy link

I am able to reproduce this issue on the latest master and stable channels using the latest version of the webview_flutter package (webview_flutter: ^4.2.0).

Code Sample

import 'dart:io';

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late final WebViewController _webViewController;

  @override
  void initState() {
    super.initState();
    _webViewController = WebViewController()
      ..loadRequest(Uri.dataFromString(_html, mimeType: 'text/html'));
  }

  final String _html = """
  <!DOCTYPE html>
  <html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>Amaze UI</title>
    <link rel="stylesheet" href="http://cdn.amazeui.org/amazeui/2.5.0/css/amazeui.min.css"/>
  </head>
  <body>
    <button onclick="alert(123456)">alert</button>
  <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
  <script src="http://cdn.amazeui.org/amazeui/2.5.0/js/amazeui.min.js"></script>
  </body> 
  </html>
  """;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: WebViewWidget(controller: _webViewController),
    );
  }
}

flutter doctor -v
[✓] Flutter (Channel master, 3.11.0-2.0.pre.55, on macOS 13.3 22E252 darwin-arm64, locale en-NG)
    • Flutter version 3.11.0-2.0.pre.55 on channel master at /Users/dammya/fvm/versions/master
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 835b892d7f (12 days ago), 2023-05-07 01:30:22 +0530
    • Engine revision 23f730efbf
    • Dart version 3.1.0 (build 3.1.0-83.0.dev)
    • DevTools version 2.23.1

[✓] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
    • Android SDK at /Users/dammya/Library/Android/sdk
    • Platform android-33, build-tools 32.1.0-rc1
    • ANDROID_HOME = /Users/dammya/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.3)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14E222b
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)

[✓] IntelliJ IDEA Community Edition (version 2022.3.2)
    • IntelliJ at /Applications/IntelliJ IDEA CE.app
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart

[✓] VS Code (version 1.78.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.50.0

[✓] VS Code (version 1.78.0)
    • VS Code at /Users/dammya/.Trash/Visual Studio Code 20.07.05.app/Contents
    • Flutter extension version 3.50.0

[✓] Connected device (4 available)
    • sdk gphone arm64 (mobile)  • emulator-5554                        • android-arm64  • Android 11 (API 30) (emulator)
    • iPhone 14 Pro Max (mobile) • D7F3302D-D66F-4B89-B8CF-DBEE1CDB5449 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-16-4 (simulator)
    • macOS (desktop)            • macos                                • darwin-arm64   • macOS 13.3 22E252 darwin-arm64
    • Chrome (web)               • chrome                               • web-javascript • Google Chrome 113.0.5672.126

[✓] Network resources
    • All expected network resources are available.

• No issues found!
[✓] Flutter (Channel stable, 3.10.1, on macOS 13.3 22E252 darwin-arm64, locale en-NG)
    • Flutter version 3.10.1 on channel stable at /Users/dammya/sdks/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision d3d8effc68 (31 hours ago), 2023-05-16 17:59:05 -0700
    • Engine revision b4fb11214d
    • Dart version 3.0.1
    • DevTools version 2.23.1

[✓] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
    • Android SDK at /Users/dammya/Library/Android/sdk
    • Platform android-33, build-tools 32.1.0-rc1
    • ANDROID_HOME = /Users/dammya/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.3)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14E222b
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.12+0-b1504.28-7817840)

[✓] IntelliJ IDEA Community Edition (version 2022.3.2)
    • IntelliJ at /Applications/IntelliJ IDEA CE.app
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart

[✓] VS Code (version 1.78.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.50.0

[✓] VS Code (version 1.78.0)
    • VS Code at /Users/dammya/.Trash/Visual Studio Code 20.07.05.app/Contents
    • Flutter extension version 3.50.0

[✓] Connected device (4 available)
    • sdk gphone arm64 (mobile)  • emulator-5554                        • android-arm64  • Android 11 (API 30) (emulator)
    • iPhone 14 Pro Max (mobile) • D7F3302D-D66F-4B89-B8CF-DBEE1CDB5449 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-16-4 (simulator)
    • macOS (desktop)            • macos                                • darwin-arm64   • macOS 13.3 22E252 darwin-arm64
    • Chrome (web)               • chrome                               • web-javascript • Google Chrome 113.0.5672.126

[✓] Network resources
    • All expected network resources are available.

• No issues found!

@dam-ease dam-ease added package flutter/packages repository. See also p: labels. found in release: 3.10 Found to occur in 3.10 found in release: 3.11 Found to occur in 3.11 and removed found in release: 2.2 Found to occur in 2.2 found in release: 2.5 Found to occur in 2.5 labels May 19, 2023
@flutter-triage-bot flutter-triage-bot bot added P3 Issues that we currently consider unimportant and removed P6 labels Jun 28, 2023
@Hixie Hixie removed the plugin label Jul 6, 2023
@flutter-triage-bot flutter-triage-bot bot added multiteam-retriage-candidate team-ecosystem Owned by Ecosystem team triaged-ecosystem Triaged by Ecosystem team labels Jul 8, 2023
@phamquoctrongnta

This comment was marked as off-topic.

@stuartmorgan
Copy link
Contributor

stuartmorgan commented Jul 21, 2023

For anyone interested in working on this, the approach we would want to take is to delegate the alert information to the plugin client via a Dart callback, rather than implementing a specific native UI. (If someone wants native UI, they can then implement that callback by calling a plugin that shows native dialogs.)

@tomonori-sakieda-iplug

This comment was marked as off-topic.

auto-submit bot pushed a commit to flutter/packages that referenced this issue Dec 19, 2023
…5670)

Adds the platform interface implementation for JavaScript dailog.

This PR is part of a series of PRs that aim to close flutter/flutter#30358 (comment)
The PR that contains all changes can be found at #4704
@dam-ease dam-ease added the r: fixed Issue is closed as already fixed in a newer version label Dec 20, 2023
ChopinDavid pushed a commit to wwt/flutter-packages that referenced this issue Dec 28, 2023
…lutter#5670)

Adds the platform interface implementation for JavaScript dailog.

This PR is part of a series of PRs that aim to close flutter/flutter#30358 (comment)
The PR that contains all changes can be found at flutter#4704
Copy link

github-actions bot commented Jan 3, 2024

This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v and a minimal reproduction of the issue.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Jan 3, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
found in release: 3.10 Found to occur in 3.10 found in release: 3.11 Found to occur in 3.11 has reproducible steps The issue has been confirmed reproducible and is ready to work on p: webview The WebView plugin P3 Issues that we currently consider unimportant package flutter/packages repository. See also p: labels. platform-android Android applications specifically platform-ios iOS applications specifically platform-views: vd Issues specific to the Android VirtualDisplay platform views backend r: fixed Issue is closed as already fixed in a newer version team-ecosystem Owned by Ecosystem team triaged-ecosystem Triaged by Ecosystem team
Projects
None yet
Development

Successfully merging a pull request may close this issue.