How to detect when history.pushState and history.r

2019-01-14 10:57发布

问题:

This question already has an answer here:

  • How to get notified about changes of the history via history.pushState? 8 answers

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

回答1:

The onpopstate event should be fired when the history changes, you can bind to it in your code like this:

window.onpopstate = function (event) {
  // do stuff here
}

This event may also be fired when the page loads, you can determine whether the event was fired from a page load, or by using pushState/replaceState by checking the event object for a state property, it will be undefined if the event was caused by a page load

window.onpopstate = function (event) {
  if (event.state) {
    // history changed because of pushState/replaceState
  } else {
    // history changed because of a page load
  }
}

There currently is no onpushstate event unfortunately, to get around this you need to wrap both the pushState and replaceState methods to implement your own onpushstate event.

I have a library that makes working with pushState a bit easier, it might be worth checking it out called Davis.js, it provides a simple api for working with routing based on pushState.



回答2:

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.