How to Retrieve If the Popstate Event Comes from Back or Forward Actions with the HTML5 Pushstate

How do I retrieve if the popstate event comes from back or forward actions with the HTML5 pushstate?

You must implement it yourself which is quite easy.

  • When invoking pushState give the data object a unique incrementing id (uid).
  • When onpopstate handler is invoked; check the state uid against a persistent variable containing the last state uid.
  • Update the persistent variable with the current state uid.
  • Do different actions depending on if state uid was greater or less than last state uid.

History pushstate back & forward functionality

I just realized I had window.history.pushState('', '', url); inside get_page_content() which then was called each time onpopstate event fired and eventually there was nothing to go forward to. I simply moved pushState outside of get_page_content() and everything works. Here's what I currently have:

$('body').on('click', 'a:not([href^="#"])', function(e) {

if ( this.host === window.location.host ) {

e.preventDefault()

get_page_content($(this).attr('href'));
window.history.pushState('', '', url);

}

});

$(window).on('popstate', function(e) {

get_page_content(location.href);

});

function get_page_content(url) {
// ...
}

JS: Erroneous popstate event when trying to navigate back past the initial page load

The initial page load shouldn't use history.pushState because it would add another history entry. There is alredy an implicit first history item with state null.

Using history.replaceState for the initial page load, sets a state for that item but doesn't add another one.

var initialPageLoad = true;
function action(text) {
if (initialPageLoad) {
// replace the state of the first (implicit) item
history.replaceState({"text":text}, text);
} else {
// add new history item
history.pushState({"text":text}, text);
}
initialPageLoad = false;
doAction(text);
}

function doAction(text) {
$('span').text(text);
}

var $button = $('button');
var $p = $('p');

$p.hide();

action("foo");
$button.on('click', function(){
action("bar");
$button.hide();
$p.show();
})

window.addEventListener("popstate", function(e) {
if (e.state !== null) {
$button.show();
$p.text("Next back should navigate away from this page");
// } else {
// won't happen anymore, as the first item has state now
// $p.text("Still here? Why is that? Next back will really navigate away");
}
});


Related Topics



Leave a reply



Submit