Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.location.hash not creating browser history entry

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?

like image 816
Hans Avatar asked Nov 12 '22 08:11

Hans


1 Answers

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.

like image 110
Paul S. Avatar answered Nov 15 '22 07:11

Paul S.