Martin AJ
Martin AJ

Reputation: 6707

How can I detect either back or forward button of the browser is pressed?

I have two customized functions that handle back and forward page. I need to call them when user clicks on the browser back/forward buttons too.

window.onpopstate  = function() {

    if ( /* back button clicked */ ){

        showPreviousPage():

    } else {

        showNextPage();

    }

})

How can I implement that condition? In other word, how can I detect browser back button is clicked?

Upvotes: 5

Views: 5977

Answers (2)

mohammad fanudi
mohammad fanudi

Reputation: 1

    //react js detect browser pop  forward or back



   window.addEventListener("popstate", (e) => {
      var loc = document.location;
      if (event && event.state && event.state.usr && event.state.usr.pop)      {
      var stateloc = event.state.usr.pop;
      } else {
      var stateloc = "forward";
    }

  if (event && event.state && event.state.usr && event.state.usr.pop) {
      var stateloc = event.state.usr.pop;
    } else {
      var stateloc = "forward";
    }
    //   window.history.pushState(null, null, null);
      if (stateloc == "forward") {
     
        history.forward();
     
        } else if (stateloc == "back") {
   
        history.back();
        
        
        
        
        
        
         console.log(
  //   "location: " +
  //     document.location +
  //     ", state: " +
  //     JSON.stringify(event.state)
  // );
        

Upvotes: -1

Oleg
Oleg

Reputation: 1140

You can use popstate event.

From here

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

Upvotes: -2

Related Questions