Stopping a user from leaving a Silverlight page

Like Flash, Silverlight applications only exist for the life of the page that hosts it.

A common complaint is that when you navigate away from your Silverlight page you get no chance to tidy up or warn the user…

Never fear, help is at hand! All browsers expose an event called window.onbeforeunload.

If you connect a method to that event handler, that returns a string, you will get a standard Message box that looks like this (Internet Explorer):



or like this (Chrome):

Your javascript  onbeforeclose method is expected to provide a string value to display in that Message box. It makes sense to return that from your Silverlight application, so we will actually kill two birds with one stone.

Here are the actual steps you need to hook into the onbeforeunload event…

1. Add a pluginloaded handler to your HTML page hosting the Silverlight application:

	var slCtl = null;
	function pluginLoaded(sender, args) {
		slCtl = sender.getHost();

This basically stores your Silverlight control object in a global (page) variable called slCtrl.

2. Specify the pluginloaded in your Silverlight object definition:

     <param name="onLoad" value="pluginLoaded" />

This ensures the previous handler is actually called.

3. Define an onClose javascript method and assign it to the onbeforeunload event:

	function onClose() {
		return slCtl.Content.App.OnBeforeClose();
	window.onbeforeunload = onClose

4. Register your Silverlight application object with Silverlight in your App.xaml.cs file Application_Startup event:

private void Application_Startup(object sender, StartupEventArgs e)
    this.RootVisual = new MainPage();
    HtmlPage.RegisterScriptableObject(“App”, this);

5. Expose a scriptable method in your application to do the cleanup and return the string to display:
public string OnBeforeClose()
    // Do some shutdown work here…
    return “This is where your custom message will be displayed”;

I am assuming you know how to put the Javascript into appropriate HTML script elements in your file.

This is guaranteed to run before the user gets the “Are you sure…” prompt. Just add your “shutdown” processing before you return from OnShutdown and voilà you now have a place to hook your code!

Unfortunately there is no way to stop the Message box, but it is better than your user leaving your Silverlight application before you want them to.

No Comments

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

You must be logged in to post a comment.

WordPress Themes