Black
Black

Reputation: 20302

How to react to sub events from onbeforeunload?

I noticed that the event onbeforeunload is able to distinguish between different user actions, e.g. whether the user pressed on a link on the page, the user tried to close the page, the user wanted to go one page back etc.

For example if a user clicks on a link, then a confirm box with the text "Are you sure that you want to close the page?" prompts, but if the user presses F5 to refresh the page, then the text of the box is "Are you sure that you want to refresh the page?".

Is it possible to distinguish the different sub events from onbeforeunload and react to it?

What I try is to change the background-color of my page to red if the user tries to leave the page, and to orange if he tries to refresh the page, thats just a simple test action for better understanding.

NOTE: I translated the text from the prompt from German to English, so the text could be different.

SIDE QUESTION: Why does the confirm box appears twice if i click on the link and press "Leave page" if i run this code on my local webserver, but not if i run it on stackoverflow?

function ask()
{
  return "Are you sure?";
  
  //How can i find out what the user actually tried? 
  //e.g. did he tried to refresh the page? Or did he tried to close it?
  //PSEUDO CODE:
  //  if (user_tried_reload) { alert("RELOAD"); }
  //  else if (user_tried_close) { alert ("CLOSE"); }
}
<body onbeforeunload="return ask()">
    <h1>onbeforeunload Test</h1>
    <a href="http://www.google.de">Google</a>
</body>

USAGE: Press on "Run code snippet" and then whether click on the link or try to refresh the page.

Upvotes: 1

Views: 350

Answers (1)

zerohero
zerohero

Reputation: 583

The reason why the code fires twice is because the "Leave Page" button re-triggers the unload event.

What I suggest you do is catch the F5 keypress event and do your own message:

document.onkeydown = function(evt) {
    evt = evt || window.event;
    if (evt.keyCode == 116) {
        ask('reload');
    }
};

In your ask() function, I'd so something like this:

var howmanytimes = 0;
function ask(action)
{
  howmanytimes++;

  //PSEUDO CODE:
  if (howmanytimes == 1) {
     if (action == 'reload') { alert("RELOAD"); }
     else { alert ("CLOSE"); }
  } else { howmanytimes == 0 };
}

This code is untested and I don't have access to jsfiddle from where I am, hope this points you in the right direction (and that I understood the question correctly in the first place!)

Upvotes: 1

Related Questions