javascript 检测浏览器历史操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14586045/
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 22:01:29  来源:igfitidea点击:

Detecting Browser History Actions

javascriptjquery

提问by Nuvolari

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:

我正在使用推送状态构建一个 Html 5 网站,我想知道是否可以在 javascript 或 JQuery 中检测浏览器的后退按钮是否已被推送。我想将它包含在一个 if 语句中,如下所示:

if (back_btn clicked){
//do stuff
}
if (forward_btn clicked){

}

回答by PlantTheIdea

You're looking for the popstate event.

您正在寻找popstate 事件

An example:

一个例子:

window.onpopstate = function(event) {
    alert("location: " + document.location);
}

Or with the ever-popular jQuery:

或者使用流行的 jQuery:

$(window).on('popstate',function(event) {
    alert("location: " + document.location);
});

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.

每当访问历史记录时都会触发,例如后退/前进。快速说明,在 Chrome 中,这也会在页面加载时触发,因此快速的方法是检查事件是否为空。

if(event.originalEvent.state!=null){
    // do something
}

Another good resource is the History.jsjQuery plugin, which has a fallback using hashtags and such. It also makes detection of popstate events very straightforward.

另一个很好的资源是History.jsjQuery 插件,它有一个使用主题标签等的后备。它还使 popstate 事件的检测变得非常简单。

回答by LeCanardNtheitroad

And for AngularJS

对于 AngularJS

$window.onpopstate = function(e) {
    $window.alert("location: " + $location.path());
}