您如何确定地检测用户是否在浏览器中按下了后退按钮?

如何使用#URL系统在单页web应用程序中强制使用页面内返回按钮?

为什么浏览器的后退按钮不触发它们自己的事件!?


当前回答

只有重新定义API(更改对象' history '的方法),才能实现成熟的组件。 我将分享刚才写的课程。 在Chrome和Mozilla上测试 仅支持HTML5和ECMAScript5-6

class HistoryNavigation {
    static init()
    {
        if(HistoryNavigation.is_init===true){
            return;
        }
        HistoryNavigation.is_init=true;

        let history_stack=[];
        let n=0;
        let  current_state={timestamp:Date.now()+n};
        n++;
        let init_HNState;
        if(history.state!==null){
            current_state=history.state.HNState;
            history_stack=history.state.HNState.history_stack;
            init_HNState=history.state.HNState;
        } else {
            init_HNState={timestamp:current_state.timestamp,history_stack};
        }
        let listenerPushState=function(params){
            params=Object.assign({state:null},params);
            params.state=params.state!==null?Object.assign({},params.state):{};
            let h_state={ timestamp:Date.now()+n};
            n++;
            let key = history_stack.indexOf(current_state.timestamp);
            key=key+1;
            history_stack.splice(key);
            history_stack.push(h_state.timestamp);
            h_state.history_stack=history_stack;
            params.state.HNState=h_state;
            current_state=h_state;
            return params;
        };
        let listenerReplaceState=function(params){
            params=Object.assign({state:null},params);
            params.state=params.state!==null?Object.assign({},params.state):null;
            let h_state=Object.assign({},current_state);
            h_state.history_stack=history_stack;
            params.state.HNState=h_state;
            return params;
        };
        let desc=Object.getOwnPropertyDescriptors(History.prototype);
        delete desc.constructor;
        Object.defineProperties(History.prototype,{

            replaceState:Object.assign({},desc.replaceState,{
                value:function(state,title,url){
                    let params={state,title,url};
                    HistoryNavigation.dispatchEvent('history.state.replace',params);
                    params=Object.assign({state,title,url},params);
                    params=listenerReplaceState(params);
                    desc.replaceState.value.call(this,params.state,params.title,params.url);
                }
            }),
            pushState:Object.assign({},desc.pushState,{
                value:function(state,title,url){
                    let params={state,title,url};
                    HistoryNavigation.dispatchEvent('history.state.push',params);
                    params=Object.assign({state,title,url},params);
                    params=listenerPushState(params);
                    return desc.pushState.value.call(this, params.state, params.title, params.url);
                }
            })
        });
        HistoryNavigation.addEventListener('popstate',function(event){
            let HNState;
            if(event.state==null){
                HNState=init_HNState;
            } else {
                HNState=event.state.HNState;
            }
            let key_prev=history_stack.indexOf(current_state.timestamp);
            let key_state=history_stack.indexOf(HNState.timestamp);
            let delta=key_state-key_prev;
            let params={delta,event,state:Object.assign({},event.state)};
            delete params.state.HNState;
            HNState.history_stack=history_stack;
            if(event.state!==null){
                event.state.HNState=HNState;
            }
            current_state=HNState;
            HistoryNavigation.dispatchEvent('history.go',params);
        });

    }
    static addEventListener(...arg)
    {
        window.addEventListener(...arg);
    }
    static removeEventListener(...arg)
    {
        window.removeEventListener(...arg);
    }
    static dispatchEvent(event,params)
    {
        if(!(event instanceof Event)){
            event=new Event(event,{cancelable:true});
        }
        event.params=params;
        window.dispatchEvent(event);
    };
}
HistoryNavigation.init();

// exemple

