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


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

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;
                @"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


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


Add this to the same user control

        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)



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!




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

Latest Posts

Popular Posts