user3915009
user3915009

Reputation: 49

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>

Upvotes: 4

Views: 16244

Answers (3)

BegYourPardon
BegYourPardon

Reputation: 197

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>

Upvotes: 0

Pratik Joshi
Pratik Joshi

Reputation: 11693

use

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

Upvotes: 2

androidavid
androidavid

Reputation: 1259

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

Upvotes: 1

Related Questions