Javascript communication to Silverlight 2.0
Tonight working with a proof of concept in regards to the communication between Javascript and Silverlight 2.0 has 2 attributes to help you with the task.
Class attribute [ScriptableType], method attribute [ScriptableMember].
There are a few steps to follow. You need to create a Javascript control and register it with a name to be able to access from Javascript. This is pretty important, make sure you add a unique name per class and mark the class with ScriptableType. Then create the method that you want to have access from JavaScript and mark it with ScriptableMember
Create a User Cointrol in Silverlight.
<UserControl x:Class="SilverlightApplication1.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Canvas Height="200" Width="200">
<TextBox x:Name="TestText" Text="Something"></TextBox>
</Canvas>
</UserControl>
[ScriptableType]
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
HtmlPage.RegisterScriptableObject("SilverlightApp", this);
}
[ScriptableMember]
public void SendToSilverlight(string sMessage)
{
HtmlPage.Window.SetProperty("status", sMessage);
TestText.Text = sMessage;
}
}
On the javascript side.
<head runat="server">
<title>Test Javascript and Silverlight</title>
<script type="text/javascript" language="Javascript">
function sendto() {
var sText = document.getElementById('Text1');
var silverlightControl = document.getElementById('Xaml1');
silverlightControl.Content.SilverlightApp.SendToSilverlight(sText.value);
}
</script>
</head>
<body style="height:100%;margin:0;">
<form id="form1" runat="server" style="height:100%;">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div style="height:100%;">
<input id="Text1" type="text" />
<input id="Button1" type="button" value="button" onclick="sendto();"/>
<asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/SilverlightApplication1.xap" MinimumVersion="2.0.30523" Width="100%" Height="100%" />
</div>
</form>
Results.
What about calling JavaScript from Silverlight?
HtmlPage.Window.Invoke("myJavascriptFunction", “text to javascript”);
Related links.
Silverlight 1.1 interaction with javascript
Silverlight interoperability
Download code and solution here
Hope that helps,
Cheers
Al
Posted from
http://weblogs.asp.net/albertpascual