php/javascript prevent page reload/refresh -


in project have php page whant in case of browser reload, or f5 page redirect one. have insert code:

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

if instead of window.location.href instruction insert alert("test"); code run, code in case of refresh page cannot redirect index.html. why?

you can capture f5 or ctrl+r keypresses , handle events before redirect. although changing default browser behavior may considered evil , more of annoyance website users.

here have provided example function handle redirecting user when try refresh page. http://jsfiddle.net/dqeew/

the heart of , handles location change 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 set true otherwise.           }         }     }); 

the function based on another answer have limited handle f5 , expanded bit handle ctrl+r. can limit keyboard driven refreshes though.

pulling yet answer may want capture page unloads , return string, warn users trying hasn't been designed do.

window.onbeforeunload = confirmexit;   function confirmexit()   {       return "you have attempted leave page.  if have made changes fields without clicking save button, changes lost.  sure want exit page?";   } 

that should give opportunity address reason want leave , chance them cancel it.


Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -