I am doing an online quiz application in PHP. I want to restrict the user from going back in an exam.
I have tried the following script, but it stops my timer.
Try it with ease :
history.pushState(null, null, document.title);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.title);
});
I had this problem with React (class component).
And I solved it easily:
componentDidMount() {
window.addEventListener("popstate", e => {
this.props.history.goForward();
}
}
I've used HashRouter
from react-router-dom
.
<script>
window.location.hash="no-back-button";
window.location.hash="Again-No-back-button";//again because google chrome don't insert first hash into history
window.onhashchange=function(){window.location.hash="no-back-button";}
</script>
Just set location.hash="Something"
. On pressing the back button, the hash will get removed from the URL, but the page won't go back.
This method is good for preventing going back accidentally, but for security purposes you should design your backend for preventing reanswering.
//"use strict";
function stopBackSpace(e) {
var ev = e || window.event;
var obj = ev.target || ev.srcElement;
var t = obj.type || obj.getAttribute('type');
var vReadOnly = obj.getAttribute('readonly');
var vEnabled = obj.getAttribute('enabled');
// null
vReadOnly = (vReadOnly == null) ? false : vReadOnly;
vEnabled = (vEnabled == null) ? true : vEnabled;
// when click Backspace,judge the type of obj.
var flag1 = ((t == 'password' || t == 'text' || t == 'textarea') && ((vReadOnly == true || vReadOnly == 'readonly') || vEnabled != true)) ? true : false;
var flag2 = (t != 'password' && t != 'text' && t != 'textarea') ? true : false;
if (flag2) {
e.keyCode = 0;
e.cancelBubble = true;
return false;
}
if (flag1) {
e.keyCode = 0;
e.cancelBubble = true;
return false;
}
}
if (typeof($) == 'function') {
$(function() {
$(document).keydown(function(e) {
if (e.keyCode == 8) {
return stopBackSpace(e);
}
});
});
} else {
document.onkeydown = stopBackSpace;
}
In my case this was a shopping order. So what I did was disable the button. When the user clicked back, the button was disabled still. When they clicked back one more time, and then clicked a page button to go forward. I knew their order was submitted and skipped to another page.
In the case when the page actually refreshed which would make the button (theoretically), available; I was then able to react in the page load that the order is already submitted and redirect then too.