Skip to content

[webview_flutter] Can not invoke Javascript function on iOS #128489

Closed as not planned

Description

@TarunRaxa

Is there an existing issue for this?

Steps to reproduce

This package work perfectly fine on android but for ios I am getting crash when I runJavaScript from webview. This happens only on iOS Side. For android I am able to send and receive data between js and flutter.

I am using latest version of package.

And the error at ios side is -

Unhandled Exception: PlatformException(FWFEvaluateJavaScriptError, Failed evaluating JavaScript., Instance of 'NSError', null)
#0      WKWebViewHostApiImpl.evaluateJavaScriptForInstances (package:webview_flutter_wkwebview/src/web_kit/web_kit_api_impls.dart:1050:7)
<asynchronous suspension>
#1      WebKitWebViewController.runJavaScript (package:webview_flutter_wkwebview/src/webkit_webview_controller.dart:385:7)
<asynchronous suspension>
#2      _WebViewExampleState.build.<anonymous closure> (package:my_rich_editor/web_view.dart:252:11)
<asynchronous suspension>

Expected results

Expected result I should runJavaScript from ios side too.

Actual results

Actually it is not sending data from js to flutter

Code sample

Code sample
WebViewController controller = WebViewController();
controller
    ..setJavaScriptMode(JavaScriptMode.unrestricted)
    ..setBackgroundColor(const Color(0x00000000))
    ..addJavaScriptChannel(
      'GetAppCurrentLanguage',
      onMessageReceived: (JavaScriptMessage message) {
        print('GetAppCurrentLanguage');
        String languageCode = "en";
             },
    )
   ..loadFlutterAsset('assets/demo.html');

Screenshots or Video

Screenshots / Video demonstration

[Upload media here]

Logs

Logs
Unhandled Exception: PlatformException(FWFEvaluateJavaScriptError, Failed evaluating JavaScript., Instance of 'NSError', null)
#0      WKWebViewHostApiImpl.evaluateJavaScriptForInstances (package:webview_flutter_wkwebview/src/web_kit/web_kit_api_impls.dart:1050:7)
<asynchronous suspension>
#1      WebKitWebViewController.runJavaScript (package:webview_flutter_wkwebview/src/webkit_webview_controller.dart:385:7)
<asynchronous suspension>
#2      _WebViewExampleState.build.<anonymous closure> (package:my_rich_editor/web_view.dart:252:11)
<asynchronous suspension>

Flutter Doctor output

