Browser back button detection after using history.pushState

I have a three-step login form that shows / hides the content on the page as it moves. When the user goes from step 1 to step 2, I call the following:

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

And I see a browser enable button.

Now I am trying to catch the back button so that I can hide / show the content (for example, back to step 1) respectively.

How can I identify the browser 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 focus on modern desktop / mobile browsers.

+5
source share
2 answers

You can use the onpopstate event.

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

For more information, see the MDN page onpopstate event.

+9
source

To detect the back button, you bind to the popstate event:

 $(window).bind("popstate", function(e) { var state = e.originalEvent.state; if ( state === null ) { console.log("step one"); } else { console.log(state.foo); } }); 
+1
source

Source: https://habr.com/ru/post/1212345/


All Articles