I have two two pages:
index.html
<script>
document.addEventListener("click",function(event){
if(event.target.id == "login"){
let username = document.getElementById("username");
let password = document.getElementById("password");
if(username.value != "" && password.value != ""){
formData.append("username",username.value);
formData.append("password",password.value);
fetch('upload.php', {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(data => {
if(data.message == "user exists"){
sessionStorage.setItem("key","loggedin");
window.location.href = "/admin_index.html";
}
else{
alert(data.error);
username.value = "";
password.value = "";
}
})
.catch(error => {
alert('Error: ' + error);
});
}
else{
alert("Please don't leave any field blank");
}
}
})
</script>
admin_index.html
<script>
if(sessionStorage.getItem("key") == "loggedin"){
sessionStorage.removeItem("key");
}
else{
window.location.href = "/index.html";
}
</script>
Upon pressing the login button in index.html
and going to admin_index.html
, I expect the sessionStorage
value to be removed. But when I use the Back button to return to index.html
and then the Forward button to go back to the admin_index.html
, the code in admin_index.html
should return me back to index.html
but doesn’t. How do I fix this?
2
Answers
You’ve said:
…and then clarified in the comments that you were "returning bacK" and "going back" using the Back and Forward buttons in the browser.
When you use Back and Forward to navigate, it doesn’t necessarily re-run the top-level code of your page again. The browser can cache the contents of the window and just re-display them. I was able to replicate the scenario you describe using Chrome (but not, interestingly, using the Chromium-based browser Vivaldi).
You can solve that problem by using the
visibilitychange
event instead, just wrap your top-level code inadmin_index.html
in avisibilitychange
handler.Here’s the
index.html
page I used to replicate the problem:…and the original JavaScript in
admin_index.html
page, which had the same problem yours did on Chrome:Here’s the modified modified
admin_index.html
code:When going Forward to the page, that code runs, and successfully detects that the
sessionStorage
didn’t have the right key and sent me back toindex.html
.You may need to do further tweaking (perhaps look at the document’s
visibilityState
, and perhaps run your check both in top-level code and in the handler), but that should get you going the right way.this will check the key is present if so it will remove the key. in either of the case page will redirect back to index.html.
i the code you wrote if the key is present it will remove and does not redirect.