Created
May 9, 2019 09:57
-
-
Save xudaolong/1024ca96d0b5619357c3d1db32ccb4ed to your computer and use it in GitHub Desktop.
spa applicaiton listen url change|-|&tag=JS
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
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