I am creating a user quiz which is timed at 3 minutes per question. How can I make it so that a user can not press back o开发者_StackOverflow社区r refresh or even if they do press it either nothing happens or they get a message that they will get 0 points if they do press it. I tried an alert box to do this but when the alert box opens up the clock stops. Anyone has any idea how this can be achieved?
You could try using a database instead of javascript to enforce the time limit.
+-------+-----------+----------+--------+------+
|user_id|question_id|start_time|end_time|answer|
+-------+-----------+----------+--------+------+
You just have to make sure that (user_id, question_id)
is unique and if they take more than 3 minutes, they get a 0 on the question.
This also allows you to stop them from answering the same question more than once.
As suggested elsewhere, you cannot override the back or refresh behavior. However, you can perform an action (such as pop up a message) to the user when they attempt to leave the page:
<body onbeforeunload="return confirm( 'If you leave this page, you will receive 0 points. Stay on page?' );">
Please note that this type of interference is annoying to users, and should not be used on general audiences. In the context of an authoritative quiz, however, this may be acceptable.
Please also note that some browsers (Opera, for example) do not support onbeforeunload.
You may need to limit the browsers your test-takers can use.
The back button behavior depends on the user/browser, which means there's no way to disable the back button itself. There are several workarounds such as opening a new window and reference the counter from the parent window. But disabling the back button itself it's not possible
If you store the current question displayed in a session, even if the user clicks back it will always show the question they where on.
But that would obviously reset the (javascript) timer as well. To cope with that, store the timestamp upon showing the question in that same session and validate that upon submitting could be an idea. Combine that with the javascript "onbeforeunload" as stated by George Cummins to inform the users of the consequences of their action.
So, when loading the question:
$_SESSION['current_question']['id'] = $question['id'];
$_SESSION['current_question']['timestamp'] = time();
And when submitting the answer:
if((time() - $_SESSION['current_question']['timestamp']) =< 180)
{
// Decide the amount of points earned
$score = ...
}
else
{
// User took more than 3 minutes, set score to 0;
$score = 0;
}
精彩评论