AleMal
AleMal

Reputation: 2077

php/javascript prevent page reload/refresh

In my project i have a php page where i whant that in case of browser reload, or F5 the page redirect to another one. I have insert this code:

<script type="text/javascript">
window.onbeforeunload = function() {
    window.location.href = "../index.html";
}
</script>

If instead of window.location.href instruction i insert an alert("test"); the code run, but with my code in case of refresh the page cannot redirect to index.html. Why?

Upvotes: 0

Views: 631

Answers (1)

EHLOVader
EHLOVader

Reputation: 483

You can capture the F5 or CTRL+R keypresses and handle events before a redirect. Although changing any default browser behavior may be considered evil and more of an annoyance by your website users.

Here i have provided an example function to handle redirecting the user when they try to refresh the page. http://jsfiddle.net/dQEeW/

The heart of it and what handles the location change is this event binding.

$(document).bind('keydown', function( event ){
        if( event !== undefined ) {
          if( (event.keyCode == 82 &&
                event.ctrlKey
               ) || (event.keyCode == 116) 
            ) {
              event.keyCode = 0;

              if(destination) window.location.href =  destination;

            return !destination; //false if destination was set true otherwise.
          }
        }
    });

The function was based on another SO answer but I have limited it to only handle F5 and expanded it a bit to handle CTRL+R. You can only limit the keyboard driven refreshes though.

Pulling from yet another SO answer you may want to capture page unloads and return a string, to warn the users they are trying to do something it hasn't been designed to do.

window.onbeforeunload = confirmExit;
  function confirmExit()
  {
      return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
  }

That should give you the opportunity to address the reason they want to leave and a chance for them to cancel it.

Upvotes: 1

Related Questions