javascript History.pushstate 有回调吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10419898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:49:00  来源:igfitidea点击:

Is there a callback for History.pushstate?

javascripthtmlhtml5-history

提问by thekevinscott

My Google-fu pulls up nothing.

我的 Google-fu 什么也拉不出来。

When you do this:

当你这样做时:

var stateObj = { state: "some state" };
history.pushState(stateObj, "page 2", "other.htm");

Is there an associated window callback?

是否有关联的窗口回调?

I know that there's this:

我知道有这个:

window.onpopstate = function() {

}

Which works great for listening to when a user hits the back button. However, I want to listen to any time the URL changes at all, and I'm not sure how to do it.

当用户点击后退按钮时,这非常适合收听。但是,我想在 URL 发生变化时随时收听,但我不知道该怎么做。

Is there a global callback for anytime the URL changes?

URL 更改时是否有全局回调?

回答by Peter C

No, there's not a onpushstateor whatever. However, a little monkey patching can fix that:

不,没有一个onpushstate或什么的。然而,一个小的猴子补丁可以解决这个问题:

var pushState = history.pushState;
history.pushState = function () {
    pushState.apply(history, arguments);
    fireEvents('pushState', arguments);  // Some event-handling function
};

This will only notify you when pushState is used. You'd probably want to do something similar for replaceState.

这只会在使用 pushState 时通知您。您可能想要为 replaceState 做类似的事情。

If you need to be notified whenever the URL changes at all, some combination of the above and a hashchange handler will get you most of the way there.

如果您需要在 URL 发生任何更改时收到通知,上述内容和 hashchange 处理程序的某种组合将使您大获全胜。