1

My application is MVC5, I want to alert the user when they close the browser tab. I found this solution Setting onbeforeunload on body element in Chrome and IE using jQuery, works great except I use location.href in few cases (custom command buttons inside Telerik grid). Tried the following:

 $(window).bind('hashchange', function() {
              validNavigation = true;
    }); 

To avoid asking the user if the want to leave the page. Is there a better way to alert the user before closing the browser tab?

Community
  • 1
  • 1
hncl
  • 2,295
  • 7
  • 63
  • 129
  • and why hashchange then? Question seems to be conflicting to me. – Bhojendra Rauniyar Apr 18 '16 at 06:52
  • Maybe haschange is not the right way to detect change in page location; could not the right way to override onbeforeunload when I use location.href. The solution used: $("a").bind("click", function() { validNavigation = true; }); – hncl Apr 18 '16 at 06:57

1 Answers1

0

Try this ;)

Need some modifications in this code:

window.onbeforeunload = function() {
  if(validNavigation){
    validNavigation = false;
    /* if this click is valid means user action is not close window or reload page then just return; */
    return;
  }

  /* Want to ask user before leaving the page */
  return "Are you sure you want to leave this page bla bla bla?"; // you can make this dynamic, ofcourse...
};


validNavigation = true;
$(document).on('click', '.validNavigation', function(){
  validNavigation = true;
});

Now what you need to do is add validNavigation class to all links for those you don't want to show onbeforeunload message to user;

UPDATE As per comment:

function gotopage(args){
  /* set validNavigation to true to don't show warning on page load; */
  validNavigation = true;
  window.location.href = [args];
}

For which action you don't wants to show the warning to user simply set validNavigation = true; and put statement after it may cause location change;

itzmukeshy7
  • 2,669
  • 1
  • 21
  • 29
  • Thank you, sounds like a good approach; however I could not find how I can add class to this: function gotopage(args) { window.location.href = [args]; } – hncl Apr 18 '16 at 16:26
  • When you don't want to show this warning to user either add class to `a` OR set `validNavigation = true;` for some action; – itzmukeshy7 Apr 19 '16 at 04:48
  • Worked great. Expect when using lightgallery lightbox. I had to add $('#lightgallery').bind("click", function () { validNavigation = false; });. Thank you – hncl Apr 20 '16 at 22:17
  • @hncl You need to add `validNavigation = true;` not `validNavigation = false;`; – itzmukeshy7 Apr 21 '16 at 09:59