5

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?

Martin AJ
  • 6,261
  • 8
  • 53
  • 111
  • Lemme know if the above dupe doesn't answer your question. – Praveen Kumar Purushothaman Jun 19 '18 at 20:22
  • @PraveenKumar Actually I read both the question you linked as duplicate and [this](https://stackoverflow.com/questions/8980255/how-do-i-retrieve-if-the-popstate-event-comes-from-back-or-forward-actions-with) before asking, but neither help. Still I don't know how can I detect either back or forward button clicked. – Martin AJ Jun 19 '18 at 20:25
  • I have reopened the question. I would believe that would be a worst idea. Think about it. `:)` You should be able to do it in a different way, whatever you do. – Praveen Kumar Purushothaman Jun 19 '18 at 20:27
  • Have checked this: https://stackoverflow.com/questions/25806608/how-to-detect-browser-back-button-event-cross-browser? He has a rather simple solution – cela Jun 19 '18 at 20:50

2 Answers2

-1

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

Oleg
  • 1,044
  • 1
  • 14
  • 10
-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)
  // );