Home > Software design >  Selenium call async JavaScript in C#
Selenium call async JavaScript in C#

Time:04-17

I need to call async JavaScript function at get the function value in Selenium. I tried but I am getting Script timeout error.

My JavaScript Code is

async function SnapScreen() {
    var node = document.getElementById("videoContainer");

    var result = await domtoimage.toPng(node);

    console.log(result);

    return result;
}

I have tried

1) Driver?.ExecuteJavaScript("ScreenToBase64()");
2) IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
var obj = js.ExecuteAsyncScript(script, args);

I am getting Script Timeout and never ge the value back.

3) var wait = new WebDriverWait(Driver, TimeSpan.FromMinutes(3));
var data = wait.Until(driver => driver.ExecuteJavaScript<T>(script, args));
4) var wait = new WebDriverWait(Driver, TimeSpan.FromMinutes(3));
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
var data = wait.Until(driver => js.ExecuteAsyncScript(script, args));

and my Driver and EdgeOptions are

var timeSpan = TimeSpan.FromMinutes(3);

var edgeDriverService = EdgeDriverService.CreateDefaultService(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

edgeDriverService.HideCommandPromptWindow = true;

var edgeOptions = new EdgeOptions { PageLoadStrategy = PageLoadStrategy.Eager };

edgeOptions.AddArgument("headless");
edgeOptions.AddArgument("no-sandbox");
edgeOptions.AddArgument("enable-javascript");
edgeOptions.AddArgument("inprivate");
edgeOptions.AddArgument("whitelisted-ips=\"\"");

Driver = new EdgeDriver(edgeDriverService, edgeOptions, timeSpan);

Driver.Manage().Window.Size = new System.Drawing.Size(1920, 1080);
Driver.Manage().Timeouts().AsynchronousJavaScript.Add(timeSpan);
Driver.Manage().Timeouts().ImplicitWait.Add(timeSpan);
Driver.Manage().Timeouts().PageLoad.Add(timeSpan);

I want to like the method or extension like following

var result=await Driver.ExecuteJavaScriptAsync<T>(script,args)
(or)
var result=await Driver.ExecuteJavaScriptAsync<T>(script,waitTime,args)

So that I can use it in the future.

For more reference my backend is blazor.

CodePudding user response:

For non-async you have to "return" the data.

return ScreenToBase64()

For async arguments[0] (or higher if you pass variables) should be the resolver so you want to:

ScreenToBase64().then(arguments[0])
  • Related