namespace JeffWilcox.RichWebClient.Utilities
{
using System;
using System.Windows;
using System.Windows.Browser;
///
/// A set of C# 3.0 extension methods *as well* as a general
/// HTML DOM bridge helper & utility library
///
public static class HtmlExtensions
{
///
/// Retrieve the first HtmlElement in the document that matches
/// the tag name
///
/// HTML tag
/// The first HtmlElement of tagName on the page
public static HtmlElement GetSingleElementByTagName(string tagName)
{
HtmlElementCollection hh = HtmlPage.Document.GetElementsByTagName(tagName);
if (hh.Count > 0) {
return hh[0];
}
throw new InvalidOperationException(
String.Format(@"There were no ""{0}"" HTML tags found on the page.", tagName));
}
///
/// Property representing the <body /> element on
/// the page.
///
/// Although a static property, this get is actually
/// a method call
public static HtmlElement BodyElement
{
get { return GetSingleElementByTagName("body"); }
}
///
/// Evaluate some JavaScript code on the page body
///
public static void Eval(string code)
{
HtmlElement js = CreateJavaScriptElement(code);
BodyElement.AppendChild(js);
}
///
/// Popup a JavaScript alert message
///
public static void Alert(string alertMessage)
{
Eval("alert('"
+ alertMessage.Replace("'", "\\'")
+ "')");
}
///
/// Create a JavaScript code block
///
public static HtmlElement CreateJavaScriptElement(string code)
{
HtmlElement js = CreateJavaScriptElement();
js.SetProperty("text", code);
return js;
}
///
/// Create an HTML element that is a JavaScript include
///
public static HtmlElement CreateJavaScriptInclude(string src)
{
HtmlElement js = CreateJavaScriptElement();
js.SetAttribute("src", src);
return js;
}
///
/// Create a new <script /> tag
///
private static HtmlElement CreateJavaScriptElement()
{
HtmlElement js = HtmlPage.Document.CreateElement("script");
js.SetAttribute("type", "text/javascript");
return js;
}
///
/// Property representing the <head /> element on
/// the page.
///
/// Although a static property, this get is actually
/// a method call
public static HtmlElement HeadElement
{
get { return GetSingleElementByTagName("head"); }
}
///
/// Append multiple HtmlElements to a single HtmlElement
///
public static void AppendChildren(this HtmlElement element, params HtmlElement[] children)
{
for (int i = 0; i < children.Length; ++i) {
element.AppendChild(children[i]);
}
}
}
}