When redirecting to another page usingsetTimeout()
either by setting window.location.href
or by clicking an anchor object from code, chrome and edge back button don’t redirect back to my page, but to the page before that.
This works well in FireFox and also in chrome when I call history.back() from the console.
I used this test page to reproduce the problem:
<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
</head>
<body>
<a href="https://stackoverflow.com/">Link</a>
<button type="button">Button</button>
<script>
setTimeout(() => document.querySelector('a').click(), 3000);
document.querySelector('button').addEventListener('click',
() => document.querySelector('a').click());
</script>
</body>
</html>
If I click the button the chrome’s back button works fine, but if I let the setTimeout
do the redirect the problem occurs.
It’s better to try it on a newly opened tab.
2
Answers
I think its something with the browser caching mechanism. Have you tried to disable the caching?
From my experience and understanding, this issue may be related to how Chrome and Edge handle page caching and history navigation. When you use
setTimeout
to redirect to a new page, the browser may cache the previous page in memory, which can interfere with the behavior of the back button.To solve this issue, you can try using the
location.replace
method instead ofwindow.location.href
to perform the redirect. Thereplace
method updates the current entry in the browser’s history with the new URL, instead of creating a new entry. This can help ensure that the back button works as expected when navigating back to the previous page.I’ve provided a code snippet to address your issue that uses
location.replace
:In this version, the
setTimeout
and button click event handlers uselocation.replace
instead ofdocument.querySelector(‘a’).click()
orwindow.location.href
to redirect to the new page.Note that using
location.replace
instead ofwindow.location.href
has some implications for your application’s behavior. Specifically, usingreplace
removes the previous entry from the browser’s history, so the user won’t be able to navigate back to the previous page using the back button. If this is not a concern for your application, usingreplace
may be a viable solution to the back button issue you’re experiencing in Chrome and Edge.Try it out, if it doesn’t’ work possible solution to this issue is to use the
history.pushState
method to modify the browser’s history stack when performing the redirect.The
pushState
method adds a new entry to the browser’s history stack, which allows the back button to work as expected when navigating back to the previous page.Here is the MDN doc for
pushState
History: pushState() method