简体   繁体   中英

Prevent user from refreshing page, redirection instead

I am creating a quiz web app, during game play I want to prevent the user from refreshing the page so the timer doesn't restart.

My app auto-save score when the game is finished (when all questions answered or time is out), but the problem is when I refresh the page (before time is out) it is still working (the timer reboot, so the player can cheat and have extra time to think and answer, or even check correct answers)

I tried to prevent refreshing events, I could deactivate F5 and reload button but hitting enter on the address bar is still working.. I realized that it is not possible to prevent all refreshing events, so I tried to think different:

  1. When the player click refresh, I want him to be redirected to main menu.
  2. The category played will be automatically deactivated (so refreshing will be considered as cheating)

Any JS script can help me doing that?

If you have any other suggestion for such type of app that will be good as well.

Here is an trick for you. Just set an cookie in user browser for sometime and check if the cookie is there or not. If it is there he is trying to refresh the page and than you should redirect it to the main page and than you can delete the cookie. Your code should look like this

 <?php

if(isset($_COOKIE['Test']))
{
header("location:quiz.php");
}
else
{
// Your stuff
}
    setcookie("quiz1",$value, time()+3600*24); // name should be unique otherwise you won't be able to use it on the next page
?>

Hope this helps you

You can use window.onbeforeunload for detecting the change of page and doing some stuff

    window.onbeforeunload = function (e) {
    var e = e || window.event;
    // Do some controls here ...
    // Do synchrone call here ...
    // Message in the confirmation dialog

    // For IE and Firefox
   if (e) {
     e.returnValue = 'Are you sure want to quit this quiz';
   }

   // For Safari
   return 'Are you sure want to quit this quiz';

   };

Here are some examples in jquery that might help you.

// slight update to account for browsers not supporting e.which
function disableF5(e) { if ((e.which || e.keyCode) == 116) e.preventDefault(); };
// To disable f5
    /* jQuery < 1.7 */
$(document).bind("keydown", disableF5);
/* OR jQuery >= 1.7 */
$(document).on("keydown", disableF5);

// To re-enable f5
    /* jQuery < 1.7 */
$(document).unbind("keydown", disableF5);
/* OR jQuery >= 1.7 */
$(document).off("keydown", disableF5);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM