javascript - How to prevent logging out automatically when the back button is clicked?

I am using code to logout of application automatically when the browser is closed, but the impact of the code is when I press the browser's back button and navigate to another page then also it automatically logout from the application.
I want my code to logout automatically only when the browser is closed and not when I am navigating through back button
can you help me in this, Thanks
Here is my code
$(window).on('mouseover', (function () {
window.onbeforeunload = null;
}));
$(window).on('mouseout', (function () {
window.onbeforeunload = ConfirmLeave;
}));
function ConfirmLeave() {
$.get("call to a php code to logout");
}
var prevKey="";
$(document).keydown(function (e) {
if (e.key=="F5"){
window.onbeforeunload = ConfirmLeave;
}else if (e.key.toUpperCase() == "W" && prevKey == "CONTROL") {
window.onbeforeunload = ConfirmLeave;
}else if (e.key.toUpperCase() == "R" && prevKey == "CONTROL") {
window.onbeforeunload = ConfirmLeave;
}else if (e.key.toUpperCase() == "F4" && prevKey == "ALT") {
window.onbeforeunload = ConfirmLeave;
}
prevKey = e.key.toUpperCase();
});
The php code is
$this->session->sess_destroy();
$this->load->driver('cache');
$this->cache->clean();
ob_clean();
redirect("login page");
Answer
Solution:
onbeforeunload event occurs when we close the browser and also when we press the back button. It fails to distinguish between the 2 actions.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: xml parsing error: no root element found
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.