History back hook on JavaScript

依然范特西╮ 提交于 2019-12-10 14:01:08

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/10703606/history-back-hook-on-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!