Written by:
Microsoft
Microsoft
HTML Bridge
Mar 05, 2009
Login to Rate
:( Error
0
0
Summary
Describes how to access the HTML DOM from managed code, and to call managed code from JavaScript.
HTML Bridge is a technology in Silverlight that enables you to access the HTML Document Object Model (DOM) from managed code, and to call managed code from JavaScript. This QuickStart demonstrates how to use some of the HTML Bridge types in Silverlight.
This QuickStart contains the following sections:
For a complete description of HTML Bridge, see HTML Bridge: Interaction Between HTML and Managed Code in the Silverlight documentation on MSDN.
HTML Bridge Overview
HTML Bridge is an integrated set of types and methods that enable you to do the following:
- Attach Silverlight managed event handlers to HTML controls.
- Attach JavaScript event handlers to Silverlight controls.
- Expose complete managed types to JavaScript for scripting.
- Expose individual methods of managed types to JavaScript for scripting.
- Use managed containers for DOM elements such as window, document, and standard HTML elements.
- Pass managed types as parameters to JavaScript functions and objects.
- Return managed types from JavaScript.
- Control various security aspects of your Silverlight-based application.
Setting Up the Silverlight Plug-in
The examples in this QuickStart are text-based, so the Silverlight plug-in does not have to display any XAML-based UI elements. Therefore, the width and height of the Silverlight plug-in can be set to 0 pixels to prevent it from occupying the Web page or interrupting normal HTML flow. Although the Silverlight plug-in does not have a visible UI, it still has access to the underlying DOM of the page.
The following HTML is embedded in this page. It applies to the two examples in this QuickStart.
HTML
<div id="silverlightControlHost">
<object id="SLP" data="data:application/x-silverlight"
type="application/x-silverlight-2"
width="0px" height="0px">
<param name="source" value="/content/quickstarts/samples/HtmlBridge1.xap"/>
<param name="background" value="white" />
<param name="minRuntimeVersion" value="2.0.30926.0" />
<param name="autoUpgrade" value="true" />
<param name="onerror" value="onSilverlightError" />
<a href="http://go.microsoft.com/fwlink/?LinkID=124807"
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>
Note
If you set the display:none or visibility:hidden styles on the Silverlight plug-in or its containing DIV, the Silverlight plug-in will not be able to access the page's underlying DOM.
Accessing the HTML DOM from Managed Code
HTML Bridge includes several types that enable you to access and modify the HTML DOM from Silverlight. The following example demonstrates how to access the HTML DOM and performs the following operations in managed code:
- Enables the first text box.
- Sets the text for the first text box to "This text is set from managed code."
- Attaches a Silverlight event handler to the Convert button.
- Converts the text in the first text box to uppercase and displays it in the second text box.
To try this example, add text to the first text box and click the Convert button.
The text is converted to uppercase and displayed in the second text box.
The following HTML creates the two text boxes and the button. Notice that it has the following characteristics:
- The text box named
Input is disabled.
- Each element has an ID value, which is helpful when you need to access the element from Silverlight.
- Inline HTML event handlers are not assigned.
- Although the entire file is not listed, there are no embedded JavaScript handlers.
HTML
<div>
Enter lowercase text <input type="text" id="Input" disabled="true"/><br>
Convert to uppercase <button type="button" id="Convert">Convert </button><br>
Uppercase text <input type="text" id="Output"/>
</div>
Accessing the HTML DOM
To access the HTML DOM from Silverlight, you typically use the following HTML Bridge classes:
- HtmlPage represents the Web page.
HtmlPage is static and is the main entry point for all DOM access.
- HtmlDocument represents the document object.
- HtmlElement represents DOM elements.
To use the HTML Bridge classes in managed code, you must add a using or Imports statement to the System.Windows.Browser namespace. Individual HTML elements can be accessed if they have an ID by using the HtmlDocument.GetElementById method. You can get properties and attributes on an element by using the HtmlElement.GetProperty and HtmlElement.GetAttribute methods. You can set properties and attributes on an element by using the HtmlElement.SetProperty and HtmlElement.SetAttribute methods.
The following managed code in the Page.xaml (Page.xaml.cs or Page.xaml.vb) file shows how you access the HTML DOM from Silverlight. This code is in the
Page constructor and runs during application startup. The code gets a reference to the Input element, sets the disabled property to false, and sets the value attribute to "This text is set from managed code."
C#
public Page()
{
InitializeComponent();
HtmlDocument htmlDoc = HtmlPage.Document;
HtmlElement htmlEl = htmlDoc.GetElementById("Input");
htmlEl.SetProperty("disabled", false);
htmlEl.SetAttribute("value", "This text is set from managed code.");
...
}
Visual Basic
Public Sub New()
InitializeComponent()
Dim htmlDoc As HtmlDocument = HtmlPage.Document
Dim htmlEl As HtmlElement = htmlDoc.GetElementById("Input")
htmlEl.SetProperty("disabled", False)
htmlEl.SetAttribute("value", "This text is set from managed code.")
...
End Sub
Attaching a Managed Event Handler
Not only can you access the HTML DOM, you can also attach events to HTML controls that are handled in managed code. HtmlElement derives from HtmlObject, which includes the HtmlObject.AttachEvent method. This method enables you to attach a Silverlight event handler to an HTML element.
The following managed code in the Page.xaml (Page.xaml.cs or Page.xaml.vb) file shows how the Convert button's onclick handler is attached to a managed event handler named OnConvertClicked by using the HtmlObject.AttachEvent method. The code also shows the OnConvertClicked event handler, which gets the value attribute on the Input text box and sets the value attribute on the Output element to an uppercase string.
C#
public Page()
{
InitializeComponent();
HtmlDocument htmlDoc = HtmlPage.Document;
HtmlElement htmlEl = htmlDoc.GetElementById("Input");
...
// Add an event handler for the Convert button.
htmlEl = htmlDoc.GetElementById("Convert");
htmlEl.AttachEvent("onclick", new EventHandler(this.OnConvertClicked));
}
void OnConvertClicked(object sender, HtmlEventArgs e)
{
HtmlDocument htmlDoc = HtmlPage.Document;
HtmlElement input = htmlDoc.GetElementById("Input");
HtmlElement output = htmlDoc.GetElementById("Output");
output.SetAttribute("value", input.GetAttribute("value").ToUpper());
}
Visual Basic
Public Sub New()
InitializeComponent()
Dim htmlDoc As HtmlDocument = HtmlPage.Document
Dim HtmlElement htmlEl As HtmlElement = htmlDoc.GetElementById("Input")
...
' Add an event handler for the Convert button.
htmlEl = htmlDoc.GetElementById("Convert")
htmlEl.AttachEvent("onclick", _
New EventHandler(Of HtmlEventArgs)(AddressOf OnConvertClicked))
End Sub
Private Sub OnConvertClicked(ByVal sender As Object, ByVal e As HtmlEventArgs)
Dim htmlDoc As HtmlDocument = HtmlPage.Document
Dim input As HtmlElement = htmlDoc.GetElementById("Input")
Dim output As HtmlElement = htmlDoc.GetElementById("Output")
output.SetAttribute("value", input.GetAttribute("value").ToUpper)
End Sub
Calling Managed Code from JavaScript
HTML Bridge provides the ScriptableType and ScriptableMember attributes. These attributes are used to mark managed types and members as scriptable. After these attributes are applied to a type or member, the type must be instantiated with the new operator, and then registered by using the HtmlPage.RegisterScriptableObject method. The type or method is then available to be called from JavaScript.
The following example demonstrates how to call managed code from JavaScript. To try this example, add some text to the first text box and click the Call Silverlight Scriptable method button. A dialog box appears that indicates that the managed SimpleMethodExample method was called and displays the text. When you click OK, the return string is displayed in the second text box.
The following HTML creates the two text boxes and the button. When you click the Call Silverlight Scriptable method button, the JavaScript Call_SL_Scriptable function is called.
HTML
<div>
Enter the text to send <input type="text" id="Text1" /><br>
Call Silverlight method <button type="button" onclick="Call_SL_Scriptable()">
Call Silverlight Scriptable method</button><br>
Display the return string <input type="text" id="Text2"/>
</div>
JavaScript Call
The following shows the JavaScript Call_SL_Scriptable function. The JavaScript gets the text from the Text1 text box and passes it to the managed SimpleMethodExample method. The text that is returned from the method is displayed in the Text2 text box. The SimpleMethodExample method call has the following format:
SLPlugin is a reference to the Silverlight plug-in.
Content is an object that represents the plug-in area.
SL_SMT is the name that is used to register the managed object.
SimpleMethodExample is the managed method name that was marked as scriptable.
JavaScript
<script type="text/javascript">
function Call_SL_Scriptable()
{
var SLPlugin = document.getElementById("SLP");
var strIn = document.getElementById("Text1").value;
var strOut = SLPlugin.Content.SL_SMT.SimpleMethodExample(strIn);
document.getElementById("Text2").value = strOut;
}
</script>
Scriptable Managed Code
The following shows the managed code in the Page.xaml (Page.xaml.cs or Page.xaml.vb) file
that the JavaScript Call_SL_Scriptable function calls. In the Page constructor, a new ScriptableManagedType is created and registered during application startup. This object is registered with the name SL_SMT by using the HtmlPage.RegisterScriptableObject method.
The ScriptableManagedType class definition appears after the Page constructor.
ScriptableManagedType has one method named SimpleMethodExample that has the ScriptableMember attribute. SimpleMethodExample calls the HtmlWindow.Alert method with the passed-in string. It returns a string to the JavaScript function.
C#
public Page()
{
InitializeComponent();
// Create and register a scriptable object.
ScriptableManagedType smt = new ScriptableManagedType();
HtmlPage.RegisterScriptableObject("SL_SMT", smt);
}
public class ScriptableManagedType
{
[ScriptableMember]
public string SimpleMethodExample(string s)
{
HtmlPage.Window.Alert("You called the Silverlight 'SimpleMethodExample'\n" +
"and passed this string parameter:\n\n" + s);
return "Returned from managed code: " + s;
}
}
Visual Basic
Public Sub New()
InitializeComponent()
' Create and register a scriptable object.
Dim smt As ScriptableManagedType = new ScriptableManagedType()
HtmlPage.RegisterScriptableObject("SL_SMT", smt)
End Sub
Public Class ScriptableManagedType
<ScriptableMember> _
Public Function SimpleMethodExample(ByVal s As String) As String
HtmlPage.Window.Alert("You called the Silverlight 'SimpleMethodExample'" + _
vbCrLf + "and passed this string parameter:" + vbCrLf + vbCrLf + s)
Return "Returned from managed code: " + s
End Function
End Class
See Also
Send Feedback