Skip to content

Instantly share code, notes, and snippets.

@pinkhominid
Last active February 12, 2021 20:13
Show Gist options
  • Save pinkhominid/559feca28be51dc28f397cf43422602c to your computer and use it in GitHub Desktop.
Save pinkhominid/559feca28be51dc28f397cf43422602c to your computer and use it in GitHub Desktop.
Custom historychangestate event for web apps that use history.pushState or history.replaceState
export const HISTORY_STATE_CHANGE_EVENT = 'historystatechange';
history.pushState = changeState(history.pushState)
history.replaceState = changeState(history.replaceState)
window.addEventListener('popstate', fireStateChange)
setTimeout(fireStateChange);
function changeState(orig) {
return (...args) => {
const result = orig.apply(history, args)
fireStateChange()
return result
}
}
function fireStateChange() {
// IE needs polyfill, https://github.com/krambuhl/custom-event-polyfill
const event = new CustomEvent(HISTORY_STATE_CHANGE_EVENT, { detail: { url: new URL(location), state: history.state } })
window.dispatchEvent(event)
}
{
"version": "0.5.1",
"name": "history-event",
"description": "Custom historychangestate event for web apps that use history.pushState or history.replaceState",
"main": "history-event.js",
"author": "pinkhominid <pinkhominid@birdbomb.com>",
"license": "MIT",
"homepage": "https://gist.github.com/pinkhominid/559feca28be51dc28f397cf43422602c"
}
@pinkhominid
Copy link
Author

npm i gist:559feca28be51dc28f397cf43422602c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment