I am running a simple:
window.location.hash = "hash";
to add a hash in the url right after page load. I get, mySite.com/aPage#hash. When I click the back button, I expect the url change back to mySite.com/aPage without any actual loading/going back. Instead I am being taken back to the history entry before mySite.com/aPage.
It works well, when I call window.location.hash e.g. in a click event callback triggered by a user.
I created a test: http://jsbin.com/idukiz/1/ See code: http://jsbin.com/idukiz/1/edit
Only the last hash added inside the setTimeout function behaves like I expect. Any ideas how to make it work without setTimeout?
Any ideas how to make it work without setTimeout?
A dynamicly created <a>
with href of #yourHash
to which you dispatchEvent
a mouse click.
window.onload = function () {
location.hash = 'foo'; // no history item created, just to help visibility
var a = document.createElement('a'),
ev = document.createEvent("MouseEvents");
a.href = '#bar'; // this will create history item
ev.initMouseEvent("click", true, false, self, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(ev); // dispatch click
};
Demo of code here. Tested in Google Chrome 25.
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