Skip to content

Instantly share code, notes, and snippets.

@ryx
Last active August 19, 2023 14:12
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 ryx/19ae2e7b68ea10ce07d9cf4d8e0835f4 to your computer and use it in GitHub Desktop.
Save ryx/19ae2e7b68ea10ce07d9cf4d8e0835f4 to your computer and use it in GitHub Desktop.
Wrap window.history to create custom pushState event dispatched from window
// 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