javascript 单击浏览器后退按钮时触发事件

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

Trigger an event when the browser back button is clicked

javascriptphpjqueryhtml

提问by user3915009

I am trying to run some code when the browser back button is clicked.

我试图在单击浏览器后退按钮时运行一些代码。

How can i found out browser's back button with out changing the browser history?

如何在不更改浏览器历史记录的情况下找到浏览器的后退按钮?

I tried the code below. I got an exception in the elseblock saying: "event is not defined".

我尝试了下面的代码。我在else块中遇到一个异常:“事件未定义”。

window.onunload = HandleBackFunctionality();
  function HandleBackFunctionality()
  {
    if(window.event)
    {
      if(window.event.clientX < 40 && window.event.clientY < 0)
      {
        alert("Browser back button is clicked…");
      } else {
        alert("Browser refresh button is clicked…");
      }
    } else {
      if(event.currentTarget.performance.navigation.type == 1)
      {
        alert("Browser refresh button is clicked…");
      }
      if(event.currentTarget.performance.navigation.type == 2)
      {
        alert("Browser back button is clicked…");
      }
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

回答by Pratik

use

利用

$(window).on("navigate", function (event, data) {
  var direction = data.state.direction;
  if (direction == 'back') {
    // do something
  }
  if (direction == 'forward') {
    // do something else
  }
});

回答by androidavid

Okay. Besides the fact that you should not initially trigger the event and to .unload = FunctionNameand not .unload=FunctionName()and that you need to pass the event-argument I checked the code in the browser.

好的。除了您最初不应该触发事件和 to.unload = FunctionName和 not.unload=FunctionName()以及您需要传递event-argument 我检查了浏览器中的代码这一事实。

currentTargetis empty - this totally makes sense as there is no event-target like onclick but it is just the site reloading/unloading.

currentTarget为空 - 这完全有道理,因为没有像 onclick 这样的事件目标,但它只是站点重新加载/卸载。

Please debug the code by yourself by using this and fit it to your needs: window.onunload = HandleBackFunctionality;

请使用它自己调试代码并使其适合您的需要:window.onunload = HandleBackFunctionality;

function HandleBackFunctionality(event)
{
  console.log(event, window.event);
}

You will see that currentTarget is not set (while event is).

您将看到 currentTarget 未设置(而 event 已设置)。