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?
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.
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.
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
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 */ } });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With