Code:
<a href="#" onclick="window.onpopstate = function() { alert('pop'); };
return false; ">set up window.onpopstate
</a><br>
<a href="#somehash2">change hash</a>
<div onclick="alert(location.href);">show location.href</div>
Why does clicking the change hash
link fire the popstate, shouldn't it only be fired if I click the change hash
link then click back?
The popstate event of the Window interface is fired when the active history entry changes while the user navigates the session history. It changes the current history entry to that of the last page the user visited or, if history.
related: call e. stopImmediatePropagation() to prevent subsequently-added popstate handlers from firing too. For instance, if a router listens to popstate and replaces content accordingly, you can prevent it from replacing content. The text you insist on re-adding isn't appropriate; stop rolling back.
PopStateEvent is an interface for the popstate event. A popstate event is dispatched to the window every time the active history entry changes between two history entries for the same document. If the history entry being activated was created by a call to history. pushState() or was affected by a call to history.
The reason window.onpopstate
fires are not because of a change to the hash.
It's because the history has been changed when you click on the anchor tag.
From https://developer.mozilla.org/en/DOM/window.onpopstate :
A popstate event is dispatched to the window every time the active history entry changes. If the history entry being activated was created by a call to history.pushState() or was affected by a call to history.replaceState(), the popstate event's state property contains a copy of the history entry's state object.
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