I tried to build a JS script that would change the location of the page, to go back until a specific hash location is found:
var StopAtThisHash ='#';
var CurrentHash = window.location.hash;
var continueLoop = true;
while ((window.history.length>0) && (continueLoop))
{
window.history.back();
var NowWeAreAtHash = window.location.hash; //this never changes in Chrome
//actually, always seems to: CurrentHash == NowWeAreAtHash;
if(NowWeAreAtHash == StopAtThisHash)
continueLoop= false;
}
Weird enough, in Chrome and FF, the window.location.hash is not changed after back().. neither is the length of history decreased by 1 as I expected. The loop runs indefinitely, and the browser hangs up.
In IE 9 this seems to run as intended.
Any workarounds around this?
function goBackHome () {
goBackToHash(''); // Assume the home is without hash. You can use '#'.
}
function goBackToHash(hash) {
setTimeout(function () {
if (window.location.hash == hash) return;
history.back();
goBackToHash(hash);
}, 0);
}
To overcome the problem of while
loop, I tried use setTimeout
, but this is usually goes further than expected... Waiting for a perfect solution.
I think there is a delay between history.back()
and when window.location.hash
is changed.
Another workaround is to keep the hashes in JS so that you can figure out how many steps is needed in history.go(N)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With