Skip to content

[Android] HeadlessInAppWebView crashes with "Must be started before we block!" when injecting document-start scripts on a cold WebView engine #2849

Description

@e2755699

Environment

  • flutter_inappwebview 6.x / flutter_inappwebview_android (also reproducible against current master)
  • Device: Samsung SM-F946B, Android 16, beta System WebView 150.0.7871.3
  • Triggered via HeadlessInAppWebView used to pre-warm a page at app startup

Crash

java.lang.RuntimeException: Must be started before we block!
  at WV.cp2.addDocumentStartJavaScript(...)
  at ...types.UserContentController.addPluginScript
  at ...in_app_webview.InAppWebView.prepareAndAddUserScripts
  at ...in_app_webview.InAppWebView.prepare
  at ...in_app_webview.FlutterWebView.<init>
  at ...headless_in_app_webview.HeadlessInAppWebViewManager.run

Root cause

UserContentController calls WebViewCompat.addDocumentStartJavaScript(...) from updateContentWorldsCreatorScript(), addUserOnlyScript() and addPluginScript(), guarded only by WebViewFeature.isFeatureSupported(DOCUMENT_START_SCRIPT). That flag reflects support-library capability, not whether the Chromium engine has finished starting.

For a HeadlessInAppWebView the WebView is never attached to a window, so the engine-startup that an attached WebView completes synchronously hasn't finished yet; and on a cold engine (first WebView in the process) the synchronous addDocumentStartJavaScript call made in the constructor races ahead of startup and throws. It only reproduces on a small set of devices / beta WebView builds where startup is slow enough to lose the race. Likely related: #2843, #2844.

Suggested fix

Proper: await engine readiness before injecting — WebViewCompat.startUpWebView(...) (callback on the main looper, idempotent) and build/inject the headless WebView inside the callback. Caveat: the stable API needs androidx.webkit:webkit:1.16.0, which raises minSdk to 24 (the plugin is currently minSdk 19); 1.14.0 only ships the @OptIn(ExperimentalAsyncStartUp) version. So it implies a dependency/minSdk decision.

Cheap interim: wrap the three addDocumentStartJavaScript calls in a try/catch that logs and returns null (callers null-check the ScriptHandler). Degrades gracefully instead of crashing, on all minSdk/webkit. I have this on a branch and am happy to open a PR if a stopgap is welcome: master...e2755699:fix/android-cold-start-document-start-script-crash

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions