您如何确定地检测用户是否在浏览器中按下了后退按钮?
如何使用#URL系统在单页web应用程序中强制使用页面内返回按钮?
为什么浏览器的后退按钮不触发它们自己的事件!?
您如何确定地检测用户是否在浏览器中按下了后退按钮?
如何使用#URL系统在单页web应用程序中强制使用页面内返回按钮?
为什么浏览器的后退按钮不触发它们自己的事件!?
当前回答
在javascript中,导航类型2意味着浏览器的后退或前进按钮被点击,浏览器实际上是从缓存中获取内容。
if(performance.navigation.type == 2)
{
//Do your code here
}
其他回答
if (window.performance && window.performance.navigation.type == window.performance.navigation.TYPE_BACK_FORWARD) {
alert('hello world');
}
这是唯一一个解决方案,为我工作(这不是一个一页网站)。 它支持Chrome、Firefox和Safari浏览器。
我已经为这个需求挣扎了很长一段时间,并采用了上面的一些解决方案来实现它。然而,我偶然发现,它似乎可以在Chrome、Firefox和Safari浏览器以及Android和iPhone上运行
页面加载:
window.history.pushState({page: 1}, "", "");
window.onpopstate = function(event) {
// "event" object seems to contain value only when the back button is clicked
// and if the pop state event fires due to clicks on a button
// or a link it comes up as "undefined"
if(event){
// Code to handle back button or prevent from navigation
}
else{
// Continue user action through link or button
}
}
如果有帮助请告诉我。如果我错过了什么,我会很高兴去理解。
看到这个:
history.pushState(null, null, location.href);
window.onpopstate = function () {
history.go(1);
};
它工作得很好……
你可以尝试popstate事件处理程序,例如:
window.addEventListener('popstate', function(event) {
// The popstate event is fired each time when the current history entry changes.
var r = confirm("You pressed a Back button! Are you sure?!");
if (r == true) {
// Call Back button programmatically as per user confirmation.
history.back();
// Uncomment below line to redirect to the previous page instead.
// window.location = document.referrer // Note: IE11 is not supporting this.
} else {
// Stay on the current page.
history.pushState(null, null, window.location.pathname);
}
history.pushState(null, null, window.location.pathname);
}, false);
注意:为了获得最佳结果,您应该只在希望实现逻辑的特定页面上加载此代码,以避免任何其他意外问题。
每当当前历史记录项更改(用户导航到新状态)时,就会触发popstate事件。当用户单击浏览器的后退/前进按钮时,或者当以编程方式调用history.back()、history.forward()、history.go()方法时,就会发生这种情况。
该事件。状态是事件的属性,等于历史状态对象。
对于jQuery语法,将它环绕起来(在文档准备好后添加监听器):
(function($) {
// Above code here.
})(jQuery);
参见:window。Onpopstate页面加载
参见单页应用程序和HTML5 pushState页面的示例:
<script>
// jQuery
$(window).on('popstate', function (e) {
var state = e.originalEvent.state;
if (state !== null) {
//load content with ajax
}
});
// Vanilla javascript
window.addEventListener('popstate', function (e) {
var state = e.state;
if (state !== null) {
//load content with ajax
}
});
</script>
这应该与Chrome 5+, Firefox 4+, IE 10+, Safari 6+, Opera 11.5+和类似的兼容。
我的版本:
const inFromBack = performance && performance.getEntriesByType( 'navigation' ).map( nav => nav.type ).includes( 'back_forward' )