QUICKSTARTS
[This topic is pre-release documentation and is subject to change in future releases of Microsoft Silverlight.]

Accessing the HTML DOM from Managed Code

Introduction

This QuickStart sample demonstrates how to programmatically access the HTML Document Object Model (DOM) by using managed code in a Microsoft Silverlight-based application. Accessing the HTML DOM lets you write .NET Framework managed code that runs on a user's computer and manipulates the UI on a Web page, without requiring a round trip to the server.

Run View
Language:

Working with this capability in your Silverlight-based application involves the following tasks:

  • Adding HTML elements to a page.

  • Connecting the HTML page to a managed class.

  • Accessing properties and methods in the HTML DOM.

  • Connecting to and handling an event of an HTML DOM element.

Prerequisites (available from the Silverlight download site):

  • Silverlight version 2 Beta 2.

  • Microsoft Visual Studio 2008.

  • Silverlight Tools Beta 2 for Visual Studio 2008.

Adding HTML Elements to a Test Page

To begin, you will add HTML elements to the project's test page.

To add HTML elements for testing

  1. Create a new Silverlight Application project in Visual Basic or Visual C# as described in Creating an Application for Silverlight. Be sure to choose the Add a new Web to the solution for hosting the control option.

  2. Set the HTML test page as the start page and open it in Source view.

  3. Find the <object> tag and change the height attribute to "10%".

  4. After the closing </iframe> tag, add the following HTML markup.

    This HTML adds two button elements and three input text elements.

    <div id="basic1">
      <h3>Manipulating HTML buttons with Silverlight managed code</h3>
      <hr />
      <strong>Convert text from the first text box to uppercase in the
          second text box</strong><br />
      <label>Type text in here:</label>&nbsp;
      <input type="text" id="txtInput" disabled="disabled"
          size="35" />&nbsp;
      <button type="button" id="btnUCtxt">UpperCase Text</button>
      <br /><br />
      <label>Uppercase text:</label>
      <input type="text" id="txtOutput" size="60" />
    </div>
    
    <br /><br />
    <div id="basic2">
      <button type="button" id="btnGetProperties">
          Get Properties</button><br/>
      <input type="text" id="txtOutputProperties" size="60"/>
    </div>
  5. Run the application.

    You should see an UpperCase Text button, a Get Properties button, and three input text elements. The first input text element, named txtInput, is empty and disabled.

Connecting the HTML Page to a Managed Class

To connect the HTML page to a managed class, you initialize a reference to the page in the XAML class constructor.

