简体   繁体   English

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

[英]Trigger an event when the browser back button is clicked

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 else block 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>

use

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

Okay.好的。 Besides the fact that you should not initially trigger the event and to .unload = FunctionName and not .unload=FunctionName() and that you need to pass the event -argument I checked the code in the browser.除了您不应该最初触发事件和.unload = FunctionName而不是.unload=FunctionName()并且您需要传递event -argument 我检查了浏览器中的代码这一事实。

currentTarget is 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 已设置)。

This is the only solution that works for me with IOS safari.这是唯一适用于 IOS Safari 的解决方案。

  <script>
     window.addEventListener( "pageshow", function ( event ) {
     var pagehistory = event.persisted || 
                     ( typeof window.performance != "undefined" && 
                          window.performance.navigation.type === 2 );
     if ( pagehistory ) {
    // back button event - Do whatever.   
      }
      });
  </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM