I have an issue with binding to window.hashchange. When calling history.replaceState
, it triggers the 'hashchange' event unless a call has been made to location.hash
. I am using Chrome 42, and jQuery to assist the binding. I have Sammy.js loaded (and I am actually trying to work out how Sammy would interpret the behaviour)
I am debugging in the console, and doing the following:
$(window).bind('hashchange', function(e) { alert('# change' + location.hash); });
history.replaceState({}, "", "#2")
--> shows the alert
location.hash = "3"
--> shows the alert
history.replaceState({}, "", "#4")
--> does not show alert
Is this a bug, or expected behaviour? I would have thought that replaceState either always, or never triggered the 'hashchange' event
I have an issue with binding to window.hashchange. When calling history.replaceState
, it triggers the 'hashchange' event unless a call has been made to location.hash
. I am using Chrome 42, and jQuery to assist the binding. I have Sammy.js loaded (and I am actually trying to work out how Sammy would interpret the behaviour)
I am debugging in the console, and doing the following:
$(window).bind('hashchange', function(e) { alert('# change' + location.hash); });
history.replaceState({}, "", "#2")
--> shows the alert
location.hash = "3"
--> shows the alert
history.replaceState({}, "", "#4")
--> does not show alert
Is this a bug, or expected behaviour? I would have thought that replaceState either always, or never triggered the 'hashchange' event
Share Improve this question asked Jun 17, 2016 at 2:05 AndrewPAndrewP 1,61814 silver badges25 bronze badges 2 |3 Answers
Reset to default 9It is simple, you must fire hashchange
native event in window after history.replaceState e.g. :
history.replaceState(null, null, '#yourHash');
window.dispatchEvent(new HashChangeEvent('hashchange'));
In my Chromium browser only the location.hash = "3"
line triggers a hashchange
event and it's not a "bug".
From MDN documentation:
Note that
pushState()
never causes ahashchange
event to be fired, even if the new URL differs from the old URL only in its hash.
And:
history.replaceState()
operates exactly likehistory.pushState()
except thatreplaceState()
modifies the current history entry instead of creating a new one.
Include the data with event.
const hash = "#/foo/bar"
history.pushState(null, '', hash);
window.dispatchEvent(new HashChangeEvent('hashchange', {
newURL: window.location.origin + window.location.pathname + hash,
oldURL: window.location.href,
}));
hashchange
event on my end forreplaceState
in any case, and I don't think it's supposed to. – Alexander O'Mara Commented Jun 17, 2016 at 2:11