Skip to content Skip to sidebar Skip to footer

How To Disable Warning By "onbeforeunload" When "reload" Same Page?

My code works well, but I do not need this 'beforeunload warning' when reloadind same page (reload button ou F5 key) , or when a click in the 'back' button... My original working c

Solution 1:

You can't do that. A page refresh is like navigating away and unloading the DOM so the onbeforeunload event will always be called but you can prevent it using jquery for keys pressed for Ctrl + R or F5 and Backspace.

For Ctrl + R use this:

$(document).keydown(function (e) {
    if (e.keyCode == 65 && e.ctrlKey) {
        e.preventDefault();
    }
});

For F5 use this:

$(document).keydown(function (e) {
    if (e.which || e.keyCode) == 116) {
        e.preventDefault();
    }
});

Solution 2:

First of all, let me say that, ""I do not want"" stop reloading the page! BUT controll the beforeunload message!

So if you allow me, I will try to explain:

  • A) I just want do DECIDE in that event I show (or not) the "warning exit message"

As far everyone say to me that, "it is impossible" do control UnbeforeUnload event, I make some tests and depending of the browser it is perfecty possible, BUT this is a "working progress rechearch"

So I know this:

  • 1) listening the keyboard it's very easy to "chose the event" and, what I want do show in the "warning mewssage" for each one.
  • 2) Listening the history I can chose what happends on "Navigator's Back button", dand do the same.
  • 3) The code below works fine in chome...

And to control the keyboard, I have this, very simple code in JS:

document.onkeydown = KeyCheck;
functionKeyCheck(e) {
    var key = (window.event) ? event.keyCode : e.keyCode;
    if(key==116) {flag_beforeunload=false;}     
    if(key==8) {flag_beforeunload=false;}       
    if (e.keyCode == 82 && e.ctrlKey) {flag_beforeunload=false;}        

    document.getElementById("container").innerHTML = "key = "+key + " - " + flag_beforeunload;
}


window.onbeforeunload = function(e){
    var msg = 'You are sure to exit?';
    e = e || window.event;

    if(e)
        if (flag_beforeunload == true) {

            return msg;
        }
}

Following, here (dotnsf site) is where I get the code for control the browser's "back button and"... I can even disable it.

but it is en Jquery, following is my code, but in JS:

window.onpopstate = function(event) {   

 window.history.back(-1)


            if( !event.state ){
            //the to lines below, disable the back button//  history.pushState( "nohb", null, "" );//  return;//  the following line iIcan use to control the envent, in UnBeforeUnload// flag_beforeunload=false;

            }
    }
}

And finaly, this is my question: I apreciate more help, and solutions for others navigators than Chrome!

Thanks a lot !

Post a Comment for "How To Disable Warning By "onbeforeunload" When "reload" Same Page?"