Skip to content

[webview] [iOS Simulator] crash in [WKUserContentController _addScriptMessageHandler:] #141242

@chipweinberger

Description

@chipweinberger

Steps to reproduce

  1. using iOS simulator, iOS 16.4
  2. using xcode 14.3.1 (14E300c)
  3. macOS 13.6.3
  4. flutter 3.16.5
  5. click the "debug" button that pops up next to void main() => runApp(const MyApp()); in the ide
  6. code crashes in [WKUserContentController _addScriptMessageHandler:]

Expected results

No crash

Actual results

crash:

-------------------------------------
Translated Report (Full Report Below)
-------------------------------------

Incident Identifier: D1905BF3-3983-424B-9FF6-B0502311FD90
CrashReporter Key:   4E780D4D-F19E-AFBA-4394-B2658DB81148
Hardware Model:      MacBookPro18,3
Process:             Runner [9288]
Path:                /Users/USER/Library/Developer/CoreSimulator/Devices/3CC4A744-C6BC-4E0F-B0BD-9592007F12A4/data/Containers/Bundle/Application/2B2868F5-2681-4A22-AC42-8392AD1BA840/Runner.app/Runner
Identifier:          com.example.jamcorderFlutterApp
Version:             1.0.0 (1.0.0)
Code Type:           ARM-64 (Native)
Role:                Foreground
Parent Process:      launchd_sim [1961]
Coalition:           com.apple.CoreSimulator.SimDevice.3CC4A744-C6BC-4E0F-B0BD-9592007F12A4 [911]
Responsible Process: SimulatorTrampoline [1937]

Date/Time:           2024-01-10 01:58:09.9383 -0600
Launch Time:         2024-01-10 01:58:07.4407 -0600
OS Version:          macOS 13.6.3 (22G436)
Release Type:        User
Report Version:      104

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Termination Reason: SIGNAL 6 Abort trap: 6
Terminating Process: Runner [9288]

Triggered by Thread:  0

Last Exception Backtrace:
0   CoreFoundation                	       0x180437324 __exceptionPreprocess + 160
1   libobjc.A.dylib               	       0x180051274 objc_exception_throw + 56
2   CoreFoundation                	       0x180437240 -[NSException initWithCoder:] + 0
3   WebKit                        	       0x10b92c35c -[WKUserContentController _addScriptMessageHandler:] + 104
4   WebKit                        	       0x10b92c484 -[WKUserContentController addScriptMessageHandler:name:] + 176
5   webview_flutter_wkwebview     	       0x100e7d250 -[FWFUserContentControllerHostApiImpl addScriptMessageHandlerForControllerWithIdentifier:handlerIdentifier:ofName:error:] + 168 (FWFUserContentControllerHostApi.m:41)
6   webview_flutter_wkwebview     	       0x100e64790 __SetUpFWFWKUserContentControllerHostApi_block_invoke_2 + 296 (FWFGeneratedWebKitApis.m:1413)
7   Flutter                       	       0x10494592c __48-[FlutterBasicMessageChannel setMessageHandler:]_block_invoke + 160
8   Flutter                       	       0x10436478c invocation function for block in flutter::PlatformMessageHandlerIos::HandlePlatformMessage(std::_LIBCPP_ABI_NAMESPACE::unique_ptr<flutter::PlatformMessage, std::_LIBCPP_ABI_NAMESPACE::default_delete<flutter::PlatformMessage>>) + 108
9   libdispatch.dylib             	       0x180132ee4 _dispatch_call_block_and_release + 24
10  libdispatch.dylib             	       0x180134708 _dispatch_client_callout + 16
11  libdispatch.dylib             	       0x180143fd8 _dispatch_main_queue_drain + 1220
12  libdispatch.dylib             	       0x180143b04 _dispatch_main_queue_callback_4CF + 40
13  CoreFoundation                	       0x18039a784 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 12
14  CoreFoundation                	       0x180394de4 __CFRunLoopRun + 1912
15  CoreFoundation                	       0x180394254 CFRunLoopRunSpecific + 584
16  GraphicsServices              	       0x188eb7c9c GSEventRunModal + 160
17  UIKitCore                     	       0x10e1ceff0 -[UIApplication _run] + 868
18  UIKitCore                     	       0x10e1d2f3c UIApplicationMain + 124
19  Runner                        	       0x100a62fd0 main + 64 (AppDelegate.swift:5)
20  dyld_sim                      	       0x100d1d514 start_sim + 20
21  dyld                          	       0x100aadf28 start + 2236
22  ???                           	0xe739000000000000 ???

