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:

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;

Published in Development Web


  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.