Skip to content
Advertisement

Detecting Browser History Actions

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

Advertisement

Answer

You’re looking for the popstate event.

An example:

JavaScript

Or with the ever-popular jQuery:

JavaScript

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

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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement