简体   繁体   中英

How to find out if the history back/forward was triggered

I'm using ajax to simulate a menu. All is fine but the back and forward buttons are not perfectly working.

So the code is:

$('#sdt_menu a').on('click', function (e) {
    href = $(this).attr("href");
    e.preventDefault();
    window.onpopstate = function (event) {
        document.url = event.state.url;
        loadSpecificPage(window.location.pathname);
    };
    pushingState(href);
})

window.onpopstate looks for changes in the history. pushingState just pushes the new page to the history.

With this the menu items are correctly loaded into the browser history. But when I hit the back button for instance, the window.onpopstate as well as my pushingState function is triggered. So let's say I'm on page 1 and now load page 2. When I hit the back button now in the browser, I correctly go back to page 1 but I reload page 1 and go to it. So at the end I was not going back correctly. So the pushingState function shall not be triggered, then it should work properly. I at least just replaced the current page with the last in the current way.

Summary : the window.onpopstate is working properly. But the pushingState function shall not be triggered when hitting the browser back/forward button.

So my idea was to create an if statement that checks if one of the buttons was clicked. But I did not find something like that. Here some links that did not work for me: detect back button click in browser and JavaScript or jQuery browser back button click detector

Maybe I'm thinking too hard into this direction and it's even easier somehow?

Added pushingState function

function pushingState(href){
    if (href == "/about" || href == "/about/") {
        history.pushState('About', 'about', href);
    }
    if (href == "/creator" || href == "/creator/") {
        history.pushState('Creator', 'creator', href);
    }
}

I'm right now using this block of code. It's a little bit different from the original idea, and still not the perfect solution, but at least better and the back and forward buttons are working:

$('#sdt_menu a').on('click', function (e) {
    var href = $(this).attr("href");
    history.pushState(href, '', href);
    e.preventDefault();
    window.onpopstate = function (event) {
        if (event.state != null){
            document.url = event.state.url;
            pushingState(event.state);
        }
    };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM