Ionic and onbeforeunload

I’m trying to get the browser back button to be reasonable when running in a web browser. I’m defaulting to having no routes/deep-links, so the whole SPA is essentially the same URL. If the user clicks the back button (which is very normal), I want to just warn them that they’re leaving the site.

I can hook up the onbeforeunload, and it does get hit, but unfortunately returning a text string doesn’t trigger the normal visual warning. Is there anything in Ionic that’s preventing this event from warning the user? Any other suggestions on warning on browser back button use?

window.onbeforeunload = () => {
    this.loggingService.info("user navigating away from page");

    //If user logged in, warn them before leaving
    if (this.auth.user) {
      return 'Leaving the site?  If not, please use the in-app navigation and not the back button.';
    }
}

A slight tweak to the onbeforeunload implementation got it to work in Chrome. I also am using the onhashchange to try to detect other back button use. Full implementation is below for anyone else who is in a similar boat. Seems to be a reasonable result until the lazy-loading/routing/nav pieces are worked out and stable.

listenToWebEvents() {
  window.onbeforeunload = (e) => {
    this.loggingService.info("user navigating away from page");

    //If user is logged in, warn them before leaving
    if (this.auth.user) {
      var warnText = 'Leaving the site?  If not, please use the in-app navigation and not the back button.';
      e.returnValue = warnText;
      return warnText;
    }
  };

  window.onhashchange = (e) => {
    this.loggingService.info("user changing hash/url values");

    //If user is logged in, warn them since they may be using the back button here
    if (this.auth.user) {
      //Present an alert
      var navWarningAlert = this.alertCtrl.create({
        title: 'Navigation Warning',
        message: 'Using the back button?  If so, please use the in-app navigation and not the back button.',
        buttons: ['Dismiss']
      });
      navWarningAlert.present();
    }
  };
}
1 Like