Calling Javascript from Silverlight

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.

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:

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:

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! ;-)

Tags: ,


One Response to “Calling Javascript from Silverlight”

  1. The planet are truly secret by having temperate garden which are generally beautiful, rrncluding a jungle that is undoubtedly surely profligate featuring so a lot of systems by way of example the game courses, golf approach and in addition private pools. Hotel reviews

Leave a Reply