Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hashchange event not triggered in IE10 & IE11 with combo of history.pushState and url manual manipulation

I'm having trouble getting the hashchange event to trigger consistently in IE10 and IE11

If I use history.pushState to alter the current hash and then manipulate the hash in the url, then hashchange will be triggered once.

Then if the above is repeated the hashchange is not triggered

I've created a jsbin for testing this issue. To replicate the issue in IE10/IE11, simply click on a section link (e.g. section 4) and then manipulate the section id in the url (e.g. section-3). A hashchange should be triggered but if you repeat, the second time it won't.

http://jsbin.com/locor/5

BTW - this works perfectly in Chrome and Firefox

like image 201
user3687422 Avatar asked May 29 '14 12:05

user3687422


People also ask

What is hashchange event?

The hashchange event is fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the # symbol).

What is jQuery Hashchange?

The jQuery Mobile . hashchange() event handler enables very basic bookmarkable #hash history by providing a callback function bound to the window. onhashchange event. The onhashchange event fires when a window's hash changes. In browsers that support it, the native HTML5 window.


1 Answers

Have a repro below. Seems that if you change the hash with pushState IE ignores that change when checking for hashchange events. So if the sequence of your hashes is:

  1. #
  2. #foo (added via pushstate)
  3. # (manually added to address bar)

IE compares #3 against #1 instead #2. Since #1 === #3, IE does not fire a hashchange event.

<script>
function log(message) {
    var div = document.getElementById("log");
    div.innerHTML += message + "<br>";
}
window.addEventListener("hashchange", function () {
    log("hashchange");
});
window.addEventListener("popstate", function(){
    log("popstate");
});
</script>
<p>1. Manually set the hash in the address bar to "#".</p>
<p><a onclick='history.pushState({}, "", "#somePushState");' style="color:blue;">2. Click here to run push state.</a></p>
<p>3. Manually set the hash in the address bar to "#".</p>

<br>
<p>Expected: browser fires hashchange event for #1 and #3. Actual: IE does not fire hashchange event for #3.</p>
<div id="log"><b>Log:</b><br></div>
like image 162
Breck Avatar answered Oct 14 '22 07:10

Breck