Javascript 如何检测 history.pushState 和 history.replaceState 何时被使用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5129386/
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
How to detect when history.pushState and history.replaceState are used?
提问by BrunoLM
Is there some event I can subscribe to when the history state is modified? How?
当历史状态被修改时,我可以订阅一些事件吗?如何?
采纳答案by Oliver Nightingale
The onpopstate event should be fired when the history changes, you can bind to it in your code like this:
onpopstate 事件应该在历史记录更改时触发,您可以像这样在代码中绑定到它:
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
此事件也可能在页面加载时触发,您可以确定该事件是否是从页面加载中触发的,或者通过检查事件对象的 state 属性使用 pushState/replaceState 触发,如果事件是由页面加载
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.
不幸的是,目前没有 onpushstate 事件,要解决这个问题,您需要包装 pushState 和 replaceState 方法来实现您自己的 onpushstate 事件。
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.
我有一个库可以让使用 pushState 更容易一些,它可能值得一试,称为Davis.js,它提供了一个简单的 api 来处理基于 pushState 的路由。
回答by Rudie
I used to use this to also be notified of when pushState
and replaceState
are called:
我曾经使用它来通知何时pushState
和replaceState
被调用:
// 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.
注意。它也不适用于 Google Chrome 扩展内容脚本,因为它不允许更改站点的 JS 环境。您可以通过插入<script>
带有上述代码的a 来解决这个问题,但这更加矫枉过正。