Skip to content →

Using Silverlight and JavaScript to prevent leaving a webpage

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:

 
<scriptlanguage="javascript"type="text/javascript">
window.onbeforeunload = askConfirm;
function askConfirm() {
    var control = document.getElementById("silverlightControl");
    var preventLeave = control.Content.Page.PreventLeave();
    if (!preventLeave) {
        return;
    }    var message = control.Content.Page.LeaveRequested();
    return message;
}
</script>

The silverlight code:

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

[ScriptableMember]
public string LeaveRequested()
{
    return "You have unsaved changes to your current document?";
}

[ScriptableMember]
public bool PreventLeave()
{
    return (bool)PreventLeaveCheckBox.IsChecked;
}

Published in Development Web

2 Comments

  1. Hitesh Panchal Hitesh Panchal

    Hi Jonny,

    Many thanks for your great suggestion !!

    Thanks & Regards,
    Hitesh Panchal

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.