public async Task<HtmlNode> VisitAsync(VisitingContext context, HtmlNode node) { // We're only interested in stylesheets. if (node.GetAttributeValue("rel", null) != "stylesheet") return node; var href = node.GetAttributeValue("href", null); if (href == null) return node; var hrefUri = new Uri(href, UriKind.RelativeOrAbsolute); if (!hrefUri.IsAbsoluteUri) { hrefUri = new Uri(context.Address, hrefUri); } // Get the stylesheet and insert it inline. var content = default(string); try { content = await context.WebClient.DownloadAsync(hrefUri); } catch (WebException) { return node; } content = "<style>" + content + "</style>"; return HtmlNode.CreateNode(content); }
public async Task<HtmlNode> VisitAsync(VisitingContext context, HtmlNode node) { var src = node.GetAttributeValue("src", null); if (src == null) return node; // Take care if the src starts with two slashes. if (src.StartsWith("//")) { src = "http:" + src; } var srcUri = new Uri(src, UriKind.RelativeOrAbsolute); if (!srcUri.IsAbsoluteUri) { srcUri = new Uri(context.Address, srcUri); } // Get the script and insert it inline. var content = default(string); try { content = await context.WebClient.DownloadAsync(srcUri); } catch (WebException) { return node; } content = "<script>" + content + "</script>"; return HtmlNode.CreateNode(content); }
public async Task Visit_ScriptWithSrcStartingWithTwoSlashes_ShouldBeHandledCorrectly() { // Arrange var visitor = new ScriptsVisitor(); var node = HtmlNode.CreateNode(@"<script src=""//www.some2.com/l.js""></script>"); var client = VisitorsHelper.CreateWebClientMock("function some(){}"); var context = new VisitingContext() { Address = new Uri("http://www.some.com"), WebClient = client.Object, }; // Act var newNode = await visitor.VisitAsync(context, node); // Assert client.Verify(c => c.DownloadAsync(new Uri("http://www.some2.com/l.js")), Times.Once); Assert.Equal("<script>function some(){}</script>", newNode.OuterHtml); }
public async Task Visit_LinkWithAbsoluteHref() { // Arrange var visitor = new StylesVisitor(); var node = HtmlNode.CreateNode(@"<link href=""http://www.some2.com/l.css"" rel=""stylesheet"">"); var client = VisitorsHelper.CreateWebClientMock("html{width:0}"); var context = new VisitingContext() { Address = new Uri("http://www.some.com"), WebClient = client.Object, }; // Act var newNode = await visitor.VisitAsync(context, node); // Assert client.Verify(c => c.DownloadAsync(new Uri("http://www.some2.com/l.css")), Times.Once); Assert.Equal("<style>html{width:0}</style>", newNode.OuterHtml); }