Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async commands to WebDriver in Selenium

I am trying to handle the completion of asynchronous function in Selenium. Asynchronous js function must be started to execute after the click on the button.

Say listenFor(arguments[0]) listens for the end of the click handlers execution and it starts to listen it before the click action was dispatched. In the next function I am listening for click event before Click action using async/await of C#.

    private async void ExecuteJsAsync(IActionElement button)
    {
        Console.WriteLine("Started async function");

        var result = Task<bool>.Factory.StartNew(() =>
        {
            Console.WriteLine("Started to listen");

            var script = "listenFor(arguments[0])";
            var executor = (IJavaScriptExecutor)browser;

            return executor.ExecuteAsyncScript(script);
        });

        Console.WriteLine("Before click");
        new Actions(browser).Click(button).Perform();
        Console.WriteLine("After click");

        _result = await result;
    }

But I am getting the next sequence of logs:

1. Started async function    
2. Before Click
3. Started to listen

Here we can see that Click action has not been dispatched. And Question is:

  1. Is it possible to execute several tasks asynchronously with Selenium (here Click action & listener)?
  2. Why Selenium can't send Click action to the browser here?
  3. Do Selenium commands like Click, SendKeys execute in the main javascripts thread?
like image 588
Makha Avatar asked Feb 06 '26 10:02

Makha


1 Answers

IMHO, if the logic is like that:

Asynchronous js function must be started to execute after the click on the button.

then you need to do something like a chain:

await Task.Run(() => { new Actions(browser).Click(button).Perform(); }).ContinueWith((_task) => { async code to execute AFTER Click (Perform method completion?) })

Sorry, not aware yet about intrinsic logic of Selenium, so not sure it's feasible.

like image 138
Alexander Avatar answered Feb 08 '26 02:02

Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!