I am building a Html 5 website using push state and I wondering whether its possible in javascript or JQuery to detect whether the browser’s back button has been pushed. I would like to include it in an if statement like so:
JavaScript
x
7
1
if (back_btn clicked){
2
//do stuff
3
}
4
if (forward_btn clicked){
5
6
}
7
Advertisement
Answer
You’re looking for the popstate event.
An example:
JavaScript
1
4
1
window.onpopstate = function(event) {
2
alert("location: " + document.location);
3
}
4
Or with the ever-popular jQuery:
JavaScript
1
4
1
$(window).on('popstate',function(event) {
2
alert("location: " + document.location);
3
});
4
This fires whenever history is accessed, such as back/forward. A quick note, in Chrome this also fires on the page load, so a quick way around is to check if the event is null.
JavaScript
1
4
1
if(event.originalEvent.state!=null){
2
// do something
3
}
4
Another good resource is the History.js jQuery plugin, which has a fallback using hashtags and such. It also makes detection of popstate events very straightforward.