Is it possible to alter the hash of a page without calling the hashchange event?
As in my app I want to do something like:
$(window).hashchange( function(){
hash = ...; // here I change the hash to something else
window.location.hash = hash; // then update it
});
The obvious problem with the code above is that it will cause a loop as window.location.hash will call the hashchange event and then so and so on.
However in my app I only change the hash on a condition:
$(window).hashchange( function(){
var hash = window.location.hash;
var lastChar = hash.substr(-1);
if(lastChar != '/') {
// Add trailing slash
hash = hash.replace(/\/?$/, '/');
// Update the hash
window.location.hash = hash;
}
});
So that it only gets called IF a trailing slash isn't found, and then once it's added it then it won't enter the conditional again so it won't do the loop issue mentioned above.
BUT it will still call the hashchange event! And two problems arise from this:
The History is broken as the previous page is the current page and the browser gets stuck in an infinite stack of the current page.
I do an AJAX request in my app on hashchange so it will do the call twice just to add the trailing slash.
Is it possible to add that slash to the hash without it calling the event?
Perhaps doing window.unbind('hashchange'). Would that work? And also needs to work in HTML4 browsers so the HTML5 History API isn't an option here.
In HTML5 browsers you can use window.history.replaceState() to update the hash without causing a new history entry to be created.
According to the MDN docs, neither .pushState() or .replaceState() will trigger a hashchange event.
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