Silverlight Browser Integration aka HTML Bridge

Sat, March 8, 2008, 11:12 AM under Silverlight
Given that Silverlight applications sit in the browser via a plug in, it would be silly if you couldn't interact from managed SL code with other browser elements, such as html elements and script so that you could, for example, reuse existing assets. I have heard the browser-agnostic integration featured described as HTML Bridge and it is implemented in the System.Windows.Browser.dll assembly in a same named namespace. You can see the types from that namespace on the following image (click on it for the expanded version):


The important inheritance hierarchy to be aware of is that HtmlDocument and HtmlElement inherit from HtmlObject (that allows handling script events via AttachEvent) which inherits from ScriptObject (that allows you to execute scripts via its Invoke and InvokeSelf methods). HtmlPage is a great entry point because you can navigate across its Window property to an HtmlWindow (that allows e.g. to Navigate URLs) and across its Document property to an HtmlDocument (that offers e.g. access to Cookies and QueryString). Also note the 2 Attribute classes: ScriptableType and ScriptableMember. Those are used for exposing Silverlight managed classes to script in the browser combined with HtmlPage.RegisterScriptableObject and RegisterCreateableType methods. Open the expanded class diagram in a separate window and identify the aforementioned methods. Notice there how HtmlDocument allows you to create new elements and retrieve existing ones (CreateElement and GetElementById). Once you have references to those HtmlElements you can do things like SetAttribute, SetStyleAttribute and AppendChild to name a few. Script events are handled in your managed ScriptEventHandler method that accepts an HtmlEventArgs which you can find on the class diagram along with its relationships (e.g. MouseButtons). You should also checkout the HttpUtility class and its self-explanatory methods such as UrlEncode.

Phew! Take a moment to study the two class diagrams using the previous paragraph as a guide and also note that all links above are direct links to the API documentation (i.e. this blog post becomes my bookmark into MSDN ;)). You can also follow a quickstart (DOM access), two walkthroughs (calling managed from script and script from managed), and for those that want even more, follow this 2-hour lab (ZIP).

To see some of the browser integration in action, I have here the ugliest and most basic SL app that simply proves some of the concepts.