Code sample

html (Edit: it turns out I was forgetting to invoke this html code. So you can ignore it)

<!DOCTYPE html>
<html>
<head>
    <title>Calculation</title>
    <script type="text/javascript">
        function startCalculation() {
            var progress = 0;
            var interval = setInterval(function() {
                progress++;
                if (progress <= 100) {
                    CalculationResult.postMessage(progress + '% completed');
                } else {
                    clearInterval(interval);
                    CalculationResult.postMessage('Result of calculation');
                }
            }, 100); // Adjust this for your calculation
        }
    </script>
</head>
<body>
    <h1>Calculation Page</h1>
</body>
</html>

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  late WebViewController _controller;
  double _progress = 0;
  bool _isLoading = false;

  void _runComplexCalculation() {
    setState(() {
      _isLoading = true;
    });
    _controller.runJavaScript("startCalculation();");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("WebView Calculation"),
      ),
      body: Stack(
        children: [
          Opacity(
            opacity: 0.0,
            child: WebViewWidget(
              controller: _controller = WebViewController()
                ..setJavaScriptMode(JavaScriptMode.unrestricted)
                ..setNavigationDelegate(
                  NavigationDelegate(
                    onProgress: (int progress) {
                      setState(() {
                        _progress = progress / 100;
                      });
                    },
                    onPageFinished: (String url) {
                      _controller.addJavaScriptChannel("CalculationResult", onMessageReceived: _onMessageReceived);
                    },
                  ),
                )
                ..loadRequest(Uri.parse('about:blank')),
            ),
          ),
          if (_isLoading)
            LinearProgressIndicator(
              value: _progress,
              backgroundColor: Colors.grey[200],
              valueColor: const AlwaysStoppedAnimation<Color>(Colors.blue),
            ),
          Center(
            child: ElevatedButton(
              onPressed: _runComplexCalculation,
              child: const Text('Render'),
            ),
          ),
        ],
      ),
    );
  }

  void _onMessageReceived(JavaScriptMessage message) {
    setState(() {
      _isLoading = false;
      _progress = 0;
    });
    // ignore: avoid_print
    print(message.message); // Handle the calculation result here
  }
}

Flutter Doctor output

Doctor output
chipweinberger@Chips-MacBook-Pro jamcorder_flutter_app % flutter doctor --verbose
[✓] Flutter (Channel stable, 3.16.5, on macOS 13.6.3 22G436 darwin-arm64, locale en-US)
    • Flutter version 3.16.5 on channel stable at /Volumes/User/MBP-Google-Drive/jamcorder/app/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 78666c8dc5 (3 weeks ago), 2023-12-19 16:14:14 -0800
    • Engine revision 3f3e560236
    • Dart version 3.2.3
    • DevTools version 2.28.4

[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
    • Android SDK at /Users/chipweinberger/Library/Android/sdk
    • Platform android-34, build-tools 34.0.0
    • 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.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14E300c
    • CocoaPods version 1.12.1

[✓] 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.85.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.80.0

[✓] Connected device (4 available)
    • ChipsiPhone (mobile)       • 00008101-000A0D1E3C90001E            • ios            • iOS 16.7.2 20H115
    • iPhone 14 Pro Max (mobile) • 3CC4A744-C6BC-4E0F-B0BD-9592007F12A4 • ios            • com.apple.CoreSimulator.SimRuntime.iOS-16-4 (simulator)
    • macOS (desktop)            • macos                                • darwin-arm64   • macOS 13.6.3 22G436 darwin-arm64
    • Chrome (web)               • chrome                               • web-javascript • Google Chrome 120.0.6099.216

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    found in release: 3.16Found to occur in 3.16found in release: 3.19Found to occur in 3.19has reproducible stepsThe issue has been confirmed reproducible and is ready to work onp: webviewThe WebView pluginpackageflutter/packages repository. See also p: labels.platform-iosiOS applications specificallyr: fixedIssue is closed as already fixed in a newer versionteam-iosOwned by iOS platform team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions