Report unhandled JavaScript exceptions from evaluateJavascript in the WebView2 backend

With the WebView2 backend on Windows, WebBrowserComponent::evaluateJavascript calls ICoreWebView2::ExecuteScript (juce_WebBrowserComponent_windows.cpp, line 692 in 9.0.6) and parses the JSON result. ExecuteScript returns "null" for an unhandled exception, for undefined and for a real null, so JUCE reports all three the same way: no error and a void result. On macOS, a thrown exception comes back as Error::Type::javascriptException.

The header (juce_WebBrowserComponent.h, line 565) says of Windows and Android:

Unfortunately these platforms don’t offer a way to detect evaluation errors.

The current WebView2 backend still uses ExecuteScript, but WebView2 now has an API for this. ICoreWebView2_21::ExecuteScriptWithResult became stable in SDK 1.0.2277.86 (February 2024, runtime 121.0.2277.86 or later). Its result has Succeeded, which is FALSE for an unhandled exception, and an Exception that carries the name and message.

Request: when QueryInterface for ICoreWebView2_21 succeeds, use ExecuteScriptWithResult and map Succeeded == FALSE to Error::Type::javascriptException, with the exception message. Keep ExecuteScript on older runtimes. A script that throws would then report the same error category on Windows as on macOS.

Repro: create a WebBrowserComponent with Backend::webview2 and load any page. After pageFinishedLoading, evaluate each script below separately and log getError() and getResult():

for (auto* script : { "throw new Error('boom')", "void 0", "null" })
    browser.evaluateJavascript (script, [script] (juce::WebBrowserComponent::EvaluationResult r)
    {
        DBG (script << " -> error: " << (r.getError() != nullptr ? r.getError()->message : juce::String ("none"))
                    << ", result: " << (r.getResult() != nullptr ? juce::JSON::toString (*r.getResult()) : juce::String ("none")));
    });

Measured with JUCE 9.0.6, Release builds:

Script Windows 11, WebView2 runtime 158.0.4370.45, SDK 1.0.3485.44 macOS 27, WKWebView
throw new Error('boom') no error, void result javascriptException, “Error: boom …”
void 0 no error, void result var::undefined()
null no error, void result void

On the same Windows machine, a plain Win32 program calling WebView2 directly shows that ExecuteScriptWithResult already separates the throw: Succeeded is FALSE, and the exception has name Error and message Error: boom …. For void 0 and null it returns Succeeded == TRUE with ResultAsJson == "null".

Two details for whoever implements this:

  • get_Exception returns E_INVALIDARG when the script did not throw.
  • The exception’s Message includes the stack line, and LineNumber/ColumnNumber were 0.

Context: we drive a WebBrowserComponent-based plugin UI from automated tests and need evaluateJavascript to report a failing script the same way on every platform.

1 Like