Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 685
Joaquín L. Robles Avatar asked Oct 22 '22 22:10

Joaquín L. Robles


2 Answers

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

like image 69
will Avatar answered Nov 15 '22 05:11

will


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.

like image 32
Josiah Ruddell Avatar answered Nov 15 '22 07:11

Josiah Ruddell