'EvaulateScriptAsPromiseAsync and async/await

I'm trying to use EvaluateScriptAsPromiseAsync with CefSharp.

It seems to work in the browser, but I get a null result in cefSharp.

Javascript:

(async function() {
    const result = await $.ajax({ type: 'GET', url: './robots.txt' });
    return result;
})();

CSharp Code:

var result = await browser.EvaluateScriptAsPromiseAsync(script);
Debug.Assert(result.Result != null);

Full Code:


public partial class Form1 : Form
    {
        ChromiumWebBrowser browser;
        public Form1()
        {
            InitializeComponent();
            browser = new ChromiumWebBrowser("jquery.com");
            this.Controls.Add(browser);

            browser.FrameLoadEnd += Browser_FrameLoadEnd;

        }

        private void Browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
        {
            const string script = @"(async function() {
                const result = await $.ajax({ type: 'GET', url: './robots.txt' });
            return result;
        })();";
            if (e.Frame.IsMain)
            {
                // Get us off the main thread
                Task task = new Task(async () =>
                {
                    var result = await browser.EvaluateScriptAsPromiseAsync(script);
                    Debug.Assert(result.Result != null);
                });
                task.Start();
            }
        }

    }


Solution 1:[1]

So the IIFE in the example above evaluates as a Promise, the extra step required is to actually return the promise. Scripts passed to EvaluateScriptAsPromiseAsync MUST return a value otherwise you'll get null.

Differs from other EvaluateScriptAsync methods in that you must return a result.

//This will return 42
await browser.EvaluateScriptAsPromiseAsync("return 42");
//This will return undefined
await browser.EvaluateScriptAsPromiseAsync("42");

As per https://github.com/cefsharp/CefSharp/pull/3251

Because it's wrapped in an IIFE which is then passed to Promise.resolve, you need to return the result. e.g.

return (async function() {
    const result = await $.ajax({ type: 'GET', url: './robots.txt' });
    return result;
})();
private void Browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
{
    const string script = @"return (async function() { const result = await $.ajax({ type: 'GET', url: './robots.txt' }); return result; })();";
    if (e.Frame.IsMain)
    {
        // Use the Thread Pool
        Task.Run(async () =>
        {
            var result = await browser.EvaluateScriptAsPromiseAsync(script);
            Debug.Assert(result.Result != null);
        });
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1