How to detect when history.pushState and history.replaceState are used?

BrunoLM picture BrunoLM · Feb 26, 2011 · Viewed 58.7k times · Source

Is there some event I can subscribe to when the history state is modified? How?

Answer

Rudie picture Rudie · Sep 4, 2014

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.