Android硬件后退按钮未触发“ popstate”

时间:2019-09-26 18:15:23

标签: javascript android google-chrome mobile

在移动SPA应用程序中,我已覆盖默认的后退行为以在页面之间进行切换。

        // create history states
        history.pushState(-1, null); // back state
        history.pushState(0, null); // main state
        history.pushState(1, null); // forward state
        history.go(-1); // start in main state
        window.addEventListener('popstate', function (event) {
            var state = event.state;
            if (state === -1) {                    
                if (!this.goBack()) {
                    return false;
                }

                // reset state to what it should be
                history.go(-state);
            }
        }, false);

除了某些Android设备上有硬件后退按钮(三星S5,BlackBerry Key 2是我正在测试的两个设备)之外,这对所有移动设备都适用。当按下硬件后退按钮时,从不会调用popstate事件,因此用户会从应用程序中退出,而不是返回页面。有没有已知的方法可以通过Javascript拦截此硬件后退按钮?

需要明确的是,后退在所有设备上都可以正常工作,除了那些带有硬件后退按钮(不是像Android 10那样的软按钮或向后滑动)的设备,这些设备似乎不会触发历史记录popstate事件。

1 个答案:

答案 0 :(得分:1)

我知道两种方法,但是它们依赖于第三方框架:

1。 jQuery mobile

  $(window).on("navigate", function(event, data){
      if(direction == "back") {
          // back
      } elseif(direction == "forward") {
          // forward
      }
  });

2。反应原生

为此目的,它提供了BackHandler

BackHandler.addEventListener('hardwareBackPress', function() {
    // this.onMainScreen and this.goBack are just examples, you need to use your own implementation here
    // Typically you would use the navigator here to go to the last state.

    if(!this.onMainScreen()) {
        this.goBack();
        return true;
    }
    return false;
});

如果使用这样的框架对您来说不是问题,那么您最好去做,因为他们在跨浏览器支持和即将进行的更改/添加方面投入了大量精力。我可以自己推荐jQuery mobile。