防止用户刷新页面,重定向

时间:2014-08-21 12:36:56

标签: javascript angularjs redirect refresh

我正在创建一个测验网络应用程序,在游戏过程中我想阻止用户刷新页面,这样计时器就不会重启。

我的应用程序在游戏结束时自动保存得分(当所有问题都得到解答或时间结束时),但问题是当我刷新页面时(在时间结束之前)它仍在工作(计时器重启,所以玩家可以作弊并有更多时间思考和回答,甚至检查正确的答案)

我试图阻止刷新事件,我可以停用F5并重新加载按钮但是在地址栏上按下输入仍然有效..我意识到不可能阻止所有刷新事件,所以我试着想到不同:< / p>

  1. 当玩家点击刷新时,我希望他被重定向到主菜单。
  2. 播放的类别将自动停用(因此刷新将被视为作弊)
  3. 任何JS脚本都可以帮助我做到这一点吗?

    如果您对此类应用程序有任何其他建议也会很好。

3 个答案:

答案 0 :(得分:0)

这是一个技巧。只需在用户浏览器中设置cookie一段时间,然后检查cookie是否存在。如果它在那里,他试图刷新页面,而不是你应该将它重定向到主页面,而不是你可以删除cookie。您的代码应如下所示

 <?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
?>

希望这有助于你

答案 1 :(得分:0)

您可以使用window.onbeforeunload来检测页面的更改并执行某些操作

    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';

   };

答案 2 :(得分:0)

以下是jquery中可能对您有帮助的一些示例。

// 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);