Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting Browser Back Button after using history.pushState

I have a three-stage login form that shows/hides content on the page as progress is made. When the user proceeds from step 1 to step 2, I call the following:

var stateObj = { foo: "bar" };
history.pushState(stateObj, "", "");

And I see the browser back button enable.

Now, I'm trying to catch the back button click so I can hide/show content (for example - back to stage 1) accordingly.

How can I detect the browser back button in this scenario? I don't want the URL to change, I just want to call some JS function when the user hits back. I am targeting modern desktop/mobile browsers.

like image 967
SB2055 Avatar asked Jan 31 '15 20:01

SB2055


People also ask

What event is fired when the back button of a browser is pressed?

The popstate event will be triggered by doing a browser action such as a click on the back or forward button (or calling history. back() or history. forward() in JavaScript). Browsers tend to handle the popstate event differently on page load.

What happens when we press back button in browser?

A back button in the browser lets you back-up to the copies of pages you visited previously. The web browser's back and next buttons work well with web sites that provide information that changes infrequently, such as news and shopping web sites.


1 Answers

You can use the onpopstate event.

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

For more info, see the MDN page about the onpopstate event.

like image 146
bigblind Avatar answered Sep 23 '22 06:09

bigblind