检测浏览器历史操作 [英] Detecting Browser History Actions
问题描述
我正在使用推送状态构建一个 Html 5 网站,我想知道它是否可以在 javascript 或 JQuery 中检测浏览器的后退按钮是否已被推送.我想将它包含在一个 if 语句中,如下所示:
I am building a Html 5 website using push state and I wondering whether its possible in javascript or JQuery to detect whether the browser's back button has been pushed. I would like to include it in an if statement like so:
if (back_btn clicked){
//do stuff
}
if (forward_btn clicked){
}
推荐答案
您正在寻找 popstate 事件.
示例:
window.onpopstate = function(event) {
alert("location: " + document.location);
}
或者使用广受欢迎的 jQuery:
Or with the ever-popular jQuery:
$(window).on('popstate',function(event) {
alert("location: " + document.location);
});
每当访问历史记录时都会触发,例如后退/前进.快速说明,在 Chrome 中,这也会在页面加载时触发,因此快速的方法是检查事件是否为空.
This fires whenever history is accessed, such as back/forward. A quick note, in Chrome this also fires on the page load, so a quick way around is to check if the event is null.
if(event.originalEvent.state!=null){
// do something
}
另一个不错的资源是 History.js jQuery 插件,它具有使用主题标签的后备功能诸如此类.它还使 popstate 事件的检测变得非常简单.
Another good resource is the History.js jQuery plugin, which has a fallback using hashtags and such. It also makes detection of popstate events very straightforward.
这篇关于检测浏览器历史操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!