Doctor output
Flutter (Channel stable, 3.10.3, on macOS 13.0.1 22A400 darwin-arm64, locale en-IN)
[!] Android toolchain - develop for Android devices (Android SDK version 33.0.1)
    ✗ cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`
      See https://developer.android.com/studio/command-line for more details.
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/macos#android-setup for more details.
[✓] Xcode - develop for iOS and macOS (Xcode 14.1)
[✓] Chrome - develop for the web
[!] Android Studio (not installed)
[✓] VS Code (version 1.78.2)
[✓] Connected device (3 available)
[✓] Network resources

Activity

  1. added
    in triagePresently being triaged by the triage team
    on Jun 8, 2023
  2. huycozy commented on Jun 8, 2023

    @huycozy
    Member

    Can you please share the complete sample code (a runnable single main.dart file) so that we may verify the issue properly?

  3. added
    waiting for responseThe Flutter team cannot make further progress on this issue until the original reporter responds
    on Jun 8, 2023
  4. removed
    waiting for responseThe Flutter team cannot make further progress on this issue until the original reporter responds
    on Jun 8, 2023
  5. TarunRaxa commented on Jun 8, 2023

    @TarunRaxa
    Author

    //main.dart

    import 'package:flutter/material.dart';
    import 'package:webview_flutter/webview_flutter.dart';
    
    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: const WebViewDemo(),
        );
      }
    }
    
    class WebViewDemo extends StatefulWidget {
      const WebViewDemo({super.key});
    
      @override
      State<WebViewDemo> createState() => _WebViewDemoState();
    }
    
    class _WebViewDemoState extends State<WebViewDemo> {
      WebViewController controller = WebViewController();
    
      @override
      void initState() {
        super.initState();
        controller
          ..setJavaScriptMode(JavaScriptMode.unrestricted)
          ..setBackgroundColor(const Color(0x00000000))
          ..addJavaScriptChannel(
            'Toaster',
            onMessageReceived: (JavaScriptMessage message) {
              print(message.message);
              print('Toaster Flutter Mobile');
            },
          )
          ..setNavigationDelegate(NavigationDelegate(
            onProgress: (int progress) {
              debugPrint('WebView is loading (progress : $progress%)');
            },
            onPageStarted: (String url) {
              debugPrint('Page started loading: $url');
            },
            onPageFinished: (String url) async {
              debugPrint('Page finished loading: $url');
              var result = await controller
                  .runJavaScriptReturningResult('yourJavascriptFunction()');
              print('JavaScript function result: $result');
            },
          ))
          ..loadFlutterAsset('assets/dummy.html');
      }
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          backgroundColor: Colors.white,
          appBar: AppBar(
            title: const Text('Flutter WebView example'),
          ),
          // ignore: unnecessary_null_comparison
          body: WebViewWidget(controller: controller),
          floatingActionButton: FloatingActionButton(
            onPressed: () async {
               String sampleData = 'Hello from Flutter!';
               String jsCode = 'testFunction("$sampleData");';
               await controller.runJavaScript(jsCode);
               var result = await controller.runJavaScriptReturningResult('yourJavascriptFunction();');
               print('JavaScript function result: $result');
               controller.runJavaScript('testFunction();');
            },
            child: const Icon(Icons.send),
          ),
        );
      }
    
    
    }

    Here is my html file code:

    <!DOCTYPE html>
    <html>
    <head>
      <title>Flutter to JavaScript Communication</title>
    </head>
    <body>
      <h1>JavaScript Communication</h1>
      <div id="wrap">
        <div id="editor" contentEditable="true" placeholder="" class="placeholder" style="overflow-y: scroll;">
        </div>
    </div>
    
      <script>
        function yourJavascriptFunction() {
          console.log('JavaScript function called from Flutter');
          alert('This is an alert from JavaScript');
          // Perform any other operations here
          return document.getElementById('editor').innerHTML;
        }
        function testFunction(data) {
                    console.log('Received data:', data);
                    // Perform any other operations with the received data
        }
        // Receive data from Flutter
        window.addEventListener('message', function(event) {
          var receivedData = event.data;
          // Handle the received data in JavaScript
          console.log(receivedData);
          // Perform any other operations with the received data
        });
      </script>
    </body>
    </html>
  6. TarunRaxa commented on Jun 8, 2023

    @TarunRaxa
    Author
  7. TarunRaxa commented on Jun 8, 2023

    @TarunRaxa
    Author

    Also not able to call js function from flutter side

  8. huycozy commented on Jun 9, 2023

    @huycozy
    Member

    Note: I merged two of your comments into one and format the sample code

    Thanks for providing sample code. I can see it works on Android but not on iOS. However, there is no crash on iOS, it just doesn't work when communicating with JS.

    I'm checking this on the latest plugin version webview_flutter_wkwebview: ^3.4.4. Which version are you working on? Can you please retry on latest version and confirm?

  9. added
    waiting for responseThe Flutter team cannot make further progress on this issue until the original reporter responds
    on Jun 9, 2023
  10. TarunRaxa commented on Jun 9, 2023

    @TarunRaxa
    Author

    I am using latest webview_flutter: ^4.2.2 version

  11. removed
    waiting for responseThe Flutter team cannot make further progress on this issue until the original reporter responds
    on Jun 9, 2023
  12. TarunRaxa commented on Jun 9, 2023

    @TarunRaxa
    Author

    Yes it is working fine on android but not on ios side

  13. huycozy commented on Jun 9, 2023

    @huycozy
    Member

    Labeling the issue for further insights.

    ✅: No Issue ❌: Issue reproduced

    flutter doctor -v (stable and master)
    [✓] Flutter (Channel stable, 3.10.4, on macOS 13.0.1 22A400 darwin-x64, locale en-VN)
        • Flutter version 3.10.4 on channel stable at /Users/huynq/Documents/GitHub/flutter
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision 682aa387cf (2 days ago), 2023-06-05 18:04:56 -0500
        • Engine revision 2a3401c9bb
        • Dart version 3.0.3
        • DevTools version 2.23.1
    
    [✓] Android toolchain - develop for Android devices (Android SDK version 32.0.0)
        • Android SDK at /Users/huynq/Library/Android/sdk
        • Platform android-33, build-tools 32.0.0
        • ANDROID_HOME = /Users/huynq/Library/Android/sdk
        • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
        • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)
        • 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 2022.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 17.0.6+0-17.0.6b802.4-9586694)
    
    [✓] VS Code (version 1.78.2)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.66.0
    
    [✓] Connected device (3 available)
        • Pixel 3a (mobile) • 964AY0WL20 • android-arm64  • Android 12 (API 32)
        • macOS (desktop)   • macos      • darwin-x64     • macOS 13.0.1 22A400 darwin-x64
        • Chrome (web)      • chrome     • web-javascript • Google Chrome 114.0.5735.106
    
    [✓] Network resources
        • All expected network resources are available.
    
    • No issues found!
    [!] Flutter (Channel master, 3.12.0-2.0.pre.43, on macOS 13.0.1 22A400 darwin-x64, locale en-VN)
        • Flutter version 3.12.0-2.0.pre.43 on channel master at /Users/huynq/Documents/GitHub/flutter_master
        ! Warning: `flutter` on your path resolves to /Users/huynq/Documents/GitHub/flutter/bin/flutter, which is not inside your current Flutter SDK checkout at /Users/huynq/Documents/GitHub/flutter_master. Consider adding /Users/huynq/Documents/GitHub/flutter_master/bin to the front of your path.
        ! Warning: `dart` on your path resolves to /Users/huynq/Documents/GitHub/flutter/bin/dart, which is not inside your current Flutter SDK checkout at /Users/huynq/Documents/GitHub/flutter_master. Consider adding /Users/huynq/Documents/GitHub/flutter_master/bin to the front of your path.
        • Upstream repository https://github.com/flutter/flutter.git
        • Framework revision e25eabd263 (81 minutes ago), 2023-06-08 18:57:25 -0700
        • Engine revision a5f7d5d75f
        • Dart version 3.1.0 (build 3.1.0-171.0.dev)
        • DevTools version 2.24.0
        • If those were intentional, you can disregard the above warnings; however it is recommended to use "git" directly to perform update checks and upgrades.
    
    [✓] Android toolchain - develop for Android devices (Android SDK version 32.0.0)
        • Android SDK at /Users/huynq/Library/Android/sdk
        • Platform android-33, build-tools 32.0.0
        • ANDROID_HOME = /Users/huynq/Library/Android/sdk
        • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
        • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)
        • 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 2022.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 17.0.6+0-17.0.6b802.4-9586694)
    
    [✓] VS Code (version 1.78.2)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.66.0
    
    [✓] Connected device (3 available)
        • Pixel 3a (mobile) • 964AY0WL20 • android-arm64  • Android 12 (API 32)
        • macOS (desktop)   • macos      • darwin-x64     • macOS 13.0.1 22A400 darwin-x64
        • Chrome (web)      • chrome     • web-javascript • Google Chrome 114.0.5735.106
    
    [✓] Network resources
        • All expected network resources are available.
    
    ! Doctor found issues in 1 category.
  14. added
    platform-iosiOS applications specifically
    and removed
    in triagePresently being triaged by the triage team
    on Jun 9, 2023
  15. 14 remaining items

  16. added
    waiting for responseThe Flutter team cannot make further progress on this issue until the original reporter responds
    on Jun 9, 2023
  17. stuartmorgan-g commented on Jun 9, 2023

    @stuartmorgan-g
    Contributor

    Adjusting labels; without a repro case for the error in the original report we can't investigate this further.

  18. TarunRaxa commented on Jun 10, 2023

    @TarunRaxa
    Author

    Hello, yes same happend at my end. It working fine on android but not on ios. Also is there any more information needed from my side.

  19. removed
    waiting for responseThe Flutter team cannot make further progress on this issue until the original reporter responds
    on Jun 10, 2023
  20. stuartmorgan-g commented on Jun 10, 2023

    @stuartmorgan-g
    Contributor

    @TarunRaxa Yes, see my comment just above. We need a complete, reproducible test case for the PlatformException you reported. The code above runs without any exceptions in our testing.

  21. added
    waiting for responseThe Flutter team cannot make further progress on this issue until the original reporter responds
    on Jun 10, 2023
  22. radoo11 commented on Jun 12, 2023

    @radoo11

    Exactly the same issue on iOS invoking
    await _controller.runJavaScript( 'localStorage["access"] = "$token";', );

    [VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(FWFEvaluateJavaScriptError, Failed evaluating JavaScript., Instance of 'NSError', null)
    WKWebViewHostApiImpl.evaluateJavaScriptForInstances (package:webview_flutter_wkwebview/src/web_kit/web_kit_api_impls.dart:1050:7)
    #1 WebKitWebViewController.runJavaScriptReturningResult (package:webview_flutter_wkwebview/src/webkit_webview_controller.dart:401:28)
    #2 _WebViewState.initState. (package:xxx/features/feed/view/web_view.dart:69:26)

    • Flutter (Channel stable, 3.7.12, on macOS 13.4 22F66 darwin-x64, locale en-GB)
    • webview_flutter: ^4.2.2
  23. stuartmorgan-g commented on Jun 12, 2023

    @stuartmorgan-g
    Contributor

    @radoo11 Per my comment above, we need a complete reproducible test case in order to investigate.

  24. radoo11 commented on Jun 12, 2023

    @radoo11

    I created minimal REPO: https://github.com/radoo11/min_jsweb
    with only main.dart with code from https://pub.dev/packages/webview_flutter/example and error below

    [VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(FWFEvaluateJavaScriptError, Failed evaluating JavaScript., Instance of 'NSError', null)
    WKWebViewHostApiImpl.evaluateJavaScriptForInstances (package:webview_flutter_wkwebview/src/web_kit/web_kit_api_impls.dart:1050:7)

    WebKitWebViewController.runJavaScriptReturningResult (package:webview_flutter_wkwebview/src/webkit_webview_controller.dart:401:28)

    _TestWebViewState.initState. (package:min_jsweb/main.dart:58:28)

    flutter doctor -v
    [✓] Flutter (Channel stable, 3.7.12, on macOS 13.4 22F66 darwin-x64, locale en-GB)
    • Flutter version 3.7.12 on channel stable at /Users/xx/development/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 4d9e56e (8 weeks ago), 2023-04-17 21:47:46 -0400
    • Engine revision 1a65d409c7
    • Dart version 2.19.6
    • DevTools version 2.20.1

  25. stuartmorgan-g commented on Jun 12, 2023

    @stuartmorgan-g
    Contributor

    @radoo11 WKWebView returns an error in your sample project because that JS is invalid; return is not valid in a non-function context. The plugin is behaving correctly there.

    That's also completely different JS than you had in the comment above, so I'm not clear on how it's related.

  26. removed
    waiting for responseThe Flutter team cannot make further progress on this issue until the original reporter responds
    on Jun 24, 2023
  27. stuartmorgan-g commented on Jun 29, 2023

    @stuartmorgan-g
    Contributor

    Closing due to lack of response, since without a reproducible test case we cannot investigate further; by far the most likely way to get the original error is a mistake in the JS itself, rather than a plugin bug.

    If anyone has a reproducible case with correct JS, please file a new issue with all of the code necessary to reproduce it.

  28. github-actions commented on Jul 13, 2023

    @github-actions

    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.

  29. locked as resolved and limited conversation to collaborators on Jul 13, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions