Silverlight - Prevent users from losing changes by using the browser back button

image

Do you know how to prevent users from losing changes in your Silverlight application, if they click the "back button" or "close browser" button?

#1
Add this method to your main page (if using Silverlight navigation framework) or user control (if Silverlight app)

 
        public void RegisterOnBeforeUnload()
        {
            //Register Silverlight object for availability in Javascript.
            const string scriptableObjectName = "SilverlightClientControl"; // <-- THIS IS THE NAME OF YOUR HOSTING OBJECT IN THE WEB PAGE
            HtmlPage.RegisterScriptableObject(scriptableObjectName, this);


            //Start listening to Javascript event.
            string pluginName = HtmlPage.Plugin.Id;
            HtmlPage.Window.Eval(string.Format(
                @"window.onbeforeunload = function () {{
                   var slApp = document.getElementById('{0}');
                   var result = slApp.Content.{1}.OnBeforeUnload();
                   if(result.length > 0)
                       return result;
               }}", pluginName, scriptableObjectName)
                    );
        }  

Figure: Method that will register your Silverlight object for availability in JavaScript and start listening on JavaScript events

 

#2
Call the top method "RegisterOnBeforeUnload" in the constructor of your control

 

#3
Add this to the same user control

        [ScriptableMember] 
        public string OnBeforeUnload() 
        { 
            if (MainViewModel.HasUnsavedChanges) 
                return "You have unsaved changes! Please save them before leaving the application."; 
            return string.Empty; 
        } 
  

Figure: "MainViewModel.HasUnsavedChanges" is the flag if the exit is allowed without warning or not (= user clicks on "Exit Auction" which exits normally)

#5
Done

 

image 
Figure: Now when you want the users is in the middle of a change and navigates away, he gets a nice warning!
This fires on the "Back button", "Close tab" or "Close browser", which is awesome!

 

 

image

PS
You could even automagically save the changes when the user closes the browser!!

Latest Posts

Popular Posts