Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window bind POPSTATE

Given the following:

$(window).bind("popstate", function() {
    alert('popstate');
});

On first load, the alert fires with FireFox and Chrome but not Safari. Why is that? Anyone else seen this and know how to best solve for this?

like image 895
AnApprentice Avatar asked Jan 14 '11 05:01

AnApprentice


People also ask

What is Window Popstate?

The popstate event of the Window interface is fired when the active history entry changes while the user navigates the session history. It changes the current history entry to that of the last page the user visited or, if history.

Does history back trigger Popstate?

The popstate event is only triggered by doing a browser action such as a clicking on the back button (or calling history. back() in JavaScript). And the event is only triggered when the user navigates between two history entries for the same document.


3 Answers

See the code from pjax. pjax is fairly popular open source library now, so the below logic might be the best to avoid this issue.

var popped = ('state' in window.history), initialURL = location.href $(window).bind('popstate', function(event) {   // Ignore inital popstate that some browsers fire on page load   var initialPop = !popped && location.href == initialURL   popped = true   if ( initialPop ) return   ... 

https://github.com/defunkt/jquery-pjax/blob/master/jquery.pjax.js

like image 81
Nobu Avatar answered Sep 19 '22 18:09

Nobu


In webkit the popstate event is fired on page load. To avoid this, this easy work around works for me:

Every time I fire history.push(...) I add the class historypushed to the body-tag:

history.push(...); $("body").addClass("historypushed"); 

When I trigger the popstate event, I check for this class:

$(window).bind('popstate', function(e) {  if($("body").hasClass("historypushed")) {    /* my code */   }  }); 
like image 30
lohsie Avatar answered Sep 21 '22 18:09

lohsie


The situation is now reversed. Chrome has fixed the bug and now fires popstate on page load but Firefox 4 (since RC) has departed from the spec and now does not fire popstate!

UPDATE: The HTML5 spec was changed in 2011 to state popstate should not fired on page load. Both Firefox and Chrome now do the right thing as of Firefox 4 and Chrome 34.

like image 22
Tamlyn Avatar answered Sep 22 '22 18:09

Tamlyn