Is there some event I can subscribe to when the history state is modified? How?
To detect the changes in the browser's history whenever history. pushState() method is called, we would have to monkey-patch (change the behavior of existing function similar to overriding) an object called window. history.
The big difference is, that while pushState will create a new entry in the browser's history, replaceState will only replace the current state. As a side effect of this, using the replaceState method will change the URL in the address bar, without creating a new history entry.
HTML5 History API allows browsers to change the URL in browser address bar without reloading or refreshing the page using pushState function. The pushState method works similar to window.
The popstate event will be triggered by doing a browser action such as a click on the back or forward button (or calling history. back() or history. forward() in JavaScript). Browsers tend to handle the popstate event differently on page load.
I used to use this to also be notified of when pushState
and replaceState
are called:
// Add this: var _wr = function(type) { var orig = history[type]; return function() { var rv = orig.apply(this, arguments); var e = new Event(type); e.arguments = arguments; window.dispatchEvent(e); return rv; }; }; history.pushState = _wr('pushState'), history.replaceState = _wr('replaceState'); // Use it like this: window.addEventListener('replaceState', function(e) { console.warn('THEY DID IT AGAIN!'); });
It's usually overkill though. And it might not work in all browsers. (I only care about my version of my browser.)
NB. It also doesn't work in Google Chrome extension content scripts, because it's not allowed to alter the site's JS environment. You can work around that by inserting a <script>
with said code, but that's even more overkill.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With