This is a mirror of official site: http://jasper-net.blogspot.com/

Silverlight Tip of the Day #15 – Communicating between JavaScript & Silverlight

| Thursday, March 24, 2011
Communicating between Javascript and Silverlight is, fortunately, relatively straight forward. The following sample demonstrates how to make the call both ways.

Calling Silverlight From Java script:

In the constructor of your Silverlight app, make a call to RegisterScriptableObject().This call essentially registers a managed object for scriptable access by JavaScript code. The first parameter is any key name you want to give. This key is referenced in your Javascript code when making the call to Silverlight.
Add the function you want called in your Silverlight code. You must prefix it with the [ScriptableMember] attribute.
In Javascript, you can now call directly into your Silverlight function. This can be done through the document object. From my example below: document.getElementById("silverlightControl").Content.Page.UpdateText("Hello from Javascript!"); where “silverlightControl” is the ID of my Silverlight control.
Calling Javascript From Silverlight:

Javascript can be directly called via the HtmlPage.Window.Invoke() function.
Example for both:

Page.xaml:

namespace SilverlightApplication
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
 
            HtmlPage.RegisterScriptableObject("Page", this);            
            HtmlPage.Window.Invoke("TalkToJavaScript", "Hello from Silverlight");
        }
 
        [ScriptableMember]
        public void UpdateText(string result)
        {
            myTextbox.Text = result;
        }
    }

Default.aspx:

<script type="text/javascript"> 
        function TalkToJavaScript( data)
        {
            alert("Message received from Silverlight: "+data);
            
            var control = document.getElementById("silverlightControl");            
            control.Content.Page.UpdateText("Hello from Javascript!");
        }    
</script>

Page.xaml:

<UserControl x:Class="SilverlightApplication7.Page"
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <TextBlock x:Name="myTextbox">Waiting for call...</TextBlock>
    </Grid>
</UserControl>

Posted via email from Jasper-net

0 comments: