Last active
February 12, 2021 20:13
-
-
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
This file contains 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
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) | |
} |
This file contains 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
{ | |
"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" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
npm i gist:559feca28be51dc28f397cf43422602c