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