简体   繁体   中英

JS: How to redirect an user to another page when user refresh the page?

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 ?

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 
})

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";
})

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!

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()">

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