CefSharp Running JavaScript



我在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);
}
}
}

你还应该检查第二个方法的IsLoading,你可以使用bool来跟踪你是否已经登录,并在该函数中使用第二个方法,就像这样:

public bool loggedIn = false;
private void Browser_Loaded(object sender, EventArgs e)
{
Browser.LoadingStateChanged += async (Sender, args) =>
{
if (args.IsLoading == false)
{
if (!loggedIn)
{
await Browser.EvaluateScriptAsync(@"document.getElementById('User').value = 'test'; document.getElementById('Password').value = 'password'; document.getElementById('LoginButton').click();")
.ContinueWith(x =>
{
var response = x.Result;
System.Diagnostics.Debug.WriteLine(response.Result);
if (response.Result == null)
{
System.Diagnostics.Debug.WriteLine("should be changed to true");
loggedIn = true;
}
});
}
else
{
JavascriptResponse test = await Browser.EvaluateScriptAsync(@"var test = ''; document.querySelectorAll('.MasterAction').forEach(el => test += el.children[3].children[0].href + ', ');test.substr(0,test.length-2)");
MessagesInbox = test.Result.ToString();
System.Diagnostics.Debug.WriteLine(MessagesInbox);
}
}
};
}

相关内容

  • 没有找到相关文章

最新更新