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

I am using onbeforeunload function. I want to alert another message when you click the browser button, browser refresh button, browser close button and browser close button. Since I can track all events inside onbeforeUnload.

My code structure is like

<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");


Any idea to fix this? Many thanks.


source to share

3 answers

As far as I know you don't want to. For security reasons, most browsers don't allow this kind of thing.

You can, however, catch a few things. Like keydown

a key f5

. So you can do something in there before the "onbeforeunload" function is fired if you like.

But you cannot bind an event to a back button, for example. Or "ctrl + r".

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



Thank you very much for your answer. But I found the code

if (window.event) {

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


yet {

      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 works in IE



you can do some little things before the client closes the tab. javascript detect browser close tab / close browser , but if your action list is large and the tab is closed before it is finished you are helpless. You can try 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



All Articles