How do I detect when the user clicks the Chrome Back / Forward / Reload buttons?
I have already made a scheme to do a check before the user leaves the page through the elements of the page itself but I can not tell when he clicks the buttons of the browser itself.
Here is an example of what I did
<script language="javascript" >
var validNavigation = false;
var numPendencias = 0;
function verificaPendencias() {
var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the user to be able to leave withou confirmation
var leave_message = 'Existem pendências ativas, deseja mesmo sair?'
//Gera um aviso para o usuário para evitar que saia com pendências ativas
function goodbye(e) {
if (!validNavigation) {
if (dont_confirm_leave!==1) {
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = leave_message;
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
//return works for Chrome and Safari
return leave_message;
}
}
}
window.onbeforeunload=goodbye;
}
function atribuirEventos() {
// Attach the event keypress to exclude the F5 refresh
jQuery(document).bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
jQuery(document).bind('keydown', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
jQuery(document).bind('keyup', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
//Atribui uma função a todos links na página
jQuery("a").bind("mouseover", function() {
validNavigation = true;
});
jQuery("a").bind("mouseout", function() {
validNavigation = false;
});
//Atribui uma função a todos forms na página
jQuery("form").bind("submit", function() {
validNavigation = true;
});
//Atribui uma função a todos input do tipo submit na página
// Attach the event click for all inputs in the page
jQuery("input[type=submit]").bind("click", function() {
validNavigation = true;
});
//Atribui uma função a todos buttons na página
jQuery("button").bind("mouseover", function() {
validNavigation = true;
});
jQuery("button").bind("mouseout", function() {
validNavigation = false;
});
}
// Wire up the events as soon as the DOM tree is ready
jQuery(document).ready(function() {
verificaPendencias();
atribuirEventos();
});
</script>
To be more exact, I would like to generate a warning for when the user closes the browser or the tab, but the problem is that through onbeforeunload, every time he clicked a link, he pressed F5 or did anything that exits the page itself it displayed the message, so I put the locks up, but even so when the user clicks the browser button it generates the message, I wanted through the above method to avoid this and leave the message only when the flap or browser is closed.