To connect the HTML page to the XAML class constructor

  1. Open the Page class code-behind file (Page.xaml.cs or Page.xaml.vb).

  2. Add a using or Imports statement to the System.Windows.Browser namespace.

  3. Declare a private class-level variable named _doc of type HtmlDocument.

  4. Initialize the _doc variable in the Page constructor.

    The following code shows how to initialize the _doc variable with an object that represents the current HTML page that is hosting the application.

    cs

    public partial class Page : UserControl {
        private HtmlDocument _doc;   // requires using System.Windows.Browser; 
        private int _count=0;
    
        public Page() {
            InitializeComponent();
            _doc = HtmlPage.Document;
    
    

    vb

    Partial Public Class Page
       Inherits UserControl
    
        Private _doc As HtmlDocument
        Private _count As Integer = 0
    
    
        Public Sub New()
            InitializeComponent()
            _doc = HtmlPage.Document
    
    

Accessing Properties in the HTML DOM

You can now access properties in the HTML DOM.

To access a property in the HTML DOM

  1. Access the properties of the txtInput element by adding the following code to the end of the Page constructor.

    This code uses the GetElementById method of the HTML document object to get a reference to the txtInput element on the HTML test page. It then enables the element and sets a new text value.

    cs

    // Return for all pages except those ending in TestPage.html
    if (_doc.DocumentUri.AbsoluteUri.EndsWith("TestPage.html") != true)
        return;
    
    _doc.GetElementById("txtInput").SetProperty("disabled", false);
    _doc.GetElementById("txtInput").SetAttribute("value",
        "This text is set from managed code.");
    
    

    vb

    ' Return for all pages except those ending in TestPage.html
    If (_doc.DocumentUri.AbsoluteUri.EndsWith("TestPage.html") <> True) Then
        Return
    End If
    
    _doc.GetElementById("txtInput").SetProperty("disabled", False)
    _doc.GetElementById("txtInput").SetAttribute("value", _
                "This text is set from managed code.")
    
    
  2. Run the application.

    The txtInput element displays "This text is set from managed code.", and the element is no longer disabled.

Handling an Event of an HTML DOM Element

You can now attach an event handler to an HTML DOM element.

To handle an event of an HTML DOM element

  1. Attach an event handler to the onclick event of the Uppercase Text button by adding the following code to the end of the Page constructor.

    This code gets a reference to the btnUCtxt element on the HTML test page. It then attaches an event handler to the button's onclick event.

    cs

    // Add event handler for Uppercase Text button.
    HtmlElement btnUC = _doc.GetElementById("btnUCtxt");
    btnUC.AttachEvent("onclick",
        new EventHandler<HtmlEventArgs>(this.OnUCtextClicked));
    
    

    vb

    ' Add event handler for Uppercase Text button.
    Dim btnUC As HtmlElement = _doc.GetElementById("btnUCtxt")
    btnUC.AttachEvent("onclick", _
       New EventHandler(Of HtmlEventArgs)(AddressOf OnUCtextClicked))
    
    
  2. Write an event handler named OnUCtextClicked for the button's onclick event.

  3. In the event handler, get and set properties on an HTML element.

    For example, in the following OnUCtextClicked event handler, the SetAttribute and GetAttribute methods are used on the txtInput and txtOutput elements to get and set property values. The text from the txtInput element is converted to uppercase and assigned to the value property of the txtOutput element.

    cs

    void OnUCtextClicked(object sender, HtmlEventArgs e) {
        HtmlElement input = _doc.GetElementById("txtInput");
        HtmlElement output = _doc.GetElementById("txtOutput");
        output.SetAttribute("value", input.GetAttribute("value").ToUpper());
    }
    
    

    vb

    Private Sub OnUCtextClicked(ByVal sender As Object, ByVal e As HtmlEventArgs)
       Dim input As HtmlElement = _doc.GetElementById("txtInput")
       _doc.GetElementById("txtOutput").SetAttribute("value", _
                            input.GetAttribute("value").ToUpper)
    End Sub
    
    
  4. Run the application and click the UpperCase Text button.

    The txtOutput element displays a copy of the text from the txtInput element in uppercase.

Calling a Method in the HTML DOM

Finally, you can call a method in the HTML DOM.

To call a method in the HTML DOM

  1. Attach an event handler to the onclick event of the Get Properties button by adding the following code to the end of the Page constructor.

    This code gets a reference to the btnGetProperties element on the HTML test page. It then attaches an event handler to the button's onclick event.

    cs

    // Add event handler for Get Properties button.
    HtmlElement btnPropGet = _doc.GetElementById("btnGetProperties");
    btnPropGet.AttachEvent("onclick",
        new EventHandler<HtmlEventArgs>(this.OnGetPropClicked));
    
    

    vb

    ' Add event handler for Get Properties button.
    Dim btnPropGet As HtmlElement = _doc.GetElementById("btnGetProperties")
    btnPropGet.AttachEvent("onclick", _
       New EventHandler(Of HtmlEventArgs)(AddressOf OnGetPropClicked))
    
    
  2. Write an event handler named OnGetPropClicked for the button's onclick event.

  3. In the event handler, get a programmatic reference to the HTML element whose method that you want to call and then call the method.

    For example, the following OnGetPropClicked event handler shows how to use the HtmlPage object to display the port number, cookie state, and Uniform Resource Identifier (URI) of the current page.

    cs

    void OnGetPropClicked(object sender, HtmlEventArgs e) {
        string outputText = "";
        _count++;
        switch (_count % 3) {
            case 0:
                outputText = "DocumentUri.AbsolutePath: "
                + HtmlPage.Document.DocumentUri.AbsolutePath;
                break;
    
            case 1:
                outputText = "Cookies Enabled: " +
                    HtmlPage.BrowserInformation.CookiesEnabled.ToString();
                break;
    
            case 2:
                outputText = "Port: " +
                    HtmlPage.Document.DocumentUri.Port.ToString();
                break;
        }
        _doc.GetElementById("txtOutputProperties").SetAttribute("value", outputText);
    }
    
    

    vb

    Private Sub OnGetPropClicked(ByVal sender As Object, ByVal e As HtmlEventArgs)
        Dim outputText As String = ""
        _count += 1
        Select Case (Me._count Mod 3)
            Case 0
                outputText = ("DocumentUri.AbsolutePath: " _
                              & HtmlPage.Document.DocumentUri.AbsolutePath)
                Exit Select
            Case 1
                outputText = ("Cookies Enabled: " _
                              & HtmlPage.BrowserInformation.CookiesEnabled.ToString)
                Exit Select
            Case 2
                outputText = ("Port: " _
                              & HtmlPage.Document.DocumentUri.Port.ToString)
                Exit Select
        End Select
        _doc.GetElementById("txtOutputProperties").SetAttribute("value", outputText)
    End Sub
    
    
  4. Run the application and click the Get Properties button multiple times.

    Each time that you click the button, the txtOutputProperties element displays one of three possible properties:

    • The URI of the page.

    • A value that indicates whether cookies are enabled.

    • The port number for the URI.

Example

The following shows complete code for this sample.

cs

using System;
using System.Windows.Controls;

using System.Windows.Browser;  // needed for HtmlPage

namespace qsHB {

    public partial class Page : UserControl {
        private HtmlDocument _doc;   // requires using System.Windows.Browser; 
        private int _count=0;

        public Page() {
            InitializeComponent();
            _doc = HtmlPage.Document;

            // Return for all pages except those ending in TestPage.html
            if (_doc.DocumentUri.AbsoluteUri.EndsWith("TestPage.html") != true)
                return;

            _doc.GetElementById("txtInput").SetProperty("disabled", false);
            _doc.GetElementById("txtInput").SetAttribute("value",
                "This text is set from managed code.");

            // Add event handler for Uppercase Text button.
            HtmlElement btnUC = _doc.GetElementById("btnUCtxt");
            btnUC.AttachEvent("onclick",
                new EventHandler<HtmlEventArgs>(this.OnUCtextClicked));

            // Add event handler for Get Properties button.
            HtmlElement btnPropGet = _doc.GetElementById("btnGetProperties");
            btnPropGet.AttachEvent("onclick",
                new EventHandler<HtmlEventArgs>(this.OnGetPropClicked));
        }


        void OnGetPropClicked(object sender, HtmlEventArgs e) {
            string outputText = "";
            _count++;
            switch (_count % 3) {
                case 0:
                    outputText = "DocumentUri.AbsolutePath: "
                    + HtmlPage.Document.DocumentUri.AbsolutePath;
                    break;

                case 1:
                    outputText = "Cookies Enabled: " +
                        HtmlPage.BrowserInformation.CookiesEnabled.ToString();
                    break;

                case 2:
                    outputText = "Port: " +
                        HtmlPage.Document.DocumentUri.Port.ToString();
                    break;
            }
            _doc.GetElementById("txtOutputProperties").SetAttribute("value", outputText);
        }

        void OnUCtextClicked(object sender, HtmlEventArgs e) {
            HtmlElement input = _doc.GetElementById("txtInput");
            HtmlElement output = _doc.GetElementById("txtOutput");
            output.SetAttribute("value", input.GetAttribute("value").ToUpper());
        }
    }
}

vb

Imports System.Windows.Browser

Partial Public Class Page
   Inherits UserControl

    Private _doc As HtmlDocument
    Private _count As Integer = 0


    Public Sub New()
        InitializeComponent()
        _doc = HtmlPage.Document

        ' Return for all pages except those ending in TestPage.html
        If (_doc.DocumentUri.AbsoluteUri.EndsWith("TestPage.html") <> True) Then
            Return
        End If

        _doc.GetElementById("txtInput").SetProperty("disabled", False)
        _doc.GetElementById("txtInput").SetAttribute("value", _
                    "This text is set from managed code.")

        ' Add event handler for Uppercase Text button.
        Dim btnUC As HtmlElement = _doc.GetElementById("btnUCtxt")
        btnUC.AttachEvent("onclick", _
           New EventHandler(Of HtmlEventArgs)(AddressOf OnUCtextClicked))

        ' Add event handler for Get Properties button.
        Dim btnPropGet As HtmlElement = _doc.GetElementById("btnGetProperties")
        btnPropGet.AttachEvent("onclick", _
           New EventHandler(Of HtmlEventArgs)(AddressOf OnGetPropClicked))
    End Sub

    Private Sub OnGetPropClicked(ByVal sender As Object, ByVal e As HtmlEventArgs)
        Dim outputText As String = ""
        _count += 1
        Select Case (Me._count Mod 3)
            Case 0
                outputText = ("DocumentUri.AbsolutePath: " _
                              & HtmlPage.Document.DocumentUri.AbsolutePath)
                Exit Select
            Case 1
                outputText = ("Cookies Enabled: " _
                              & HtmlPage.BrowserInformation.CookiesEnabled.ToString)
                Exit Select
            Case 2
                outputText = ("Port: " _
                              & HtmlPage.Document.DocumentUri.Port.ToString)
                Exit Select
        End Select
        _doc.GetElementById("txtOutputProperties").SetAttribute("value", outputText)
    End Sub

   Private Sub OnUCtextClicked(ByVal sender As Object, ByVal e As HtmlEventArgs)
      Dim input As HtmlElement = _doc.GetElementById("txtInput")
      _doc.GetElementById("txtOutput").SetAttribute("value", _
                           input.GetAttribute("value").ToUpper)
   End Sub
End Class

See Also

Page view counter