Silverlight: HTML Bridge


The Silverlight HTML bridge enables full integration with the browser and JavaScript. Capabilities include:

  • Access the Document Object Model (DOM).
  • Call JavaScript methods from managed code.
  • Call managed methods from JavaScript.
  • Seamlessly transfer datatypes from managed code to JavaScript and back.

It is extremely important to keep security in mind whenever dealing with web page integration. It is easy to accidentally create vulnerabilities which can be used for various malicious exploits. Therefore you should always take care when opening up communications in either direction and to validate the input of all method calls, events and properties.

The enableHtmlAccess embed property and the ExternalCallersFromCrossDomain deployment manifest attribute allow explicit control over communications for both same and cross-domain situations.

Accessing Managed Code from JavaScript

You may expose properties, methods and whole managed classes to JavaScript. This is done by marking your managed code with attributes and then by calling the RegisterScriptableObject(String, Object) method. This opens up many interesting possibilities in addition to simple integration with the hosting page. For example, performance intensive code could be written in managed code while keeping everything else on the page, or you could use the Silverlight isolated storage system as a local cache for data in addition to the browser's caching mechanism.

Managed Attributes

Attribute Description
ScriptableTypeAttribute Marks a property, method or event accessible to JavaScript.
ScriptableMemberAttribute Marks all public properties, methods, and events on a managed type accessible to JavaScript when registered using the RegisterCreateableType method.


The following demonstrates using the ScriptableTypeAttribute and ScriptableMemberAttribute. Note that using the ScriptableTypeAttribute also marks all public methods, events and properties as scriptable. To avoid this you should only use the ScriptableMemberAttribute on the items you wish to expose.

C# Example
Visual Basic Example

Next, we create an instance of our scriptable class and register it for use with JavaScript.

C# Example
Visual Basic Example

On the containing HTML page we create the Silverlight application and set the onLoad callback method.

Our JavaScript callback method gets a reference to the application instance and calls the managed Compute() method on the exposed ManagedComputation class.

Accessing JavaScript from Managed Code

Calling a global-level JavaScript method from managed code can be accomplished using the HtmlPage.Window.Invoke() method. In addition, all DOM objects inherit from the ScriptObject class making it possible to invoke methods on both native JavaScript objects and your own custom classes using the Invoke() and InvokeSelf() methods.


Further Reading

Related information on the web is listed below.