Joaquín L. Robles
Joaquín L. Robles

Reputation: 6494

History back hook on JavaScript

Is there a way to provide a hook such as onHistoryBack? I'm currently using history.js with

History.Adapter.bind (window, 'statechange', function () {});

But I have no way to ask if user presed history.back() or if it's result of a History.pushState() call.. any idea?

Upvotes: 5

Views: 3784

Answers (2)

Josiah Ruddell
Josiah Ruddell

Reputation: 29831

All of the states are stored in History.savedStates. Each time back is pushed another state is added. So in theory you could test History.savedStates to see if History.savedStates[History.savedStates.length - 2] == currentState. That would indicate the user went from step a, to step b, back to step a. However the user could get there other ways than the back button - so you may need to use this in combination with user events.

You can also use the History.getStateByIndex method to return a saved state.

Upvotes: 1

will
will

Reputation: 4575

The way I did this was to set a variable set to true on each click on the actual site. The statechange event would then check this variable. If it was true, they had used a link on the site. If it was false, they had clicked the browsers back button.

For example:

var clicked = false;

$(document).on('click','a',function(){

    clicked = true;

    // Do something

});

History.Adapter.bind (window, 'statechange', function () {

    if( clicked ){
        // Normal link
    }else{
        // Back button
    }

    clicked = false;

});

Hope that helps :)

Upvotes: 2

Related Questions