Trigger an event when the browser return button is pressed

I am trying to run some kind of code when I click the "Back back" button.

How can I find out the browser button with changing browser history?

I tried the code below. I got an exception in the block elsesaying: "event 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>
Run codeHide result
+4
source share
2 answers

using

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

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

currentTarget - , -, onclick, / .

, , : window.onunload = HandleBackFunctionality;

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

, currentTarget ( ).

+1

All Articles