Posted By

Krummelz on 09/13/11


onbeforeunload navigate away

Versions (?)

Who likes this?

1 person have marked this snippet as a favorite


Javascript to warn the user that they will lose data if they go away from this page

 / Published in: JavaScript

Easy to use in C# ASP.NET: to prevent a user from losing data when navigating away from whatever page they are on, just add string setConfirmUnload = "setConfirmUnload(true);"; ScriptManager.RegisterStartupScript(this, this.GetType(), "", setConfirmUnload, true); to you code somewhere, or just call setConfirmUnload(true); from the onClick or onClientClick even of a link. To allow a link to navigate away, pass in false instead.

Might be handy on an ASP.NET master page.

  1. function setConfirmUnload(on) {
  2. window.onbeforeunload = (on) ? unloadMessage : null;
  3. }
  4. function unloadMessage() {
  5. return 'You have entered new data on this page. If you navigate away from this page without first saving your data, the changes will be lost.';
  6. }

Report this snippet  

You need to login to post a comment.