Last active
July 4, 2024 20:54
-
-
Save isocroft/918455c07b35ced8664622aee63f3caa to your computer and use it in GitHub Desktop.
A way to monkey-patch the HTML5 JavaScript History API
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
| /* @HINT: If statement for feature detection */ | |
| /* @CHECK: https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Feature_detection */ | |
| if (typeof window.History === 'function') { | |
| /* @HINT: Copy out the native browser `pushState` function for later use */ | |
| const __pushState = window.History.prototype.pushState; | |
| /* @HINT: Also, monkey-patch pushState (which is used by React / Vue / jQuery / Vanilla for their routing) */ | |
| window.History.prototype.pushState = function (...args) { | |
| const [, , url] = args | |
| const origin = window.location.origin | |
| /* @HINT: The URL of the last loaded page */ | |
| const newURL = ((url.indexOf('http') === 0 ? url : origin + url) || '').toString() | |
| /* @HINT: The URL of the currently loaded page */ | |
| const oldURL = document.URL; | |
| /* @HINT: Ensuring that it wasn't a reload but a page transistion to a different page */ | |
| const isProperNav = oldURL !== newURL | |
| if (isProperNav) { | |
| /* @HINT: Dispatch a custom event named `beforeurlchange` (Reads as: before URL change) */ | |
| document.dispatchEvent( | |
| new Event( 'beforeurlchange' ) | |
| ) | |
| } | |
| /* @HINT: Call the native browser `pushState` function so everything works as per usual */ | |
| return __pushState.apply(this, args); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment