简体   繁体   中英

How to track browser refresh/back/tab close and browser close event in javascript or jquery

I am using onbeforeunload function. I want to alert different message when any one click on browser back button , browser refresh button ,browser tab close button and browser close button .So how can i track all the events inside onbeforeUnload functions .

My code structure is like that

<body  onbeforeunload="return closePage();">
<script type="text/javascript">    
function closePage() {
  if(back button click){
    alert("back button");
  } else if(refresh button click || f5){
    alert("refresh button click");
  } else if(browser tab close){
    alert("tab close");
  } else {
    alert("browser closed");
  }
}
</script>

Any idea to fix this? Thanks a lot.

To the best of my knowledge, what you want is not possible. For security reasons most browsers won't allow these kinds of things.

You can, however, catch a few things. Like keydown on the f5 key. That way you can do some stuff there before the "onbeforeunload" function runs if you like.

But you can't bind an event on the "back" button for instance. Or "ctrl+r".

So I'm afraid you'll have to reconsider your options, and go with some other solution.

Thankyou so much for reply.But i have found some code

 if(window.event){
               if (window.event.clientX < 40 && window.event.clientY < 0)
                 {
                    alert("Backbutton is clicked");
                 }
                 else
                 { 
                  return exitPage(); 
                }
            }
    else{

      if(event.currentTarget.performance.navigation.type == 2)
      {
          alert("Back button click in mozilla");
      }
      if(event.currentTarget.performance.navigation.type == 1)
      {
        return exitPage();
      }
}

Using this code i can track the back button event but it only working in IE

you can do some small things before the customer closes the tab. javascript detect browser close tab/close browser but if your list of actions are big and the tab closes before it is finished you are helpless. You can try it but with my experience donot depend on it.

window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";
  /* Do you small action code here */
  (e || window.event).returnValue = confirmationMessage; //Gecko + IE
  return confirmationMessage;                            //Webkit, Safari, Chrome
});

https://developer.mozilla.org/en-US/docs/Web/Reference/Events/beforeunload?redirectlocale=en-US&redirectslug=DOM/Mozilla_event_reference/beforeunload

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM