How to Detect Browser Back Button event - Cross Browser

后端 未结 16 2777
鱼传尺愫
鱼传尺愫 2020-11-21 23:09

How do you definitively detect whether or not the user has pressed the back button in the browser?

How do you enforce the use of an in-page back button inside a sin

16条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-21 23:58

    I had been struggling with this requirement for quite a while and took some of the solutions above to implement it. However, I stumbled upon an observation and it seems to work across Chrome, Firefox and Safari browsers + Android and iPhone

    On page load:

    window.history.pushState({page: 1}, "", "");
    
    window.onpopstate = function(event) {
    
      // "event" object seems to contain value only when the back button is clicked
      // and if the pop state event fires due to clicks on a button
      // or a link it comes up as "undefined" 
    
      if(event){
        // Code to handle back button or prevent from navigation
      }
      else{
        // Continue user action through link or button
      }
    }
    

    Let me know if this helps. If am missing something, I will be happy to understand.

提交回复
热议问题