How to detect click on Chrome Back/Next/Reload buttons

Asked

Viewed 6,532 times

6

How do I detect when the user clicks on the Back/Forward/Reload buttons of Google Chrome?

I already made a scheme to make a check before the user exit the page through the elements of the page itself but I can’t know when it clicks the buttons of the browser itself.

Here’s 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>

27/08 - To be more exact, I would like to generate a warning for when the user closes the browser or tab, but the problem is that through onbeforeunload, every time he clicked on a link, pressed F5 or did anything that exits the page itself it displayed the message, then I put the locks above, but even so when the user clicks on the buttons of the browser it generates the message, I wanted through the above method to avoid this and leave the message only when it was closed the tab or the browser.

3 answers

3

Basically, the answer is: That 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 JS code that prevents the user from leaving the page. And this is not possible.

Javascript works through a console/emulator. Internal browser structures are not accessed by JS.

  • 2

    So, I’m turned on that there is no way to avoid but I wanted to at least display an alert message, that I already managed to do, just the way I did ta making that with any drive I make on the page display the message, so I did those above locks. At least I wanted to know if the user clicked on any of the buttons regardless of what, in other forums I was told to use onpopstate, it works but it hangs the user and does not let him back nor advance in the history.

  • @brunodotcom If this answer answered your question please mark with answered.

  • 1

    Actually still waiting for another answer, in other forums I saw the use of popstate but did not understand how to apply it

1

Following the response of @Rowaraujo not possible, but you can use refresh event.

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

Follow an example: DEMO

  • So I use it but it shoots all the time, not just when it’s gonna refresh

  • That’s the problem, it will shoot every time it tries to leave the page.

0

I think even the post being old.... always worth the update...

I think it’s possible...

This little code, can understand when the keyboard is used, capturing the keys CTRL+R or F5 or Backspace, and so decide how to treat the event.

There’s also a way to capture the event "Back Boot of the Navigator", but for this was used the History of the Navigator. Where you can also choose how to treat the event. With this "control of history" one can even CANCEL the boot "Browser back"....

please check the code below... When the proposal is displayed "a warning message" ONLY if clicked on a favorite, or typed a new address in the URL bar... When any kind of back, Reload, or click on buttons of the same page, should not appear the "warning exit page"

        // 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 speaking, in the tests I did... it just doesn’t work on safari...

Already in Firefox Mozilla and Iexplorer, they work almost 100% but with a few caveats in Firefox...

I keep searching, if anyone has more tips and considerations please share! Mainly because I would like to control when the user presses the "Reload button" of the browser.

[]s Sena

Browser other questions tagged

You are not signed in. Login or sign up in order to post.