Skip to content

Instantly share code, notes, and snippets.

@mahemoff
Created January 10, 2012 22:09
Show Gist options
  • Select an option

  • Save mahemoff/1591495 to your computer and use it in GitHub Desktop.

Select an option

Save mahemoff/1591495 to your computer and use it in GitHub Desktop.
"Prevent" popstate firing on hash change
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)
@vevo-arthur-klepchukov

Copy link
Copy Markdown

Don't forget document.location.search if you want query params.

@alexandre67fr

Copy link
Copy Markdown
window.onpopstate = (ev) ->
  return if ev.srcElement.location.pathname == ev.target.location.pathname
  # now handle a real back-button or page load event

@clifgriffin

Copy link
Copy Markdown

Conventional 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;
} );

@maoxiaoke

Copy link
Copy Markdown
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