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

I tried to create a JS script that would change the page layout to return to a specific hash location:

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; } 

Strange, in Chrome and FF window.location.hash does not change after back (). none of them are reduced by 1, as I expected. The loop runs endlessly and the browser freezes.

In IE 9, this is similar to running.

Any workarounds around this?

+7
source share
2 answers

It seems that window.history.back() , window.history.forward() and window.history.go() does not change the story, it just moves back and forth. If back() changes the length of the story, you cannot forward() .

As a workaround, I would suggest a window.history with for from last to first, not while .

0
source
 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 while problem, I tried using setTimeout , but this usually goes further than expected ... Waiting for the perfect solution.

I think there is a delay between history.back() and when window.location.hash changes.

Another workaround is to store the hashes in JS so you can figure out how many steps are required in history.go(N) .

0
source

All Articles