Html Agility Pack messing with my javascript

html-agility-pack javascript

Question

I'm using the Html Agility Pack to output some javascript in the head of my document. But after saving the document to the file system I recognized that the javascript source has been modified. I guess this happens because HAP is trying to validate my script. Is it possible to prevent this? As you can see below I already tried setting different options.

My code using HAP:

var htmlDoc = new HtmlDocument();
htmlDoc.OptionCheckSyntax = false;
htmlDoc.OptionAutoCloseOnEnd = false;
htmlDoc.OptionFixNestedTags = false;
htmlDoc.LoadHtml(htmlContent);

HtmlNode headNode = htmlDoc.DocumentNode.SelectSingleNode("//head");
headNode.AddScriptNode(htmlDoc, "../../Scripts/jquery-1.7.1.min.js");

Extension Method for adding the script tag

public static void AddScriptNode(this HtmlNode headNode, HtmlDocument htmlDoc, string filePath)
{
    string content = "";

    using (StreamReader rdr = File.OpenText(filePath))
    {
        content = rdr.ReadToEnd();
    }
    if(headNode != null)
    {
        HtmlNode scripts = htmlDoc.CreateElement("script");
        scripts.Attributes.Add("type", "text/javascript");
        scripts.InnerHtml = "\n" + content + "\n";
        headNode.AppendChild(scripts);
    }
}

Accepted Answer

My assumption: when using scripts.InnerHtml AgilityPack tries to parse the content as HTML. So if there are tags there they will be converted to HTML nodes.

To avoid this you should set the content of the <script> as text. Unfortunately, HtmlNode.InnerText property is a read-only but there is a workaround for this. You could just add a text(a comment node will be preferrable) node to your <script> node:

if(headNode != null)
{
    HtmlNode scripts = htmlDoc.CreateElement("script");
    scripts.Attributes.Add("type", "text/javascript");
    scripts.AppendChild(htmlDoc.CreateComment("\n" + content + "\n"));
    headNode.AppendChild(scripts);
}

Here the body of your script will be added as a comment node (<!-- and --> will be added).



Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow