Thursday, May 8, 2008

Silverlight - Javascript communication - Part 1

Please don't confuse this with one of my earlier post which described how to do things with javascript without disturbing C#.

Here I am going to say how to accomplish communication between C# code in Silverlight and Javascript in aspx , html or any file which hosts Silverlight plug in.

Simple communication
Here I am using the Invoke() method of HTMLWindow class for communication.
  • Silverlight –> Javascript The data flow here is from Silverlight to Javascript.For accomplishing this we need to entities.
    1. Sender->Silverlight code which initiate the action.This is Invoke() method call now.
    2. Receiver -> Javascript function which is being called by Silverlight's Invoke method
    Silverlight
    private void Button_Click(object sender, RoutedEventArgs e){
    System.Windows.Browser.HtmlPage.Window.Invoke("ShowMsg", txtInput.Text);

    }

    Javascript

    function ShowMsg(msg)
    {
    alert(msg);
    }



  • Javascript -> Silverlight

    Here the data flow is from Javascript to Silverlight.i.e we returns some value from the javascript function to Silverlight .

    Javascript

    function GetData()
    {
    var reply = prompt("What's your name?", "");
    return (reply);
    }


    Silverlight


    private void Button_Click_1(object sender, RoutedEventArgs e){
    string o=(string)System.Windows.Browser.HtmlPage.Window.Invoke("GetData", "");
    txtOutput.Text = o;
    }

Sample here

Here initiator of all the communications is Silverlight.But what to do if Javascript has to start communication.For that we should be familiar with Scriptable attribute,ScriptObject etc..That will discuss later otherwise this post become a story. :-)

No comments: