Catch onbeforeunload of hosting HTML page in ApplicationService?

Apr 12, 2011 at 2:44 PM
Edited Apr 12, 2011 at 2:46 PM

Hi community,

I just ran into the problem that Silverlight applications are inherently susceptible to data loss problems related to browser navigation buttons, F5 page refresh, tab closing, and browser closing events. If you don't take special precautions, your casual user can easily lose an arbitrary amount of work through an absent-minded click on the browser refresh button because even Silverlight Navigation Applications will simply reload the entire hosting HTML page in this case.

Seeing how it appears to be pretty easy to prevent data loss by inadvertently pressing F5 in about eight lines of code (slight adaptation of Peter Gfader's Blog):

   [ExportAsView("MainPage", IsShell = true)]
   public partial class MainPage : UserControl
      public ViewModelRoute ViewBindings { get { return ViewModelRoute.Create("MainPageViewModel""MainPage"); } }
      public MainPage()
         HtmlPage.Window.AttachEvent("onbeforeunload", HandleOnBeforeUnload);
      public void HandleOnBeforeUnload(object sender, HtmlEventArgs args)
         ViewModels.MainPageViewModel viewModel = this.LayoutRoot.DataContext as ViewModels.MainPageViewModel;
         if (viewModel != null && viewModel.HasUnsavedChanges)
            args.EventObject.SetProperty("returnValue""The application contains unsaved changes.");

I was wondering if it were a good idea to include this kind of functionality in Jounce's ApplicationService - or maybe in a separate LifecycleService.

A more general approach would probably publish a cancellable Unloading-Event in HandleOnBeforeUnload() via the EventAggregatorService and allow any interested application component to veto the unloading of the running Silverlight application.

What do you think?

Apr 15, 2011 at 3:00 AM

I like the idea of broadcasting it similar to how the unhandled exception is sent out. The reason is that it makes it easy to see who is "interested" in the message based on the method implementation. This is interesting and definitely something I'd like to look into to ... also curious about the community's take on this as well.

Thanks for starting the discussion!

May 2, 2011 at 9:07 AM

I do this as a matter of course in all HTML and SL apps so , yes, it would be great if this was baked into the framework.


May 31, 2011 at 9:57 AM

Doesn't work with Firefox (popup & hang), Opera (ignore) and Chrome (ignore).

Jun 6, 2011 at 1:56 PM
Edited Jun 6, 2011 at 1:57 PM

Contrary to my post above the firefox works with onbeforeunload. Firefox still hangs in Unittests (Nunit.Silverlight.Framework).