Compartilhar via


Silverlight HTML Bridge FAQ

**

This FAQ provides answers to questions about Silverlight HTML Bridge. What is HTML Bridge? Why is HTML Bridge important? How do I use HTML Bridge classes in managed code? How do I call managed code from JavaScript? As well as several other questions, answers and code examples.

(This information relates to Silverlight 2 and ASP.NET)

What is HTML Bridge?

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.

 

Why is HTML Bridge important?

A Silverlight application runs within the Silverlight Plug-in. When you need to communicate between the Silverlight application and the rest of your Web page, you would commonly use HTML Bridge to transfer information, such as events, types and data.

 

In general, when would I use HTML Bridge?

You would commonly use HTML Bridge to:

· Control the HTML DOM from managed code.

· Attach events to HTML controls that are handled in managed code.

· Call managed code from JavaScript.

 

More specifically, what does HTML Bridge allow me to do?

HTML Bridge is an integrated set of types and methods that enable you to:

· 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.

 

Is it possible to hide the Silverlight plug-in and still use HTML Bridge?

Yes. The Silverlight plug-in does not need to have a visible UI to access the underlying DOM of the page.

 

What types can I use to access the HTML DOM from managed code?

HTML Bridge includes three main types that enable you to access and modify the HTML DOM from managed code:

· HtmlPage represents the Web page.

· HtmlDocument represents the document object.

· HtmlElement represents DOM elements.

 

How do I use the HTML Bridge classes in managed code?

To use the HTML Bridge classes in managed code, you must add a using or Imports statement accessing the System.Windows.Browser namespace. You can use the HtmlDocument.GetElementById method to access an HTML element from managed code if you include an ID with your HTML element. You can use the HtmlElement.GetProperty and HtmlElement.GetAttribute methods to get properties and attributes of an HTML element. Also, you can use the HtmlElement.SetProperty and HtmlElement.SetAttribute methods to set properties and attributes of an HTML element.

 

C#

    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

    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.")

 

Can you step me through an example of using the HTML Bridge classes?

First, you must create a Silverlight project with a linked Web Site project. For details, see Walkthrough: Integrating XAML into an ASP.NET Web Site Using Managed Code.

 

Next, locate your default.aspx page in your Web site project. Right-click the default.aspx page and select Set As Start Page. Also, add the following HTML to create two text boxes and a button.

HTML

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"/>

Add the following managed code to the page behind of the Page.xaml (Page.xaml.cs or Page.xaml.vb) file to 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

 

Next, add a ScriptManager control and a Silverlight control to your default.aspx page. Make sure the Source attribute of the Silverlight control points to the .xap file located in the ClientBin of your Web site project.

<asp:ScriptManager ID="ScriptManager1" runat="server">

</asp:ScriptManager>

<asp:Silverlight Source="~/ClientBin/htmlbridge01.xap" ID="Silverlight1"

  runat="server" Height="100px" Width="100px">

</asp:Silverlight>

 

Now you are ready to run this example. When you run it, you will see the textbox labeled “Input” is enabled and contains text. The text is populated from managed code.

 

What method do I use to attach a managed event handler to an HTML element?

This HtmlElement.AttachEvent method enables you to attach a Silverlight event handler to an HTML element. HtmlElement derives from HtmlObject, which includes the HtmlObject.AttachEvent method.

 

What would be a code example of attaching a managed 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 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");

    htmlEl.SetProperty("disabled", false);

    htmlEl.SetAttribute("value", "This text is set from managed code.");

    // Add an event handler for the Convert button.

    htmlEl = htmlDoc.GetElementById("Convert");

    htmlEl.AttachEvent("onclick", new EventHandler(this.OnConvertClicked));

}

void OnConvertClicked(object sender, EventArgs 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 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

 

How do I call managed code from JavaScript?

· Make the managed types and members scriptable.

· Include a JavaScript function that calls a managed method and returns an expected value.

 

How do I make the managed types and members scriptable?
To make the managed types and members scriptable, you need to:

· Mark the managed type and members using the appropriate attributes.

· Instantiate the marked managed type with the new operator.

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.

What would be an example of calling managed code from JavaScript?

Create a new Silverlight project with a linked Web site project. Added the following HTML to the default.aspx page:

HTML

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"/>

 

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.

· strIn references the input string.

· strOut references the output string.

· Content is an object that represents the plug-in area.

· SL_SMT is the name that is used to register the managed object show later in the managed code.

· SimpleMethodExample is the managed method name that will be marked as scriptable later in the managed code.

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>

The following shows the managed code in the Page.xaml (Page.xaml.cs or Page.xaml.vb) file that the above JavaScript Call_SL_Scriptable function calls. In the below 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

 

What is the Silverlight programming model?

When using the Silverlight programming model, you can choose one of three API variations: JavaScript interpreted by the browser, managed code, or dynamic languages interpreted by the dynamic language runtime (DLR). This FAQ focuses on the more common managed API approach for creating and running Silverlight applications.

You can use managed code to handle interaction with the Silverlight server control (a Silverlight 2 scenario) by using Visual Studio 2008 SP1 or Microsoft Expression Blend 2 SP1 to create a Silverlight application project that is compiled as a .xap package. This managed code contained within the .xap package can use HTML Bridge to transfer information between the Silverlight application and the rest of your Web page.

For more information about creating a Silverlight application using managed code, see Walkthrough: Integrating XAML into an ASP.NET Web Site Using Managed Code. For more information about Silverlight XAP, see ASP.NET - Silverlight XAP FAQ.

 

What is the managed Silverlight API?

The Silverlight managed API defines a set of objects as object trees that enable you to populate the initial content of a Silverlight-based application by loading XAML, and then adjust the object tree at run time. The Silverlight object tree is exposed through the Silverlight plug-in, which you create as a plug-in instance on a Web page. Silverlight uses the ActiveX plug-in model for Microsoft Internet Explorer, and uses the Netscape API plug-in model for other browsers. For more information, see Managed API for Silverlight.

 

What is XAML?

XAML stands for Extensible Application Markup Language. XAML simplifies creating a UI for the .NET Framework programming model. You can create visible UI elements in the declarative XAML markup, and then separate the UI definition from the run-time logic by using code-behind files, joined to the markup through partial class definitions. The ability to mix code with markup in XAML is important because XML by itself is declarative, and does not really suggest a model for flow control. An XML based declarative language is very intuitive for creating interfaces ranging from prototype to production, especially for people with a background in web design and technologies. Unlike most other markup languages, XAML directly represents the instantiation of managed objects. This general design principle enables simplified code and debugging access for objects that are created in XAML. For more information, see XAML Overview.

 

Do I have the latest Silverlight 2 plug-in or, where can I find it?

https://www.microsoft.com/silverlight/resources/install.aspx?v=2.0

What are the Compatible Operating Systems and Browsers for the Silverlight 2 plug-in?

Compatible Operating Systems and Browsers

 

What managed programming languages can I use to create a Silverlight 2 application?

C#, Visual Basic

 

What are some good links for additional information?

ASP.NET Controls for Silverlight

Silverlight FAQ

Why Silverlight?

Silverlight Resources

HTML Bridge (Contains many of the above code examples)

Comments