Selenium 在 C# 中调用异步 JavaScript

Selenium call async JavaScript in C#

我需要在获取 Selenium 中的函数值时调用异步 JavaScript 函数。我试过了,但出现脚本超时错误。

我的JavaScript密码是

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

    var result = await domtoimage.toPng(node);

    console.log(result);

    return result;
}

我试过了

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

我收到脚本超时,并且再也没有返回值。

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));

我的 Driver 和 EdgeOptions 是

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);

我想喜欢下面的方法或扩展

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

方便以后使用

更多参考,我的后端是 blazor。

对于 non-async,您必须“return”数据。

return ScreenToBase64()

对于异步参数[0](如果你传递变量则更高)应该是解析器所以你想:

ScreenToBase64().then(arguments[0])