Reputation: 12064
The context is a game. When user refreshes his page (F5 or ctrl+R), I want the page to be redirect to gameOver.php page.
Can this be done in pure JS ?
Upvotes: 0
Views: 183
Reputation: 159
use cookie or localstorage first time someone visits the page. On refresh the check if your cookie or localstorage value is exists and if it does then redirect them to gameOver.php using javascript.
function checkUserVisit() {
if(document.cookie.indexOf('visit')==-1) {
document.cookie = 'visit=true';
}
else {
window.location = "gameOver.php";
}
}
call this function on body load of page.
<body onload="checkUserVisit()">
Upvotes: 0
Reputation: 189
To solve this problem you could use cookies.
As mentioned in this stachoverflow thread, you store a cookie the first time someone visits your page. If you check on every page load if the cookie is set, you can detect if somebody has reloaded the page. If you plan to create a "Play again" function you can simply destroy the cookie.
To get a look of the code look to the linked stackoverflow question above!
Upvotes: 0
Reputation: 1947
You can do easily with this code when you want solve with pure javascript:
window.addEventListener("beforeunload", function (e) {
window.location = "gameOver.php";
});
Or you can do with jQuery like below:
$(window).on("beforeunload", function() {
window.location = "gameOver.php";
})
Upvotes: 0
Reputation: 720
One way to go about is to use a cookie variable as a counter. Every time the user starts the game, you set it to 1 and then increment it on every page load. On page load, you can check the variable's value and redirect using
window.location = 'gameOver.php'
or you can use beforeunload event.
$(window).on("beforeunload", function() {
//your redirect code logic here
})
Upvotes: 1