我开始阅读有关 Anglesharp 的官方文档,最后一个示例在 JavaScript 和 C# 中以某种奇怪的方式工作。从逻辑上讲,我应该从加载事件中获取文本并从脚本中获取hello,但我只能从 c# 代码中获取它。
编码
using AngleSharp;
using System;
namespace ConsoleApp1
{
class MyClass
{
public async static void EventScriptingExample()
{
//We require a custom configuration
var config = Configuration.Default.WithJs();
//Create a new context for evaluating webpages with the given config
var context = BrowsingContext.New(config);
//This is our sample source, we will trigger the load event
var source = @"<!doctype html>
<html>
<head><title>Event sample</title></head>
<body>
<script>
console.log('Before setting the handler!');
document.addEventListener('load', function() {
console.log('Document loaded!');
});
document.addEventListener('hello', function() {
console.log('hello world from JavaScript!');
});
console.log('After setting the handler!');
</script>
</body>";
var document = await context.OpenAsync(req => req.Content(source));
//HTML should be output in the end
Console.WriteLine(document.DocumentElement.OuterHtml);
//Register Hello event listener from C# (we also have one in JS)
document.AddEventListener("hello", (s, ev) =>
{
Console.WriteLine("hello world from C#!");
});
var e = document.CreateEvent("event");
e.Init("hello", false, false);
document.Dispatch(e);
}
static void Main()
{
EventScriptingExample();
Console.ReadKey();
}
}
}
它应该是:
我能得到什么:
注意:也就是说,事件只能从 c# 代码中执行。


也许这个例子并不完整。它对我有用:
我还纠正了异步性,使一切都很漂亮。