Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

history.back() does not update location.hash in Chrome/FireFox

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?

like image 262
Radu094 Avatar asked Nov 30 '11 00:11

Radu094


1 Answers

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

like image 107
lzl124631x Avatar answered Nov 15 '22 10:11

lzl124631x