HistoryNavigation.addEventListener('popstate',function(event){
    console.log('Will not start because they blocked the work');
});
HistoryNavigation.addEventListener('history.go',function(event){
    event.params.event.stopImmediatePropagation();// blocked popstate listeners
    console.log(event.params);
    // back or forward - see event.params.delta

});
HistoryNavigation.addEventListener('history.state.push',function(event){
    console.log(event);
});
HistoryNavigation.addEventListener('history.state.replace',function(event){
    console.log(event);
});
history.pushState({h:'hello'},'','');
history.pushState({h:'hello2'},'','');
history.pushState({h:'hello3'},'','');
history.back();

    ```

其他回答

该文档。鼠标悬停不适用于IE和FireFox。 但是我试过了:

$(document).ready(function () {
  setInterval(function () {
    var $sample = $("body");
    if ($sample.is(":hover")) {
      window.innerDocClick = true;
    } else {
      window.innerDocClick = false;
    }
  });

});

window.onhashchange = function () {
  if (window.innerDocClick) {
    //Your own in-page mechanism triggered the hash change
  } else {
    //Browser back or forward button was pressed
  }
};

这适用于Chrome和IE,而不是FireFox。仍在努力完善FireFox。任何检测浏览器后退/前进按钮点击的简单方法都是受欢迎的,尤其是在JQuery中,也包括AngularJS或纯Javascript。

我尝试了上面的方法,但是没有一个对我有效。这是解决方案

if(window.event)
   {
        if(window.event.clientX < 40 && window.event.clientY < 0)
        {
            alert("Browser back button is clicked...");
        }
        else
        {
            alert("Browser refresh button is clicked...");
        }
    }

详情请参考http://www.codeproject.com/Articles/696526/Solution-to-Browser-Back-Button-Click-Event-Handli

以下是我的看法。假设是,当URL更改但检测到文档内没有单击时,它是浏览器返回(是的,或向前)。用户点击2秒后重置,使其在通过Ajax加载内容的页面上工作:

(function(window, $) {
  var anyClick, consoleLog, debug, delay;
  delay = function(sec, func) {
    return setTimeout(func, sec * 1000);
  };
  debug = true;
  anyClick = false;
  consoleLog = function(type, message) {
    if (debug) {
      return console[type](message);
    }
  };
  $(window.document).click(function() {
    anyClick = true;
    consoleLog("info", "clicked");
    return delay(2, function() {
      consoleLog("info", "reset click state");
      return anyClick = false;
    });
  });
  return window.addEventListener("popstate", function(e) {
    if (anyClick !== true) {
      consoleLog("info", "Back clicked");
      return window.dataLayer.push({
        event: 'analyticsEvent',
        eventCategory: 'test',
        eventAction: 'test'
      });
    }
  });
})(window, jQuery);

浏览器会发出popstate事件,如果你通过你的应用程序调用导航

window.history.pushState({},'','/to')

如果您手动在地址栏中输入地址并单击后退按钮,popstate事件将不会被触发。

如果你用这个简化的功能在应用中导航

const navigate = (to) => {
    window.history.pushState({}, ",", to);
  };

这样就可以了

const handlePopstate = () => {
  console.log("popped");
};
window.addEventListener("popstate", handlePopstate);

正在寻找这个问题的解决方案,并根据这里的一些答案和History.pushState()和WindowEventHandlers.onpopstate的MDN Web文档页面,将一个简单的骨架测试html放在一起。

下面的HTML和JavaScript很容易复制、粘贴和测试。

使用后退和前进浏览器按钮,快捷键,添加对URL的更改(这在某些情况下很重要)。

简单到可以向现有代码中添加关键点,并且应该是可扩展的。

<html>
<body>
<div id="p1">Option 1</div>
<div id="p2">Option 2</div>
<div id="p3">Option 3</div>
<div id="p4">Option 4</div>
<div id="c"></div>
<script>
var chg={
    set:function(str){
        var d=document.getElementById("c");
        d.textContent=str;
    },
    go:function(e){
        var s={"p":this.id};
        chg.set(s.p);
        hstry.add(s);
    }
};
var hstry={
    add:function(s){
        var u=new URL(window.location);
        u.searchParams.set("x",s.p);
        window.history.pushState(s,"",u);
    },
    adjust:function(state){
        if(state.p){
            chg.set(state.p);
        }
    }
};
window.onpopstate=function(e){
    console.log("popstate, e.state:["+ JSON.stringify(e.state) +"]");
    hstry.adjust(e.state);
}
window.onload=function(){
    var i,d,a=["p1","p2","p3","p4"];
    for(i=0;i<a.length;i++){
        d=document.getElementById(a[i]);
        d.addEventListener("click",chg.go,false);
    }
}
</script>
</body>
</html>