3

I want to have a confirm box when user tries to close the window.

window.onbeforeunload = function (evt) {
    var message = 'Are you sure you want to leave, cause there are some unsaved changes?';
    if (typeof evt == 'undefined') {
        evt = window.event;
    }
    if (evt) {
        evt.returnValue = message;
    }

    return message;
}

The thing is I want to check a variables value

var sncro = 1;

If its value is not equal to one then this confirmation box should be there, else no need to have a confirmation. I'm not able to figure this. Its so silly but I request anybody can have a look on the code.

dashdashzako
  • 1,268
  • 15
  • 24
Mohit Jain
  • 43,139
  • 57
  • 169
  • 274

1 Answers1

1

I assume that on page load, you are setting up var sncro=1; and when some data changes, you adjust this value. Here is the quick check:

window.onbeforeunload = function (evt) {
  if (sncro != 1) {
   var message = 'Are you sure you want to leave, cause there are some unsaved changes?';
   if (typeof evt == 'undefined') {
      evt = window.event;
   }
   if (evt ) {
      evt.returnValue = message;
   }
   return message;
  }
}
Fenton
  • 241,084
  • 71
  • 387
  • 401
  • @Sohnee: I would consider using '!=='. What you have should work, but the concept of truth and implicit type conversion in js can be quite confusing. – Mads Ravn Mar 16 '10 at 08:48
  • @Mads Ravn - I agree with !== especially when comparing to 0 - but I never go too far down "JSLint" territory when talking about other people's code as you just never know where they decide to do blah = "1"; if (blah !== 1)... – Fenton Mar 22 '10 at 09:39
  • @Fenton - Can I write my own javascript code instead of this confirmation box. – Musaddiq Khan May 18 '17 at 07:49
  • 2
    Any specific method to use only on browser or tab close action rather than using on navigation ? – dipak_pusti May 24 '17 at 06:38