【发布时间】:2021-11-24 11:04:55
【问题描述】:
我在 CefSharp 中运行 JS 时遇到了困难,因为命令会一个接一个地运行。基本上,在执行最后一个脚本后,我需要一个等待命令来等待页面加载。
因此它会是:
await Browser.ExecuteScriptAsync(script1);
Browser.WaitForLoad();
Task<JavascriptResponse> test = await Browser.EvaluateScriptAsync(script2);
我找到了一些资源,但我只是编程新手,所以我发现要弄清楚如何做我想做的事情有点困难。
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CefSharp;
using CefSharp.Wpf;
namespace WpfApp2
{
public partial class MainWindow : Window
{
private string MessagesInbox;
public MainWindow()
{
InitializeComponent();
}
private void Browser_Loaded(object sender, RoutedEventArgs e)
{
Browser.LoadingStateChanged += async (Sender, args) => {if (args.IsLoading == false)
{
await Browser.EvaluateScriptAsync(@"document.getElementById('User').value = 'test'; document.getElementById('Password').value = 'password'; document.getElementById('LoginButton').click();");
}};
Task<JavascriptResponse> test = Browser.EvaluateScriptAsPromiseAsync(@"return new Promise(function(resolve, reject) { setTimeout(resolve.bind(null, { var test = ''; document.querySelectorAll('.MasterAction').forEach(el => test += el.children[3].children[0].href + ', ')}), 2000);");
MessagesInbox = test.Result.ToString();
MessageBox.Show(MessagesInbox);
}
}
}
【问题讨论】:
-
您当前的代码有什么问题?
-
目前,我收到“System.Exception: 'Unable to execute javascript at this time, scripts can only be executed within a V8Context”错误。但是在发送返回 Task
的第二个命令之前,我需要页面等待加载
标签: javascript c# wpf cefsharp