Skip to content

Commit f438163

Browse files
committed
Added navigation handler #47
1 parent 8108170 commit f438163

2 files changed

Lines changed: 57 additions & 0 deletions

File tree

src/AngleSharp.Js/JsConfigurationExtensions.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ public static IConfiguration WithJs(this IConfiguration configuration)
6565
{
6666
var service = new JsScriptingService();
6767
var observer = new EventAttributeObserver(service);
68+
var handler = new JsNavigationHandler(service);
6869

6970
if (!configuration.Has<INavigator>())
7071
{
@@ -73,6 +74,7 @@ public static IConfiguration WithJs(this IConfiguration configuration)
7374

7475
return configuration
7576
.WithOnly(observer)
77+
.With(handler)
7678
.With(service);
7779
}
7880
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
namespace AngleSharp.Js
2+
{
3+
using AngleSharp.Browser;
4+
using AngleSharp.Dom;
5+
using AngleSharp.Io;
6+
using AngleSharp.Scripting;
7+
using AngleSharp.Text;
8+
using System;
9+
using System.IO;
10+
using System.Threading;
11+
using System.Threading.Tasks;
12+
13+
/// <summary>
14+
/// Represents a handler for javascript: URLs.
15+
/// </summary>
16+
public class JsNavigationHandler : INavigationHandler
17+
{
18+
private static readonly String UrlSchema = "javascript";
19+
private readonly JsScriptingService _service;
20+
21+
/// <summary>
22+
/// Creates a new navigation handler for javascript: URLs.
23+
/// </summary>
24+
/// <param name="service">The underlying scripting service.</param>
25+
public JsNavigationHandler(JsScriptingService service)
26+
{
27+
_service = service;
28+
}
29+
30+
/// <inheritdoc />
31+
public async Task<IDocument> NavigateAsync(DocumentRequest request, CancellationToken token)
32+
{
33+
var document = request.Source?.Owner;
34+
35+
if (document != null)
36+
{
37+
var loop = document.Context.GetService<IEventLoop>();
38+
var options = new ScriptOptions(document, loop);
39+
var script = request.Target.Href.Substring(UrlSchema.Length + 1);
40+
var content = TextEncoding.Utf8.GetBytes(script);
41+
var response = new DefaultResponse
42+
{
43+
Address = new Url(document.Url),
44+
Content = new MemoryStream(content),
45+
};
46+
await _service.EvaluateScriptAsync(response, options, token).ConfigureAwait(false);
47+
}
48+
49+
return document;
50+
}
51+
52+
/// <inheritdoc />
53+
public Boolean SupportsProtocol(String protocol) => protocol.Is(UrlSchema);
54+
}
55+
}

0 commit comments

Comments
 (0)