Posts Tagged ‘Javascript’

Calling Javascript from Silverlight

Thursday, May 6th, 2010

Over the past month or two, I’ve been learning Silverlight at work, so I might put up a few posts when I encounter interesting topics. The solutions I post might not be the best way of doing things, obviously ;-)

Integrating Silverlight into a rich, Javascript-driven website, I found myself wanting to call Javascript functions from Silverlight. A quick Google search told me this was possible, using the HtmlPage.Window.Invoke method. You could also use the Eval method, but it feels like a dirty hack,
so let’s not go there.

?View Code CSHARP
1
2
3
4
private void displayDialog(string message)
{
	HtmlPage.Window.Invoke("showSomeDialog", message);
}

Easy, right? But like a good Javascript-coder, I like to “namespace” my methods, instead of leaving lots of global functions around. The invoke method seems to call global objects only, so I can’t do Invoke(“Rexxars.showSomeDialog”, “message”) – which is a shame. So I thought to myself, I’ll just create a “proxy” function which calls methods in my namespace. Simple:

?View Code JAVASCRIPT
1
2
3
4
5
function slBridge(method, arg) {
	if(Rexxars[method]) {
		Rexxars[method](arg);
	}
}

Now I can do: HtmlPage.Window.Invoke(“slBridge”, “showSomeDialog”, message); – cool. But what if I want to call a function with more than one argument? I further improved my Silverlight-Javascript “bridge” to support a variable number of arguments:

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
function slBridge() {
	// Turn the arguments object into a regular, usable array
	var args = Array.prototype.slice.call(arguments);
	// Method name is the first argument and should not be included
	var method = args.shift();
	// Make sure the method exists inside our namespace
	if(Rexxars[method]) {
		// Call the method with the arguments passed
		Rexxars[method].apply(null, args);
	}
}

Simple, eh? Now I can use the slBridge function to call any method inside my Rexxars namespace, with different number of arguments in each. Sweet! ;-)