I’m trying to figure out how to use HTML5’s history functions. Here’s my basic code:
$(document).ready(function () {
var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");
console.log(history.state);
$(window).bind('popstate', function(e) {
console.log(e.originalEvent);
});
});
I’m using Jquery 1.5.1. Here’s the console output:
undefined
PopStateEvent
bubbles: false
cancelBubble: false
cancelable: true
clipboardData: undefined
currentTarget: DOMWindow
defaultPrevented: false
eventPhase: 2
returnValue: true
srcElement: DOMWindow
state: null
target: DOMWindow
timeStamp: 1300966328992
type: "popstate"
__proto__: PopStateEvent
I have two questions:
- Why is the history.state undefined? Even in the popstate event nothing exists.
- Why is popstate even called?! I never pressed back or forward. This is on the first load.
Hopefully somebody can shed some light on this for me.
Thanks in advance!
Sean
According to the FF team,
history.stateand not firing popstate on page-load are features of their browser.Here’s a quote from their notes, at http://hacks.mozilla.org/2011/03/history-api-changes-in-firefox-4/
No matter the feature, it is frustrating when vendors split hairs on implementation. Thankfully you can handle the difference easily enough, by simulating the specification and firing your own popstate event on pageload.
Something like this should work in FF4 using jQuery. You would use this code after binding your event handlers.
This approach does favor the specification, but it consolidates state management to your handler function(s), instead of an initialization routine; which is easier to maintain. Honestly, I appreciate
history.state, but it is superfluous as it’s only useful during page load; otherwise it becomes another variable storage mechanism.On a similar note, avoid calling
pushState()initially. States are not a kind of variable and shouldn’t be used as such. I only recommend setting the state while responding to a user action – that is after the page/app loads.