0

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?

10
  • 3
    You can't prevent this. Commented Jan 31, 2014 at 14:24
  • 1
    This is to prevent pages from preventing you from closing them. Imagine what a pain it would be if browsers could keep redirecting you when you try to close a page. Commented Jan 31, 2014 at 14:25
  • And how is possible prevent the refresh on my php page? Commented Jan 31, 2014 at 14:28
  • possible duplicate of how to redirect when user closes window or tab Commented Jan 31, 2014 at 14:29
  • 1
    Cache the results from the ajax calls to prevent running them multiple times Commented Jan 31, 2014 at 15:19

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.