Repository: flutter
Issue: Could not find identifier for JavaScriptChannel
Labels: c: crash,platform-android,p: webview,package,has reproducible steps,P2,c: fatal crash,found in release: 3.7,found in release: 3.10,team-android,triaged-android

### Is there an existing issue for this?

- [X] I have searched the [existing issues](https://github.com/flutter/flutter/issues)
- [X] I have read the [guide to filing a bug](https://flutter.dev/docs/resources/bug-reports)

### Steps to reproduce

1. Load code sample
2. `Hot restart`
3. Wait 5 seconds for `window.setInterval()` to execute

### Expected results

I guess I expected the JS from the initial load not to execute.

### Actual results

An accumulation of distinct `window.setInterval()` executions for every app load.

### Code sample

<details><summary>Code sample</summary>

```dart
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:url_launcher/url_launcher_string.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 MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late WebViewController webViewController;
  bool _ready = false;
  final String jsChannelName = 'TestChannel';

  @override
  void initState() {
    super.initState();
    webViewController = WebViewController()
      ..enableZoom(false)
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(
        NavigationDelegate(
          onNavigationRequest: (navigation) {
            if (navigation.url == 'about:blank' || navigation.url.startsWith('file://')) {
              return NavigationDecision.navigate;
            } else {
              launchUrlString(navigation.url, mode: LaunchMode.externalApplication);
              return NavigationDecision.prevent;
            }
          },
          onPageStarted: (value) {
            //
          },
          onPageFinished: (value) {
            //
          },
          onProgress: (value) {
            //
          },
          onWebResourceError: (err) {
            //
          },
        ),
      );
    webViewController.addJavaScriptChannel(
      jsChannelName,
      onMessageReceived: (JavaScriptMessage message) {
        Map msg = jsonDecode(message.message);
        if (msg['kind'] == 'bug') {
          debugPrint("${msg['msg']}");
        }
      },
    );
    setFile();
  }

  void setFile() async {
    Directory dir = await getApplicationDocumentsDirectory();
    String filepath = join(dir.path, 'index.html');
    File file = File(filepath);
    String fileHtml = '''
      <!DOCTYPE html>
      <html lang="en">
      <head>
        <meta charset="UTF-8">
        <title>Webview4 Test iOS Bug</title>
      </head>
      <body>
        <div style="font-size:45px;">
          <p>Lorem ipsum dolor....</p>
        </div>
      </body>
      </html>
      <script>
        callTest = function() {
          window.setInterval(function() {
            window.$jsChannelName.postMessage(JSON.stringify({
              kind: 'bug',
              msg: 'MARCO POLO',
            }));
          }, 5000);
        }
        callTest();
      </script>
    ''';
    await file.writeAsString(fileHtml);

    webViewController.loadFile(join(dir.path, 'index.html'));
    setState(() {
      _ready = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: _ready
          ? Center(
              child: WebViewWidget(
                controller: webViewController,
              ),
            )
          : const CircularProgressIndicator(),
    );
  }
}

```

</details>


### Screenshots or Video

<details>
<summary>Screenshots / Video demonstration</summary>

![Screenshot_20230425_135654](https://user-images.githubusercontent.com/6127483/234257074-42fa7af8-4587-4edc-adeb-97e264214342.png)


</details>


### Logs

<details><summary>Logs</summary>

```console
[Paste your logs here]
D/AndroidRuntime(29886): Shutting down VM
E/AndroidRuntime(29886): FATAL EXCEPTION: main
E/AndroidRuntime(29886): Process: com.example.webview_crash, PID: 29886
E/AndroidRuntime(29886): java.lang.IllegalStateException: Could not find identifier for JavaScriptChannel.
E/AndroidRuntime(29886): 	at io.flutter.plugins.webviewflutter.JavaScriptChannelFlutterApiImpl.getIdentifierForJavaScriptChannel(JavaScriptChannelFlutterApiImpl.java:42)
E/AndroidRuntime(29886): 	at io.flutter.plugins.webviewflutter.JavaScriptChannelFlutterApiImpl.postMessage(JavaScriptChannelFlutterApiImpl.java:36)
E/AndroidRuntime(29886): 	at io.flutter.plugins.webviewflutter.JavaScriptChannel.lambda$postMessage$1$io-flutter-plugins-webviewflutter-JavaScriptChannel(JavaScriptChannel.java:45)
E/AndroidRuntime(29886): 	at io.flutter.plugins.webviewflutter.JavaScriptChannel$$ExternalSyntheticLambda1.run(Unknown Source:4)
E/AndroidRuntime(29886): 	at android.os.Handler.handleCallback(Handler.java:942)
E/AndroidRuntime(29886): 	at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(29886): 	at android.os.Looper.loopOnce(Looper.java:226)
E/AndroidRuntime(29886): 	at android.os.Looper.loop(Looper.java:313)
E/AndroidRuntime(29886): 	at android.app.ActivityThread.main(ActivityThread.java:8757)
E/AndroidRuntime(29886): 	at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(29886): 	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571)
E/AndroidRuntime(29886): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1067)
W/e.webview_crash(29886): Attempt to remove non-JNI local reference, dumping thread
Lost connection to device.
```

</details>


### Flutter Doctor output

<details><summary>Doctor output</summary>

```console
[✓] Flutter (Channel stable, 3.7.10, on macOS 12.6 21G115 darwin-arm64, locale en-IL)
    • Flutter version 3.7.10 on channel stable at /Users/lielvdh/Developer/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 4b12645012 (3 weeks ago), 2023-04-03 17:46:48 -0700
    • Engine revision ec975089ac
    • Dart version 2.19.6
    • DevTools version 2.20.1

[✓] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
    • Android SDK at /Users/lielvdh/Library/Android/sdk
    • Platform android-33, build-tools 32.1.0-rc1
    • 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.2)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14C18
    • 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.73.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension can be installed from:
      🔨 https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[✓] Connected device (3 available)
    • SM G781B (mobile) • RZCT310HAMK • android-arm64  • Android 13 (API 33)
    • macOS (desktop)   • macos       • darwin-arm64   • macOS 12.6 21G115 darwin-arm64
    • Chrome (web)      • chrome      • web-javascript • Google Chrome 112.0.5615.137

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!

```

</details>