0

I am trying to bind an event on before leaving a page, but except, when the back button is pressed. This is my code for the event:

    window.onbeforeunload = (e) => {

    if(something){
        // do my custom code
    }
};

It works, but it binds and when the back button is pressed. This a normal logic, of course, but I need to find a way to check, is it back button pressed inside onbeforeunload. Something like this:

if(something && !isBackButton){
        // do my custom code
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
gdfgdfg
  • 3,181
  • 7
  • 37
  • 83

1 Answers1

1

I think onbeforeunload will work better for your situation. You can check intercept-page-exit-event

$(document).ready(function() {
    isBackButton = false; 
    window.onbeforeunload = backHandler;
});

function backHandler() {
    if (isBackButton) {
        // do something's
    }
}

$("button.back").click(function() {
    isBackButton = true;
});

The above code checks the isBackButton variable if it's true then it will execute your code. Whenever click on back button value is changed, isBackButton variable is set to true.

Abdelrhman Arnos
  • 1,404
  • 3
  • 11
  • 22