Skip to content

Instantly share code, notes, and snippets.

@Offirmo
Last active October 5, 2017 05:59
Show Gist options
  • Save Offirmo/9efd2c7b95a5e05fceb96e7dd5c66fe0 to your computer and use it in GitHub Desktop.
Save Offirmo/9efd2c7b95a5e05fceb96e7dd5c66fe0 to your computer and use it in GitHub Desktop.
[Intercepting navigation in JavaScript] #JavaScript #browser #growth
function hookNavigationEvent(onNavigate) {
// always provide a full location object to the final callback
function uniformizedOnNavigate(locationOrUrl) {
try {
const location = (typeof locationOrUrl === 'string')
? new URL(
locationOrUrl[0] === '/' // relative
? document.location.origin + locationOrUrl
: locationOrUrl
)
: locationOrUrl
onNavigate(location)
} catch (e) {
golbalCatch(e, 'processingNavigation')
}
}
const originalPushState = history.pushState
history.pushState = function pushState(data, title, url) {
uniformizedOnNavigate(url)
return originalPushState.apply(history, arguments)
}
window.onpopstate = function popStateHandler() {
uniformizedOnNavigate(document.location)
}
// initial call for current page
uniformizedOnNavigate(document.location)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment