{"record":{"id":"fa6d6983ad39e76f","repo":"dotnet/wpf","slug":"sr-cannotinvokescript","errorCode":null,"errorMessage":"SR.CannotInvokeScript","messagePattern":"SR\\.CannotInvokeScript","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Controls/WebBrowser.cs","lineNumber":337,"sourceCode":"                        Thread.CurrentThread.CurrentCulture.LCID,\n                        NativeMethods.DISPATCH_METHOD,\n                        dp,\n                        out retVal, \n                        new NativeMethods.EXCEPINFO(),\n                        null);\n                    hr.ThrowIfFailed();\n                }\n                finally\n                {\n                    if (dp.rgvarg != IntPtr.Zero)\n                    {\n                        UnsafeNativeMethods.ArrayToVARIANTHelper.FreeVARIANTVector(dp.rgvarg, args.Length);\n                    }\n                }\n            }\n            else\n            {\n                throw new InvalidOperationException(SR.CannotInvokeScript);\n            }\n            return retVal;\n        }\n\n        #endregion Public Methods\n\n        //----------------------------------------------\n        //\n        // Public Properties\n        //\n        //----------------------------------------------\n\n        #region Public Properties\n\n        /// <summary>\n        /// Gets or sets the current uri of the WebBrowser control.\n        /// </summary>\n        public Uri Source","sourceCodeStart":319,"sourceCodeEnd":355,"githubUrl":"https://github.com/dotnet/wpf/blob/81131a70a4c573cd62748a5c36908fc4d662daa9/src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Controls/WebBrowser.cs#L319-L355","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Wait for the WebBrowser.LoadCompleted event (or Navigated + DocumentCompleted equivalent) before invoking script.","Track load state with a bool flag set in LoadCompleted and check it before InvokeScript.","Guard with try-catch (InvalidOperationException) and retry after load completes.","Verify the page actually loaded (check Source / handle navigation errors) instead of assuming success."],"exampleFix":"// before\nwebBrowser.Navigate(url);\nwebBrowser.InvokeScript(\"update\", new object[] { data });\n// after\nwebBrowser.LoadCompleted += (s, e) =>\n{\n    try { webBrowser.InvokeScript(\"update\", new object[] { data }); }\n    catch (InvalidOperationException) { /* script/doc not ready */ }\n};\nwebBrowser.Navigate(url);","handlingStrategy":"try-catch","validationCode":"bool docReady = loaded && webBrowser.Document != null; if (!docReady) defer call;","typeGuard":null,"tryCatchPattern":"try { webBrowser.InvokeScript(name, args); } catch (InvalidOperationException) { pendingScripts.Add(() => webBrowser.InvokeScript(name, args)); }","preventionTips":["Invoke scripts only from LoadCompleted handler","Track load state with a flag","Handle navigation failures so state stays accurate"],"tags":["wpf","webbrowser","invalidoperation","javascript","document-not-loaded"],"backgroundTag":"invalid-state-transition","analyzedSha":"81131a70a4c573cd62748a5c36908fc4d662daa9","analyzedAt":"2026-09-14T10:12:48.479Z","contentChangedAt":"2026-09-14T10:12:48.479Z","schemaVersion":2},"datasetVersion":"2026-09-21T21:30:21.729Z"}