How to detect the click on the Back / Forward / Reload buttons in Google Chrome

6

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.

    
asked by anonymous 26.08.2014 / 18:35

3 answers

3

Basically, the answer is: This is not possible !

JavaScript does not have access to these browser features, so JavaScript has no way to detect when the user pressed the Back, Forward, and Restart button.

From what I understand, you want to create a code in JS that prevents the user from leaving the page. And that's not possible.

JavaScript works through a console / emulator. The internal browser structures are not accessed by JS.

    
27.08.2014 / 05:09
1

Following the response from @RowAraujo is not possible, but you can use the refresh event.

window.onbeforeunload = function(e) {
  return 'Evento disparado!!';
};

Here's an example: DEMO

    
27.08.2014 / 13:48
0

I think even the post being old .... it's always worth updating ...

I think it's possible ...

This small code can see when the keyboard is used by capturing the CTRL + R or F5 or BackSpace , and thus decide how to handle the event.

There is also a way to capture the " Browser Back " event, but for this the Browser History was used. Where you can also choose how to handle the event. With this "history control" you can even CANCEL the " Browser Back " button. ....

Please enter the code below ... If the proposal is to display a "warning message" ONLY if a favorite is clicked, or a new address is typed in the URL bar ... When any type of back is triggered, reload , or click on the buttons on the same page, the "" warning of the page should not appear "

        // para o botao voltar do navegador

detectedBrowser= Qual_Eh_o_Seu_Browser?;

if(detectedBrowser==InternetExplorer){history.pushState( "nohb", null, "URL_Corretaaaaa" );}
else    {history.pushState( "nohb", null, "" );}

window.onpopstate = function(event) {               // JS version
//  $(window).on( "popstate", function(event){          // Jquery version
    console.log('MESSAGE  213 = ' + flag_beforeunload ) 
    if( !event.state ){                             // JS version
//      if( !event.originalEvent.state ){               // Jquery version

            // para desabilitar o botao BACK do navegador, descomente as linhas abaixo:
            //  history.pushState( "nohb", null, "" );
            //  return;

            // para tratar o evento UnBeforeUnload voce tem as linhas abaixo..  modifique conforme sua necessidade... neste exemplo ele so volta uam pagina, sem pop up.
                flag_beforeunload=false;
             window.history.back();


    }
};


//
//escutando o teclado
//

    document.onkeydown = KeyCheck;
    function KeyCheck(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;}        
        if(e.keyCode == 91) {flag_beforeunload=false;}      // safari
        if (e.keyCode == 82) {flag_beforeunload=false;}     // safari

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



//
// o evento UnBeforeUnload
//
        window.onbeforeunload = function(e){
            var msg = 'Deseja mesmo sair?';
            e = e || window.event;

            if(e)
                if (flag_beforeunload == true) {
                    return msg;
                }
        }

Remember, every browser is different ... But roughly, in the tests I've done ... it just does not work on safari ...

Already in FireFox Mozilla and IExplorer, they work almost 100% but, with some caveats in FireFox ...

I'm still searching, if anyone has more tips and considerations please share! Mainly because I would like to control when the user press the "reload button" of the browser.

[] s Seine

    
22.04.2016 / 06:29