Created
January 10, 2012 22:09
-
-
Save mahemoff/1591495 to your computer and use it in GitHub Desktop.
"Prevent" popstate firing on hash change
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| currentPathname = null | |
| window.onpopstate = (ev) -> | |
| return if document.location.pathname == currentPathname | |
| currentPathname = document.location.pathname | |
| #... (now handle a real back-button or page load event) |
window.onpopstate = (ev) ->
return if ev.srcElement.location.pathname == ev.target.location.pathname
# now handle a real back-button or page load eventConventional JavaScript example.
In our case, a third party script was setting window.location.href to itself, which didn't have the intended effect (refreshing the page) due to a hash being present.
So, this script detects if the hash is being changed to itself and fires a refresh.
But there are a lot of other cool things you can do with this pattern so sharing here:
let currentHash = window.location.hash;
window.addEventListener('popstate', function( event ) {
if ( window.location.hash == currentHash ) {
window.location.reload();
}
currentHash = window.location.hash;
} );window.onpopstate = (ev) -> return if ev.srcElement.location.pathname == ev.target.location.pathname # now handle a real back-button or page load event
srcElement and target are the same https://developer.mozilla.org/en-US/docs/Web/API/Event/srcElement
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Don't forget
document.location.searchif you want query params.