处理 Ionic3 PWA 后退按钮

Handling Ionic3 PWA back button

问题是当点击 phone/desktop 浏览器中的后退按钮时,PWA 将关闭,因为默认情况下 ionic3 PWA 没有处理后退按钮。我到处搜索可以处理 ionic3 PWA 后退按钮的解决方案,但我找不到目前可用的解决方案。

我在这里找到了解决方案:

但是我不知道如何在我的应用程序中修复它,因为我试图在我的应用程序初始化时将它放入我的代码中,现在它完全禁用了后退按钮,所以现在我正在寻求帮助。

我的代码在app.components.ts

  initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      this.statusBar.styleDefault();
      this.splashScreen.hide();

      //Back button handling
      window.addEventListener('load', function() {
        window.history.pushState({}, '')
      })

      window.addEventListener('load', function() {
        window.history.pushState({}, '')
      })

      window.addEventListener('popstate', function() {
        window.history.pushState({}, '')
      })

      window.addEventListener('load', function() {
        window.history.pushState({ noBackExitsApp: true }, '')
      })

      window.addEventListener('popstate', function(event) {
        if (event.state && event.state.noBackExitsApp) {
          window.history.pushState({ noBackExitsApp: true }, '')
        }
      })
    });
  }

解决方案(代码在app.components.ts)

    import { Platform, App, IonicApp, MenuController } from 'ionic-angular';
    import { StatusBar } from '@ionic-native/status-bar';
    import { SplashScreen } from '@ionic-native/splash-screen';

    constructor(
        platform: Platform, 
        statusBar: StatusBar, 
        splashScreen: SplashScreen,
        private app:App,
        private ionicApp: IonicApp,
        private menu: MenuController
    ) {

    }

  initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      this.statusBar.styleDefault();
      this.splashScreen.hide();
      this.setupBackButtonBehavior();
    });
  }

    setupBackButtonBehavior () {
    // If on web version (browser)
    if (window.location.protocol !== "file:") {
      // Register browser back button action(s)
      window.onpopstate = (evt) => {
                // Close menu if open
        if (this.menu.isOpen()) {
          this.menu.close ();
          return;
        }
        // Close any active modals or overlays
        let activePortal = this.ionicApp._loadingPortal.getActive() ||
          this.ionicApp._modalPortal.getActive() ||
          this.ionicApp._toastPortal.getActive() ||
          this.ionicApp._overlayPortal.getActive();
        if (activePortal) {
          activePortal.dismiss();
          return;
        }
        // Navigate back
        if (this.app.getRootNav().canGoBack()) this.app.getRootNav().pop();
      };
      // Fake browser history on each view enter
      this.app.viewDidEnter.subscribe((app) => {
        history.pushState (null, null, "");
      });
    }
  }