Skip to content

Instantly share code, notes, and snippets.

@xudaolong
Created May 9, 2019 09:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xudaolong/1024ca96d0b5619357c3d1db32ccb4ed to your computer and use it in GitHub Desktop.
Save xudaolong/1024ca96d0b5619357c3d1db32ccb4ed to your computer and use it in GitHub Desktop.
spa applicaiton listen url change|-|&tag=JS
import _ from 'lodash'
// eslint-disable-next-line no-undef
class URLChangeEvent extends HashChangeEvent {
get [Symbol.toStringTag] () {
return 'URLChangeEvent'
}
}
let urlCache = window.location.href
const onURLChange = () => {
if (window.location.href !== urlCache) {
const event = new URLChangeEvent('urlchange', {
oldURL: urlCache,
newURL: window.location.href
})
window.dispatchEvent(event)
typeof window.onurlchange === 'function' && window.onurlchange(event)
urlCache = window.location.href
}
}
const registryOnChangeURL = _.once(() => {
const pushStateNative = window.history.pushState
window.history.pushState = (...args) => {
pushStateNative.apply(window.history, args)
onURLChange()
}
window.addEventListener('hashchange', onURLChange)
})
export { registryOnChangeURL }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment