How to call a JavaScript function from SilverLight ?
The simplest way which I found is by calling the Invoke method of the HtmlWindow class using the HtmlPage object.
As you can see the method take 2 arguments, first being the name of the function and second is the object array for parameters. HtmlPage class is available under System.Windows.Browser namespace.
How to call a SilverLight function from JavaScript ?
Lets take a simple scenario that we need a string trimming functionality on the client side. Since the Silverlight library already has this functionality buildin, we would try to reuse it by exposing a method from Silverlight and calling it from JavaScript.
I have created a separate class for the function to make is easy.
The function which we need to access from the client side should be marked with the [ScriptableMember] attribute.
The next step is to register the scriptable objects when the application is started.
The Application_Startup event can be found in the App.xaml file. The RegisterScriptableObject inturn calls the :
NativeHost.Current.RuntimeHost.RegisterScriptableObject & NativeHost.Current.BrowserService.ReleaseObject methods for the interop.
Now to access this registered object we need to handle the OnPluginLoaded event and get the reference of the entire silverlight control first.
Now we can use the silverLightControl object and access the registered methods like this :
Does this mean that a Silverlight control could access any of your client side code on the hosting page ?
No, we can disable the silverlight to access any of the html/client side content by setting the HtmlAccess property as below:
The default is set to “Enabled”.
Learning is Inevitable !!!