[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 DOM and how to control visual elements in an HTML page 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.

  • Handling the XAML class constructor in order to connect the Web page to a managed-code class.

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

  • Accessing properties and methods in the HTML DOM.

In order to run the examples in this topic, you need the following:

  • Silverlight version 2 Beta 1.

  • Microsoft Visual Studio 2008 Service Pack 1.

  • Microsoft Silverlight Tools Beta 1 for Visual Studio 2008.

  • This software is available from the Silverlight download site.

This topic also assumes that you have available a Silverlight-based project. For information on how to create a Silverlight-based Web site, see Creating an Application for Silverlight.

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. In the test page HTML file add the following HTML elements:

    <input type="text" id="txtInput" disabled="disabled" />
    <button type="button" id=" btnUCtxt"> UpperCase Text</button>
    <input type="text" id="txtOutput" size="60" />
    <button type="button" id="btnGetProperties">
        Get Properties
    </button>
    <br/>
    <input type="text" id="txtOutputProperties" size="60"/>

    The following example shows the complete markup for the body element of the test page.

    <body>
      <!-- Runtime errors from Silverlight will be displayed here.
      This will contain debugging information and should be removed or 
      hidden when debugging is completed -->
      <div id='errorLocation' style="font-size: small;color:Gray;"></div>
        <div id="silverlightControlHost">
        <object data="data:application/x-silverlight," type="application/x-silverlight-2-b1" width="10%" height="10%">
          <param name="source" value="ClientBin/qsHB.xap"/>
          <param name="onerror" value="onSilverlightError" />
          <param name="background" value="white" />
    
          <a href="http://go.microsoft.com/fwlink/?LinkID=108182" 
                  style="text-decoration: none;">
            <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/>
          </a>
        </object>
        <iframe style='visibility:hidden;height:0;width:0;border:0px'>
        </iframe>
       <div id="basic1">
         <h3>Manipulating HTML buttons with Silverlight managed code</h3>
         <hr />
         <strong>Uppercase text from the first text box to the second 
             text box</strong><br />
         Type text in here:&nbsp; <input type="text" id="txtInput" 
             disabled="disabled" />&nbsp;&nbsp;&nbsp;
         <button type="button" id="btnUCtxt">UpperCase Text</button>
             <br /><br />
         Uppercase text: <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>
      </div>
    </body>

Connecting the Page to a Managed Class

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

To connect the HTML page to the XAML class constructor

  1. In the Page class (Page.xaml.cs or Page.xaml.vb), add a module-level variable named _doc of type HtmlDocument.

    This variable will be used to store the HtmlDocument instance, which is a reference to the current page.

  2. Initialize the class variable _doc in the Page constructor.

    The following example shows code from the Page constructor that performs these tasks.

    cs

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

    vb

    Imports System.Windows.Browser
    
    Partial Public Class Page
       Inherits UserControl
    
       Dim _doc As HtmlDocument
       Dim _cnt As Integer = 0
    
    
       Public Sub New()
          InitializeComponent()
          _doc = HtmlPage.Document
    
    

    The code creates a private, module-level variable of type HtmlDocument. It then assigns to the private variable the object that represents the HTML page that is hosting the application.

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. In the Page constructor, get a reference to the HTML element by calling the GetElementByID method of the HTML document object that you created, passing the ID of one of the HTML elements.

  2. Attach an event handler. To attach a handler, you need the reference to the element that you obtained in step 1.

    The following example shows the Page constructor. The code gets a reference to the Uppercase Text button and the txtInput element on the HTML page. It then attaches an event handler to the button's OnClick event.

    cs

    // <snippet7>
    public partial class Page : UserControl {
        HtmlDocument _doc;   // requires using System.Windows.Browser; 
        int _cnt=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 from the Silverlight Side");
    
            HtmlElement btnUC = _doc.GetElementById("btnUCtxt");
    
            btnUC.AttachEvent("onclick",
                new EventHandler<HtmlEventArgs>(this.OnUCtextClicked));
    
            setUpPropBtn();
        }
    
    

    vb

    Partial Public Class Page
       Inherits UserControl
    
       Dim _doc As HtmlDocument
       Dim _cnt 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 from the Silverlight Side")
          _doc.GetElementById("btnUCtxt").AttachEvent("onclick", _
             New EventHandler(Of HtmlEventArgs)(AddressOf OnUCtextClicked))
    
          setUpPropBtn()
    
       End Sub
    
    
  3. Run the application.

    The txtInput element displays "This text from the Silverlight Side", and the element is no longer disabled.

Accessing the HTML DOM

You can now access properties and call methods in the HTML DOM.

To access a property in the HTML DOM

  1. Write a handler for the onclick event that is attached to the Uppercase Text button. Name the event handler OnUCtextClicked.

  2. In the handler, use the properties of an HTML DOM object to access information about that object.

    For example, you can use the properties of the HtmlPage object (in the _doc member) to retrieve the current text of the txtInput input text element.

  3. Use the property information to set properties of another element in the page, such as a text box.

    In the example below, the SetAttribute and GetAttribute methods are used on the txtInput and txtOutput DOM elements to get and set property values. The text from the txtInput DOM element is converted to uppercase and assigned to the value property of the txtOutput DOM 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.

    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. Get a programmatic reference to the HTML DOM element whose method you want to call.

  2. Call the DOM method directly.

    The following example shows how to call the OnGetPropClicked method of the HtmlPage object to display the port number, cookie state, and Uniform Resource Identifier (URI) of the current page.

    cs

    void setUpPropBtn() {
    
        HtmlElement btnPropGet = _doc.GetElementById("btnGetProperties");
        btnPropGet.AttachEvent("onclick",
            new EventHandler<HtmlEventArgs>(this.OnGetPropClicked));
    }
    
    void OnGetPropClicked(object sender, HtmlEventArgs e) {
        string outputText = "";
        _cnt++;
        switch (_cnt % 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 setUpPropBtn()
       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 = ""
       _cnt += 1
       Select Case (Me._cnt 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
    
    
  3. Run the application and click the Get Properties button multiple times.

    Each time 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 (true or false).

    • The port number for the URI.