Tuesday, May 3, 2011

Modifying HTML content before on Render

You could modify the HTML that is about to be rendered to a page using the ASP.NET Render event. For example, below we add an onclick event to every a href tag on the page:

///
/// Add an onclick handler to each link. Allows omniture to trace user clicks and navigation with s_objectID.
/// Exceptions: if onclick exists do not override or add another one to the chain.
///

protected override void Render(System.Web.UI.HtmlTextWriter writer)
{

System.IO.StringWriter stringWriter = new System.IO.StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
base.Render(htmlWriter);
string html = stringWriter.ToString();

// get to the first a tag and start processing from there
int startPoint = html.IndexOf("
// is there already an onclick handler on some tag in this page
bool hasOnclick = html.IndexOf("onclick=", StringComparison.InvariantCultureIgnoreCase) > -1;

// get to the href and add an onclick handler unless one already exists
startPoint = html.IndexOf("href=\"", startPoint);
int ihref2 = 0;
string link;

// distniguishes links within different pages
string linkExtension;
string[] pathseg = Request.Url.Segments;
if (pathseg.Length > 0)
{
linkExtension = pathseg[pathseg.Length - 1];
linkExtension = linkExtension.Replace(".", "");
}
else
linkExtension = String.Empty;


while (startPoint > -1)
{
if (hasOnclick)
{
int idx1 = html.IndexOf(" int idx2 = html.IndexOf(">", idx1 + 1);
string atag = html.Substring(idx1, idx2 - idx1);

// is this an if (atag.IndexOf("onclick", StringComparison.InvariantCultureIgnoreCase) > -1)
{
// move to the next tag. Do not override existing onclick
startPoint = startPoint + 7;
startPoint = html.IndexOf("href=\"", startPoint);
continue;
}
}

startPoint = startPoint + 7;
ihref2 = html.IndexOf("\"", startPoint);
if (ihref2 > -1 && ihref2 > startPoint)
{
link = html.Substring(startPoint, ihref2 - startPoint).Replace("http", "").Replace("\\", "").Replace(@"/", "").Replace("\"", "").Replace("'", "").Replace(".", "").Replace("(", "").Replace(")", "").Replace(":", "");
ihref2++;
html = html.Substring(0, ihref2) + " onclick=\"s_objectID='" + link + linkExtension + "'\" " + html.Substring(ihref2);
startPoint = html.IndexOf("href=\"", ihref2); // get the next href - ihref2 is > startPoint
}
else
startPoint = -1;
}

writer.Write(html);
}