简体   繁体   中英

Pure javascript - Stop onbeforeunload event if button is clicked

I have a function I am adding to a large form for in house use only, the function will ask you if you meant to leave.

This is working just great, but it also prompts the alert when pressing "save" as this takes you to another page... So, I added a var and test against that vars value, I figured I could change the value if submit is clicked. I thought my code below would work, but alas it does not. Any ideas of why this does not work, also is there a way to stop the onbeforeunload from firing IF submit is clicked?

var trigger=1;
document.getElementById("edit-submit").onclick = function(){
   var trigger=2;
};
window.onbeforeunload = function (e) {
  if (trigger==1){
  var message = "You are editing your P3 - Are you sure you want to exit?",
  e = e || window.event;
  // For IE and Firefox
  if (e) {
    e.returnValue = message;
  }
}

I put a console.log inside the onclick function, and that shows up, so I know the onclick is working, its just not setting trigger = 2.. I am not sure if this is because:

A) The var is outside the scope of the unload function - I am not that good with scope yet.

B) The unload event always happens before the var is changed.

I have looked on google for anything the helps me with this and found nothing useful.

This creates a new variable, which is local to the onclick handler:

document.getElementById("edit-submit").onclick = function(){
  var trigger=2;
};

To affect the global variable, remove the var :

document.getElementById("edit-submit").onclick = function(){
  trigger=2;
};

I would remove the event handler with the button click.

document.getElementById("edit-submit").onclick = function(){            
    window.onbeforeunload = null;
};

Also i would set the handler only if not set on an input changed event.... but that is just me :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM