I want to prevent the javascript of the description from working after pressing the Back button on my browser (on reload).

Asked 2 years ago, Updated 2 years ago, 42 views

<script>
varflg = true;
setTimeout("redirect(), 1000);
function redirect() {
  if(flg){
    flg = false;
    location.href='http://www.yahoo.co.jp/';
  }
}
</script>

I wrote the above javascript in index.html, and when I access index.html, it flies to Yahoo in 1 second, but when I click the "Back" button on my browser while I'm in Yahoo,
Also, I would like to stop processing it because it will fly to Yahoo in 1 second from index.html.
(If you press the "Back" button on your browser, the script above will not work.)
If it's local, it works well, but when I upload the server, the script above works... How should I write the script?

javascript jquery

2022-09-30 10:41

1 Answers

You can leave a hash on the URL that you want to leave in the history, and you can't redirect it to the URL that you have that hash.

window.addEventListener("unload", function(){
    // Leave a URL with #no-redirect in the history when moving
    history.replaceState(undefined, document.title, "#no-redirect");
});

if(window.location.hash=="#no-redirect"){
    // Do not redirect as it is likely to be accessed via history
    // Expose URL without #no-redirect to user
    history.replaceState(undefined, document.title, window.location.pathname);
}
else{
    // Redirect as it does not appear to be accessible via history
    setTimeout (redirect, 1000);
}

function redirect() {
    window.location.assign("http://example.com/");
}


2022-09-30 10:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.