Last active
August 19, 2023 14:12
-
-
Save ryx/19ae2e7b68ea10ce07d9cf4d8e0835f4 to your computer and use it in GitHub Desktop.
Wrap window.history to create custom pushState event dispatched from window
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
// wrap history object (call only once!) | |
(function (history) { | |
const funcs = []; | |
// wrap pushState to send custom event | |
const pushState = history.pushState; | |
history.pushState = function (state, unused, href) { | |
window.dispatchEvent( | |
new CustomEvent('pushState', { detail: { state, href } }) | |
); | |
return pushState.apply(history, arguments); | |
}; | |
})(window.history); | |
// test handler | |
function handlePushState(e) { | |
console.log('pushState event caught: ', e); | |
window.removeEventListener('pushState', handlePushState); | |
} | |
window.addEventListener('pushState', handlePushState); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment