Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

if (back_btn clicked){
//do stuff
}
if (forward_btn clicked){

}
like image 665
Nuvolari Avatar asked Jan 29 '13 15:01

Nuvolari


People also ask

How does Window history work?

The Window. history read-only property returns a reference to the History object, which provides an interface for manipulating the browser session history (pages visited in the tab or frame that the current page is loaded in). See Manipulating the browser history for examples and details.

Can JavaScript access browser history?

Introduction to the JavaScript history object. The history stack stores the current page and previous pages that you visited. For the security reason, it's not possible to query the pages that a user have visited. However, you can use the history object to navigate back and forth without knowing the exact URL.


1 Answers

You're looking for the popstate event.

An example:

window.onpopstate = function(event) {
    alert("location: " + document.location);
}

Or with the ever-popular jQuery:

$(window).on('popstate',function(event) {
    alert("location: " + document.location);
});

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.

if(event.originalEvent.state!=null){
    // do something
}

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.

like image 192
PlantTheIdea Avatar answered Oct 18 '22 08:10

PlantTheIdea