dotnet/wpf · error · InvalidOperationException

SR.CannotInvokeScript

Error message

SR.CannotInvokeScript

What it means

InvokeScript throws InvalidOperationException (SR.CannotInvokeScript) when it cannot obtain a script dispatch object — typically because no HTML document is loaded (or the underlying IHTMLDocument2/script object is unavailable), so there is nothing to invoke the script on.

Solutions

  1. Wait for the WebBrowser.LoadCompleted event (or Navigated + DocumentCompleted equivalent) before invoking script.
  2. Track load state with a bool flag set in LoadCompleted and check it before InvokeScript.
  3. Guard with try-catch (InvalidOperationException) and retry after load completes.
  4. Verify the page actually loaded (check Source / handle navigation errors) instead of assuming success.

Example fix

// before
webBrowser.Navigate(url);
webBrowser.InvokeScript("update", new object[] { data });
// after
webBrowser.LoadCompleted += (s, e) =>
{
    try { webBrowser.InvokeScript("update", new object[] { data }); }
    catch (InvalidOperationException) { /* script/doc not ready */ }
};
webBrowser.Navigate(url);
Defensive patterns

Strategy: try-catch

Validate before calling

bool docReady = loaded && webBrowser.Document != null; if (!docReady) defer call;

Try / catch

try { webBrowser.InvokeScript(name, args); } catch (InvalidOperationException) { pendingScripts.Add(() => webBrowser.InvokeScript(name, args)); }

Prevention

When it happens

Trigger: Calling InvokeScript before Navigate has completed, after a failed navigation, when the document is about:blank, or when the hosted ActiveX control has not reached a state exposing IHTMLDocument2.

Common situations: Calling InvokeScript in the constructor or right after NavigateToString without waiting for LoadCompleted; navigation blocked by security settings; document still loading in slow network conditions.

Understand the failure class

Background: "Invalid state transition" errors: "status must be X, actually Y", "already rejected/charging/uninstalled", "cannot ... while running" — what they mean when a library rejects your call — this error's family across 31 libraries.

Related errors


AI-assisted analysis of dotnet/wpf@81131a70a4 (2026-09-14). Data as JSON: /api/errors/fa6d6983ad39e76f. Report an issue: GitHub.

Appendix: source

Thrown at src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Controls/WebBrowser.cs:337

                        Thread.CurrentThread.CurrentCulture.LCID,
                        NativeMethods.DISPATCH_METHOD,
                        dp,
                        out retVal, 
                        new NativeMethods.EXCEPINFO(),
                        null);
                    hr.ThrowIfFailed();
                }
                finally
                {
                    if (dp.rgvarg != IntPtr.Zero)
                    {
                        UnsafeNativeMethods.ArrayToVARIANTHelper.FreeVARIANTVector(dp.rgvarg, args.Length);
                    }
                }
            }
            else
            {
                throw new InvalidOperationException(SR.CannotInvokeScript);
            }
            return retVal;
        }

        #endregion Public Methods

        //----------------------------------------------
        //
        // Public Properties
        //
        //----------------------------------------------

        #region Public Properties

        /// <summary>
        /// Gets or sets the current uri of the WebBrowser control.
        /// </summary>
        public Uri Source

View on GitHub (pinned to 81131a70a4)