我们能够检测浏览器的刷新和后退按钮事件吗?

11

有人知道如何使用jquery或javascript在Firefox中检测浏览器刷新和后退按钮事件吗?

4个回答

5

返回按钮:

window.addEventListener('popstate', function (event) {
//Your code here
});

刷新:

window.onbeforeunload = function () {
 // Your code here
}

2
popstate事件在前进和后退按钮按下时都会触发。 - Lewis Morris
onbeforeunload 会在页面卸载时触发,包括关闭、导航等。 - LWSChad

2
您可以尝试使用 WindowEventHandlers.onbeforeunload 来实现此功能:
window.onbeforeunload = function(e) {

};

并且

$(window).unload(function() {
      //
});

还要检查浏览器返回按钮检测

I have made a very reusable javascript class, that can be simply dropped into your web page, and when the user clicks back, it will call a function. The default function on this call is a javascript alert “Back Button Clicked”.

To replace this functionality, you simply need to override the OnBack function. This can be done by using the code below.

<script type="text/javascript">
bajb_backdetect.OnBack = function()
{
alert('You clicked it!');
}
</script>

This will now replace the “Back Button Clicked” alert with a “You clicked it!’” alert.


1

1
您可以使用以下事件:
用于后退按钮按下的 window.onpopstate
window.onpopstate = (e) => {
  // your logic goes here
};

window.onbeforeunload 用于刷新或关闭选项卡。

window.onbeforeunload = (e) => {
  // your logic here
  e.preventDefault();
  e.returnValue = 'There are unsaved changes. Sure you want to leave?';
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接