Search code examples
c#geckofx

Call Javascript From C# in GeckoFX 33


Im trying to execute javascript call from C# to the Document loaded in GeckoFX controller, im doing this:

public void evaluateScript(string command)
{            
    System.Diagnostics.Debug.WriteLine("evaluateScript: " + command);
    using (Gecko.AutoJSContext context = 
        new AutoJSContext(geckoWebBrowser1.Window.JSContext))
    {
            string result;
            context.EvaluateScript(
                command, 
                (nsISupports)geckoWebBrowser1.Window.DomWindow, 
                out result);
    }
}

But this doesn't work, I only found as a solution to call geckoWebBrowser1.Navigate('javascript:functionName(1,2);'); but with this, I can't recover return data from functionName and using the Navigate to make a JavaScript call I think is an error. Is there no way to call JavaScript functions in the DOM and receive their data in C#?


Solution

  • I found the solution, in the version 33, the API has changed a little, its more simple, because by default the EvaluateScript get the WebBrowser DOM as default context if you pass the param, and return the result direct.

    public void evaluateScript(string command)
            {
    
                System.Diagnostics.Debug.WriteLine("evaluateScript: " + command);
                using (Gecko.AutoJSContext context = new AutoJSContext(geckoWebBrowser1.Window.JSContext))
                {
                    var result = context.EvaluateScript(command, geckoWebBrowser1.Window.DomWindow);
                }
            }
    

    In the older versions, need to specify the context of the EvaluateScript, i found examples in this URL: https://nhabuiduc.wordpress.com/2014/09/18/geckofx-net-webbrowser-setup-and-features/