Recently I have been thinking about applications with data input and the problems of being in a browser. One of the perils of being in a browser is that a user may have some unsaved data input tasks. The data can be easily lost by accidently navigating to a different webpage, closing the browser or closing the tab.

Preventing this is relatively easy making use of Silverlight and JavaScript communication in conjunction with the window.onbeforeunload function. See below for example and code snippets. 😀

Sample Application

The javascript:

window.onbeforeunload = askConfirm;
function askConfirm() {
    var control = document.getElementById("silverlightControl");
    var preventLeave = control.Content.Page.PreventLeave();
    if (!preventLeave) {
    }    var message = control.Content.Page.LeaveRequested();
    return message;

The silverlight code:

public MainPage()
    HtmlPage.RegisterScriptableObject("Page", this);

public string LeaveRequested()
    return "You have unsaved changes to your current document?";

public bool PreventLeave()
    return (bool)PreventLeaveCheckBox.IsChecked;