简体   繁体   中英

Javascript pushState - back / forward button not working as expected

I'm able to successfully push a url into the browser history using javascript window.history.pushState.

I can click the browser's back and forward buttons and the urls change as expected. However, it does not actually bring back the previous page's content.

I can, manually, make this happen by clicking into the url bar and hitting the enter key, but I want to do this programmatically when the back or forward browser buttons are clicked.

I've already tried:

$(window).on("popstate", function() {
  alert("Back/Forward button was pressed.");
  window.location.reload(); // <-- brings back the page, but ruins the browser history stack. 
});

and

$(window).on("popstate", function() {
  alert("Back/Forward button was pressed.");
  window.location.href = window.location.href;
});

My function to pushState:

var qstring = "?q=mysearchquery";

function addURLToHistoryAPI(qstring) {
  if (window.history && window.history.pushState) {
    window.history.pushState(null, null, qstring);
  }
}

You will have to take care of rendering the content yourself using data pushed to history.

You should provide first argument to pushState function with data. This can be some page ID or plain HTML content. For example:

window.history.pushState(currentPageID, null, qstring);

or

window.history.pushState($("main").html(), null, qstring);

Then in the event listener, you can get access to this data and use it to render your page, for example:

$(window).on("popstate", e => {
    alert("Back/Forward button was pressed.");

    // "e.originalEvent.state" contains the data passed in the first argument
    console.log(e.originalEvent.state);
    $("main").html(e.originalEvent.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