开发者

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

This question already has answers here: 开发者_如何学JAVA How to get notified about changes of the history via history.pushState? (16 answers) Closed 7 years ago.

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