简体   繁体   中英

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".

 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.

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

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

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

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

This is the only solution that works for me with 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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