Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Quick and dirty way to ask/warn user when navigating off the page.

0.00/5 (No votes)
20 Feb 2012 1  
Problem:
I want to warn user before navigating off the current page that one could lose unsaved data etc.
It may seam trivial, but this was my first beginner's roadblock when shifting from desktop-based to web-based solutions and after some time has passed I felt obliged to share my solution and help some wandering beginner.

Solution:
You can hook up your questioning logic on onbeforeunload event.
In your page's markup you should add following code:
XML
<script language="JavaScript" type="text/javascript">
   window.onbeforeunload = confirmExit;

   function confirmExit() {
       return "Ask the user whether he/she really wants na navigate off the page.";
   }

</script>

This will warn user every time.

There is however one major issue - post back, then code shown above becomes major annoyance.
For instance, you don't want to have popup warning when selecting new value from filtering drop down list or when clicking on submitting button...

Easy way to avoid such behavior is to add following code in markup on every control responsible for post back.

window.onbeforeunload = null;

It will stop firing onbeforeunload event and code mentioned above won't execute.
No popup on awkward place :).

for instance
XML
<asp:DropDownList ID="ddlTip" runat="server" DataSourceID="tipSqlDataSource" DataTextField="Naziv" DataValueField="TipArtiklID" AutoPostBack="True" CssClass="dropDownList" onchange="window.onbeforeunload=null">
</asp:DropDownList>

or
XML
<asp:Calendar ID="calendar" runat="server" onclick="window.onbeforeunload=null">
</asp:Calendar>


Some controls (such as buttons), have OnClientClick property where you can easily add desired javascript snippet in code behind as well.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if(!this.IsPostBack)
    {
        btnOK.OnClientClick = "window.onbeforeunload=null";
    }
}



I hope this helps.
Please warn me for grammar and spelling mistakes.
And please if you know something better, share it!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here