Diga.WebView2 icon indicating copy to clipboard operation
Diga.WebView2 copied to clipboard

Frame.ExecuteScript to retrieve frame html source problem

Open PaulYBChiang opened this issue 11 months ago • 1 comments

The following code frameId can be retrieved but resultObjectAsJson always returned null watever script was document.documentElement.outerHTML; or "return 'Hello from JavaScript!';";

Frame.ExecuteScript works?

    public static TabPage AddNewWebPage(string title, string url)
    {
        var newTab = new TabPage(title)
        { Tag = url };
        tabcontrol.TabPages.Add(newTab);
        var webView = new WebView() { Dock = DockStyle.Fill };
        webView.FrameCreated += (s, e) => 
        {
            var frameId = e.Frame.FrameId;
            var frameName = e.Frame.name;
            Console.WriteLine($"Frame Created - ID: {frameId}, Name: {frameName}");

            string script = "document.documentElement.outerHTML;";
            

            var handler = new ScriptCompletedHandler();

            e.Frame.ExecuteScript(script, handler);
        };
        newTab.Controls.Add(webView);
        webView.Navigate(url);

        return newTab;
    }
    public class ScriptCompletedHandler : ICoreWebView2ExecuteScriptCompletedHandler
    {
        public ScriptCompletedHandler() { }

        public void Invoke(int errorCode, string resultObjectAsJson)
        {
            if (errorCode == 0)
            {
                Console.WriteLine("Script executed successfully.");

                Console.WriteLine("HTML Source:");
                Console.WriteLine(resultObjectAsJson);
            }
            else
            {
                Console.WriteLine($"Script execution failed with error code: {errorCode}");
            }
        }
    }

PaulYBChiang avatar Feb 10 '25 07:02 PaulYBChiang

https://learn.microsoft.com/en-us/microsoft-edge/webview2/reference/win32/icorewebview2frame2?view=webview2-1.0.2957.106#executescript => "The result of evaluating the provided JavaScript is passed to the completion handler. The result value is a JSON encoded string. If the result is undefined, contains a reference cycle, or otherwise is not able to be encoded into JSON, then the result is considered to be null, which is encoded in JSON as the string "null"."

        webView.FrameCreated += (s, e) => 
        {
            var frameId = e.Frame.FrameId;
            var frameName = e.Frame.name;
            Console.WriteLine($"Frame Created - ID: {frameId}, Name: {frameName}");

            ScriptContext.Run(() =>
                {
                        string script = "document.documentElement.outerHTML;";
                        var handler = new ScriptCompletedHandler();
                        e.Frame.ExecuteScript(script, handler);
                });
       }

This might help you. Please remember that WinForms is synchronous, while the calls from WebView2 are asynchronous.

DIGAToDIGA avatar Feb 10 '25 13:02 DIGAToDIGA